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/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/Config/llvm-config.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/Constant.h"
90 #include "llvm/IR/ConstantRange.h"
91 #include "llvm/IR/Constants.h"
92 #include "llvm/IR/DataLayout.h"
93 #include "llvm/IR/DerivedTypes.h"
94 #include "llvm/IR/Dominators.h"
95 #include "llvm/IR/Function.h"
96 #include "llvm/IR/GlobalAlias.h"
97 #include "llvm/IR/GlobalValue.h"
98 #include "llvm/IR/InstIterator.h"
99 #include "llvm/IR/InstrTypes.h"
100 #include "llvm/IR/Instruction.h"
101 #include "llvm/IR/Instructions.h"
102 #include "llvm/IR/IntrinsicInst.h"
103 #include "llvm/IR/Intrinsics.h"
104 #include "llvm/IR/LLVMContext.h"
105 #include "llvm/IR/Operator.h"
106 #include "llvm/IR/PatternMatch.h"
107 #include "llvm/IR/Type.h"
108 #include "llvm/IR/Use.h"
109 #include "llvm/IR/User.h"
110 #include "llvm/IR/Value.h"
111 #include "llvm/IR/Verifier.h"
112 #include "llvm/InitializePasses.h"
113 #include "llvm/Pass.h"
114 #include "llvm/Support/Casting.h"
115 #include "llvm/Support/CommandLine.h"
116 #include "llvm/Support/Compiler.h"
117 #include "llvm/Support/Debug.h"
118 #include "llvm/Support/ErrorHandling.h"
119 #include "llvm/Support/KnownBits.h"
120 #include "llvm/Support/SaveAndRestore.h"
121 #include "llvm/Support/raw_ostream.h"
122 #include <algorithm>
123 #include <cassert>
124 #include <climits>
125 #include <cstdint>
126 #include <cstdlib>
127 #include <map>
128 #include <memory>
129 #include <tuple>
130 #include <utility>
131 #include <vector>
132 
133 using namespace llvm;
134 using namespace PatternMatch;
135 
136 #define DEBUG_TYPE "scalar-evolution"
137 
138 STATISTIC(NumTripCountsComputed,
139           "Number of loops with predictable loop counts");
140 STATISTIC(NumTripCountsNotComputed,
141           "Number of loops without predictable loop counts");
142 STATISTIC(NumBruteForceTripCountsComputed,
143           "Number of loops with trip counts computed by force");
144 
145 #ifdef EXPENSIVE_CHECKS
146 bool llvm::VerifySCEV = true;
147 #else
148 bool llvm::VerifySCEV = false;
149 #endif
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 static cl::opt<bool, true> VerifySCEVOpt(
160     "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163     "verify-scev-strict", cl::Hidden,
164     cl::desc("Enable stricter verification with -verify-scev is passed"));
165 static cl::opt<bool>
166     VerifySCEVMap("verify-scev-maps", cl::Hidden,
167                   cl::desc("Verify no dangling value in ScalarEvolution's "
168                            "ExprValueMap (slow)"));
169 
170 static cl::opt<bool> VerifyIR(
171     "scev-verify-ir", cl::Hidden,
172     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
173     cl::init(false));
174 
175 static cl::opt<unsigned> MulOpsInlineThreshold(
176     "scev-mulops-inline-threshold", cl::Hidden,
177     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> AddOpsInlineThreshold(
181     "scev-addops-inline-threshold", cl::Hidden,
182     cl::desc("Threshold for inlining addition operands into a SCEV"),
183     cl::init(500));
184 
185 static cl::opt<unsigned> MaxSCEVCompareDepth(
186     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
188     cl::init(32));
189 
190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
191     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
192     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
193     cl::init(2));
194 
195 static cl::opt<unsigned> MaxValueCompareDepth(
196     "scalar-evolution-max-value-compare-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive value complexity comparisons"),
198     cl::init(2));
199 
200 static cl::opt<unsigned>
201     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
202                   cl::desc("Maximum depth of recursive arithmetics"),
203                   cl::init(32));
204 
205 static cl::opt<unsigned> MaxConstantEvolvingDepth(
206     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
207     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208 
209 static cl::opt<unsigned>
210     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
211                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
212                  cl::init(8));
213 
214 static cl::opt<unsigned>
215     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
216                   cl::desc("Max coefficients in AddRec during evolving"),
217                   cl::init(8));
218 
219 static cl::opt<unsigned>
220     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
221                   cl::desc("Size of the expression which is considered huge"),
222                   cl::init(4096));
223 
224 static cl::opt<bool>
225 ClassifyExpressions("scalar-evolution-classify-expressions",
226     cl::Hidden, cl::init(true),
227     cl::desc("When printing analysis, include information on every instruction"));
228 
229 static cl::opt<bool> UseExpensiveRangeSharpening(
230     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
231     cl::init(false),
232     cl::desc("Use more powerful methods of sharpening expression ranges. May "
233              "be costly in terms of compile time"));
234 
235 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
236     "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
237     cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
238              "Phi strongly connected components"),
239     cl::init(8));
240 
241 static cl::opt<bool>
242     EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
243                             cl::desc("Handle <= and >= in finite loops"),
244                             cl::init(true));
245 
246 //===----------------------------------------------------------------------===//
247 //                           SCEV class definitions
248 //===----------------------------------------------------------------------===//
249 
250 //===----------------------------------------------------------------------===//
251 // Implementation of the SCEV class.
252 //
253 
254 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
255 LLVM_DUMP_METHOD void SCEV::dump() const {
256   print(dbgs());
257   dbgs() << '\n';
258 }
259 #endif
260 
261 void SCEV::print(raw_ostream &OS) const {
262   switch (getSCEVType()) {
263   case scConstant:
264     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
265     return;
266   case scPtrToInt: {
267     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
268     const SCEV *Op = PtrToInt->getOperand();
269     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
270        << *PtrToInt->getType() << ")";
271     return;
272   }
273   case scTruncate: {
274     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
275     const SCEV *Op = Trunc->getOperand();
276     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
277        << *Trunc->getType() << ")";
278     return;
279   }
280   case scZeroExtend: {
281     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
282     const SCEV *Op = ZExt->getOperand();
283     OS << "(zext " << *Op->getType() << " " << *Op << " to "
284        << *ZExt->getType() << ")";
285     return;
286   }
287   case scSignExtend: {
288     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
289     const SCEV *Op = SExt->getOperand();
290     OS << "(sext " << *Op->getType() << " " << *Op << " to "
291        << *SExt->getType() << ")";
292     return;
293   }
294   case scAddRecExpr: {
295     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
296     OS << "{" << *AR->getOperand(0);
297     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
298       OS << ",+," << *AR->getOperand(i);
299     OS << "}<";
300     if (AR->hasNoUnsignedWrap())
301       OS << "nuw><";
302     if (AR->hasNoSignedWrap())
303       OS << "nsw><";
304     if (AR->hasNoSelfWrap() &&
305         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
306       OS << "nw><";
307     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
308     OS << ">";
309     return;
310   }
311   case scAddExpr:
312   case scMulExpr:
313   case scUMaxExpr:
314   case scSMaxExpr:
315   case scUMinExpr:
316   case scSMinExpr:
317   case scSequentialUMinExpr: {
318     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
319     const char *OpStr = nullptr;
320     switch (NAry->getSCEVType()) {
321     case scAddExpr: OpStr = " + "; break;
322     case scMulExpr: OpStr = " * "; break;
323     case scUMaxExpr: OpStr = " umax "; break;
324     case scSMaxExpr: OpStr = " smax "; break;
325     case scUMinExpr:
326       OpStr = " umin ";
327       break;
328     case scSMinExpr:
329       OpStr = " smin ";
330       break;
331     case scSequentialUMinExpr:
332       OpStr = " umin_seq ";
333       break;
334     default:
335       llvm_unreachable("There are no other nary expression types.");
336     }
337     OS << "(";
338     ListSeparator LS(OpStr);
339     for (const SCEV *Op : NAry->operands())
340       OS << LS << *Op;
341     OS << ")";
342     switch (NAry->getSCEVType()) {
343     case scAddExpr:
344     case scMulExpr:
345       if (NAry->hasNoUnsignedWrap())
346         OS << "<nuw>";
347       if (NAry->hasNoSignedWrap())
348         OS << "<nsw>";
349       break;
350     default:
351       // Nothing to print for other nary expressions.
352       break;
353     }
354     return;
355   }
356   case scUDivExpr: {
357     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
358     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
359     return;
360   }
361   case scUnknown: {
362     const SCEVUnknown *U = cast<SCEVUnknown>(this);
363     Type *AllocTy;
364     if (U->isSizeOf(AllocTy)) {
365       OS << "sizeof(" << *AllocTy << ")";
366       return;
367     }
368     if (U->isAlignOf(AllocTy)) {
369       OS << "alignof(" << *AllocTy << ")";
370       return;
371     }
372 
373     Type *CTy;
374     Constant *FieldNo;
375     if (U->isOffsetOf(CTy, FieldNo)) {
376       OS << "offsetof(" << *CTy << ", ";
377       FieldNo->printAsOperand(OS, false);
378       OS << ")";
379       return;
380     }
381 
382     // Otherwise just print it normally.
383     U->getValue()->printAsOperand(OS, false);
384     return;
385   }
386   case scCouldNotCompute:
387     OS << "***COULDNOTCOMPUTE***";
388     return;
389   }
390   llvm_unreachable("Unknown SCEV kind!");
391 }
392 
393 Type *SCEV::getType() const {
394   switch (getSCEVType()) {
395   case scConstant:
396     return cast<SCEVConstant>(this)->getType();
397   case scPtrToInt:
398   case scTruncate:
399   case scZeroExtend:
400   case scSignExtend:
401     return cast<SCEVCastExpr>(this)->getType();
402   case scAddRecExpr:
403     return cast<SCEVAddRecExpr>(this)->getType();
404   case scMulExpr:
405     return cast<SCEVMulExpr>(this)->getType();
406   case scUMaxExpr:
407   case scSMaxExpr:
408   case scUMinExpr:
409   case scSMinExpr:
410     return cast<SCEVMinMaxExpr>(this)->getType();
411   case scSequentialUMinExpr:
412     return cast<SCEVSequentialMinMaxExpr>(this)->getType();
413   case scAddExpr:
414     return cast<SCEVAddExpr>(this)->getType();
415   case scUDivExpr:
416     return cast<SCEVUDivExpr>(this)->getType();
417   case scUnknown:
418     return cast<SCEVUnknown>(this)->getType();
419   case scCouldNotCompute:
420     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
421   }
422   llvm_unreachable("Unknown SCEV kind!");
423 }
424 
425 bool SCEV::isZero() const {
426   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
427     return SC->getValue()->isZero();
428   return false;
429 }
430 
431 bool SCEV::isOne() const {
432   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
433     return SC->getValue()->isOne();
434   return false;
435 }
436 
437 bool SCEV::isAllOnesValue() const {
438   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
439     return SC->getValue()->isMinusOne();
440   return false;
441 }
442 
443 bool SCEV::isNonConstantNegative() const {
444   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
445   if (!Mul) return false;
446 
447   // If there is a constant factor, it will be first.
448   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
449   if (!SC) return false;
450 
451   // Return true if the value is negative, this matches things like (-42 * V).
452   return SC->getAPInt().isNegative();
453 }
454 
455 SCEVCouldNotCompute::SCEVCouldNotCompute() :
456   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
457 
458 bool SCEVCouldNotCompute::classof(const SCEV *S) {
459   return S->getSCEVType() == scCouldNotCompute;
460 }
461 
462 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
463   FoldingSetNodeID ID;
464   ID.AddInteger(scConstant);
465   ID.AddPointer(V);
466   void *IP = nullptr;
467   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
468   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
469   UniqueSCEVs.InsertNode(S, IP);
470   return S;
471 }
472 
473 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
474   return getConstant(ConstantInt::get(getContext(), Val));
475 }
476 
477 const SCEV *
478 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
479   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
480   return getConstant(ConstantInt::get(ITy, V, isSigned));
481 }
482 
483 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
484                            const SCEV *op, Type *ty)
485     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
486   Operands[0] = op;
487 }
488 
489 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
490                                    Type *ITy)
491     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
492   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
493          "Must be a non-bit-width-changing pointer-to-integer cast!");
494 }
495 
496 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
497                                            SCEVTypes SCEVTy, const SCEV *op,
498                                            Type *ty)
499     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
500 
501 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
502                                    Type *ty)
503     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
504   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
505          "Cannot truncate non-integer value!");
506 }
507 
508 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
509                                        const SCEV *op, Type *ty)
510     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
511   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
512          "Cannot zero extend non-integer value!");
513 }
514 
515 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
516                                        const SCEV *op, Type *ty)
517     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
518   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
519          "Cannot sign extend non-integer value!");
520 }
521 
522 void SCEVUnknown::deleted() {
523   // Clear this SCEVUnknown from various maps.
524   SE->forgetMemoizedResults(this);
525 
526   // Remove this SCEVUnknown from the uniquing map.
527   SE->UniqueSCEVs.RemoveNode(this);
528 
529   // Release the value.
530   setValPtr(nullptr);
531 }
532 
533 void SCEVUnknown::allUsesReplacedWith(Value *New) {
534   // Clear this SCEVUnknown from various maps.
535   SE->forgetMemoizedResults(this);
536 
537   // Remove this SCEVUnknown from the uniquing map.
538   SE->UniqueSCEVs.RemoveNode(this);
539 
540   // Replace the value pointer in case someone is still using this SCEVUnknown.
541   setValPtr(New);
542 }
543 
544 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
545   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
546     if (VCE->getOpcode() == Instruction::PtrToInt)
547       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
548         if (CE->getOpcode() == Instruction::GetElementPtr &&
549             CE->getOperand(0)->isNullValue() &&
550             CE->getNumOperands() == 2)
551           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
552             if (CI->isOne()) {
553               AllocTy = cast<GEPOperator>(CE)->getSourceElementType();
554               return true;
555             }
556 
557   return false;
558 }
559 
560 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
561   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
562     if (VCE->getOpcode() == Instruction::PtrToInt)
563       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
564         if (CE->getOpcode() == Instruction::GetElementPtr &&
565             CE->getOperand(0)->isNullValue()) {
566           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
567           if (StructType *STy = dyn_cast<StructType>(Ty))
568             if (!STy->isPacked() &&
569                 CE->getNumOperands() == 3 &&
570                 CE->getOperand(1)->isNullValue()) {
571               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
572                 if (CI->isOne() &&
573                     STy->getNumElements() == 2 &&
574                     STy->getElementType(0)->isIntegerTy(1)) {
575                   AllocTy = STy->getElementType(1);
576                   return true;
577                 }
578             }
579         }
580 
581   return false;
582 }
583 
584 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
585   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
586     if (VCE->getOpcode() == Instruction::PtrToInt)
587       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
588         if (CE->getOpcode() == Instruction::GetElementPtr &&
589             CE->getNumOperands() == 3 &&
590             CE->getOperand(0)->isNullValue() &&
591             CE->getOperand(1)->isNullValue()) {
592           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
593           // Ignore vector types here so that ScalarEvolutionExpander doesn't
594           // emit getelementptrs that index into vectors.
595           if (Ty->isStructTy() || Ty->isArrayTy()) {
596             CTy = Ty;
597             FieldNo = CE->getOperand(2);
598             return true;
599           }
600         }
601 
602   return false;
603 }
604 
605 //===----------------------------------------------------------------------===//
606 //                               SCEV Utilities
607 //===----------------------------------------------------------------------===//
608 
609 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
610 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
611 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
612 /// have been previously deemed to be "equally complex" by this routine.  It is
613 /// intended to avoid exponential time complexity in cases like:
614 ///
615 ///   %a = f(%x, %y)
616 ///   %b = f(%a, %a)
617 ///   %c = f(%b, %b)
618 ///
619 ///   %d = f(%x, %y)
620 ///   %e = f(%d, %d)
621 ///   %f = f(%e, %e)
622 ///
623 ///   CompareValueComplexity(%f, %c)
624 ///
625 /// Since we do not continue running this routine on expression trees once we
626 /// have seen unequal values, there is no need to track them in the cache.
627 static int
628 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
629                        const LoopInfo *const LI, Value *LV, Value *RV,
630                        unsigned Depth) {
631   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
632     return 0;
633 
634   // Order pointer values after integer values. This helps SCEVExpander form
635   // GEPs.
636   bool LIsPointer = LV->getType()->isPointerTy(),
637        RIsPointer = RV->getType()->isPointerTy();
638   if (LIsPointer != RIsPointer)
639     return (int)LIsPointer - (int)RIsPointer;
640 
641   // Compare getValueID values.
642   unsigned LID = LV->getValueID(), RID = RV->getValueID();
643   if (LID != RID)
644     return (int)LID - (int)RID;
645 
646   // Sort arguments by their position.
647   if (const auto *LA = dyn_cast<Argument>(LV)) {
648     const auto *RA = cast<Argument>(RV);
649     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
650     return (int)LArgNo - (int)RArgNo;
651   }
652 
653   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
654     const auto *RGV = cast<GlobalValue>(RV);
655 
656     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
657       auto LT = GV->getLinkage();
658       return !(GlobalValue::isPrivateLinkage(LT) ||
659                GlobalValue::isInternalLinkage(LT));
660     };
661 
662     // Use the names to distinguish the two values, but only if the
663     // names are semantically important.
664     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
665       return LGV->getName().compare(RGV->getName());
666   }
667 
668   // For instructions, compare their loop depth, and their operand count.  This
669   // is pretty loose.
670   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
671     const auto *RInst = cast<Instruction>(RV);
672 
673     // Compare loop depths.
674     const BasicBlock *LParent = LInst->getParent(),
675                      *RParent = RInst->getParent();
676     if (LParent != RParent) {
677       unsigned LDepth = LI->getLoopDepth(LParent),
678                RDepth = LI->getLoopDepth(RParent);
679       if (LDepth != RDepth)
680         return (int)LDepth - (int)RDepth;
681     }
682 
683     // Compare the number of operands.
684     unsigned LNumOps = LInst->getNumOperands(),
685              RNumOps = RInst->getNumOperands();
686     if (LNumOps != RNumOps)
687       return (int)LNumOps - (int)RNumOps;
688 
689     for (unsigned Idx : seq(0u, LNumOps)) {
690       int Result =
691           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
692                                  RInst->getOperand(Idx), Depth + 1);
693       if (Result != 0)
694         return Result;
695     }
696   }
697 
698   EqCacheValue.unionSets(LV, RV);
699   return 0;
700 }
701 
702 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
703 // than RHS, respectively. A three-way result allows recursive comparisons to be
704 // more efficient.
705 // If the max analysis depth was reached, return None, assuming we do not know
706 // if they are equivalent for sure.
707 static Optional<int>
708 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
709                       EquivalenceClasses<const Value *> &EqCacheValue,
710                       const LoopInfo *const LI, const SCEV *LHS,
711                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
712   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
713   if (LHS == RHS)
714     return 0;
715 
716   // Primarily, sort the SCEVs by their getSCEVType().
717   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
718   if (LType != RType)
719     return (int)LType - (int)RType;
720 
721   if (EqCacheSCEV.isEquivalent(LHS, RHS))
722     return 0;
723 
724   if (Depth > MaxSCEVCompareDepth)
725     return None;
726 
727   // Aside from the getSCEVType() ordering, the particular ordering
728   // isn't very important except that it's beneficial to be consistent,
729   // so that (a + b) and (b + a) don't end up as different expressions.
730   switch (LType) {
731   case scUnknown: {
732     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
733     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
734 
735     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
736                                    RU->getValue(), Depth + 1);
737     if (X == 0)
738       EqCacheSCEV.unionSets(LHS, RHS);
739     return X;
740   }
741 
742   case scConstant: {
743     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
744     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
745 
746     // Compare constant values.
747     const APInt &LA = LC->getAPInt();
748     const APInt &RA = RC->getAPInt();
749     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
750     if (LBitWidth != RBitWidth)
751       return (int)LBitWidth - (int)RBitWidth;
752     return LA.ult(RA) ? -1 : 1;
753   }
754 
755   case scAddRecExpr: {
756     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
757     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
758 
759     // There is always a dominance between two recs that are used by one SCEV,
760     // so we can safely sort recs by loop header dominance. We require such
761     // order in getAddExpr.
762     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
763     if (LLoop != RLoop) {
764       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
765       assert(LHead != RHead && "Two loops share the same header?");
766       if (DT.dominates(LHead, RHead))
767         return 1;
768       else
769         assert(DT.dominates(RHead, LHead) &&
770                "No dominance between recurrences used by one SCEV?");
771       return -1;
772     }
773 
774     // Addrec complexity grows with operand count.
775     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
776     if (LNumOps != RNumOps)
777       return (int)LNumOps - (int)RNumOps;
778 
779     // Lexicographically compare.
780     for (unsigned i = 0; i != LNumOps; ++i) {
781       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
782                                      LA->getOperand(i), RA->getOperand(i), DT,
783                                      Depth + 1);
784       if (X != 0)
785         return X;
786     }
787     EqCacheSCEV.unionSets(LHS, RHS);
788     return 0;
789   }
790 
791   case scAddExpr:
792   case scMulExpr:
793   case scSMaxExpr:
794   case scUMaxExpr:
795   case scSMinExpr:
796   case scUMinExpr:
797   case scSequentialUMinExpr: {
798     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
799     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
800 
801     // Lexicographically compare n-ary expressions.
802     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
803     if (LNumOps != RNumOps)
804       return (int)LNumOps - (int)RNumOps;
805 
806     for (unsigned i = 0; i != LNumOps; ++i) {
807       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
808                                      LC->getOperand(i), RC->getOperand(i), DT,
809                                      Depth + 1);
810       if (X != 0)
811         return X;
812     }
813     EqCacheSCEV.unionSets(LHS, RHS);
814     return 0;
815   }
816 
817   case scUDivExpr: {
818     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
819     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
820 
821     // Lexicographically compare udiv expressions.
822     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
823                                    RC->getLHS(), DT, Depth + 1);
824     if (X != 0)
825       return X;
826     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
827                               RC->getRHS(), DT, Depth + 1);
828     if (X == 0)
829       EqCacheSCEV.unionSets(LHS, RHS);
830     return X;
831   }
832 
833   case scPtrToInt:
834   case scTruncate:
835   case scZeroExtend:
836   case scSignExtend: {
837     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
838     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
839 
840     // Compare cast expressions by operand.
841     auto X =
842         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
843                               RC->getOperand(), DT, Depth + 1);
844     if (X == 0)
845       EqCacheSCEV.unionSets(LHS, RHS);
846     return X;
847   }
848 
849   case scCouldNotCompute:
850     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
851   }
852   llvm_unreachable("Unknown SCEV kind!");
853 }
854 
855 /// Given a list of SCEV objects, order them by their complexity, and group
856 /// objects of the same complexity together by value.  When this routine is
857 /// finished, we know that any duplicates in the vector are consecutive and that
858 /// complexity is monotonically increasing.
859 ///
860 /// Note that we go take special precautions to ensure that we get deterministic
861 /// results from this routine.  In other words, we don't want the results of
862 /// this to depend on where the addresses of various SCEV objects happened to
863 /// land in memory.
864 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
865                               LoopInfo *LI, DominatorTree &DT) {
866   if (Ops.size() < 2) return;  // Noop
867 
868   EquivalenceClasses<const SCEV *> EqCacheSCEV;
869   EquivalenceClasses<const Value *> EqCacheValue;
870 
871   // Whether LHS has provably less complexity than RHS.
872   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
873     auto Complexity =
874         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
875     return Complexity && *Complexity < 0;
876   };
877   if (Ops.size() == 2) {
878     // This is the common case, which also happens to be trivially simple.
879     // Special case it.
880     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
881     if (IsLessComplex(RHS, LHS))
882       std::swap(LHS, RHS);
883     return;
884   }
885 
886   // Do the rough sort by complexity.
887   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
888     return IsLessComplex(LHS, RHS);
889   });
890 
891   // Now that we are sorted by complexity, group elements of the same
892   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
893   // be extremely short in practice.  Note that we take this approach because we
894   // do not want to depend on the addresses of the objects we are grouping.
895   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
896     const SCEV *S = Ops[i];
897     unsigned Complexity = S->getSCEVType();
898 
899     // If there are any objects of the same complexity and same value as this
900     // one, group them.
901     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
902       if (Ops[j] == S) { // Found a duplicate.
903         // Move it to immediately after i'th element.
904         std::swap(Ops[i+1], Ops[j]);
905         ++i;   // no need to rescan it.
906         if (i == e-2) return;  // Done!
907       }
908     }
909   }
910 }
911 
912 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
913 /// least HugeExprThreshold nodes).
914 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
915   return any_of(Ops, [](const SCEV *S) {
916     return S->getExpressionSize() >= HugeExprThreshold;
917   });
918 }
919 
920 //===----------------------------------------------------------------------===//
921 //                      Simple SCEV method implementations
922 //===----------------------------------------------------------------------===//
923 
924 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
925 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
926                                        ScalarEvolution &SE,
927                                        Type *ResultTy) {
928   // Handle the simplest case efficiently.
929   if (K == 1)
930     return SE.getTruncateOrZeroExtend(It, ResultTy);
931 
932   // We are using the following formula for BC(It, K):
933   //
934   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
935   //
936   // Suppose, W is the bitwidth of the return value.  We must be prepared for
937   // overflow.  Hence, we must assure that the result of our computation is
938   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
939   // safe in modular arithmetic.
940   //
941   // However, this code doesn't use exactly that formula; the formula it uses
942   // is something like the following, where T is the number of factors of 2 in
943   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
944   // exponentiation:
945   //
946   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
947   //
948   // This formula is trivially equivalent to the previous formula.  However,
949   // this formula can be implemented much more efficiently.  The trick is that
950   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
951   // arithmetic.  To do exact division in modular arithmetic, all we have
952   // to do is multiply by the inverse.  Therefore, this step can be done at
953   // width W.
954   //
955   // The next issue is how to safely do the division by 2^T.  The way this
956   // is done is by doing the multiplication step at a width of at least W + T
957   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
958   // when we perform the division by 2^T (which is equivalent to a right shift
959   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
960   // truncated out after the division by 2^T.
961   //
962   // In comparison to just directly using the first formula, this technique
963   // is much more efficient; using the first formula requires W * K bits,
964   // but this formula less than W + K bits. Also, the first formula requires
965   // a division step, whereas this formula only requires multiplies and shifts.
966   //
967   // It doesn't matter whether the subtraction step is done in the calculation
968   // width or the input iteration count's width; if the subtraction overflows,
969   // the result must be zero anyway.  We prefer here to do it in the width of
970   // the induction variable because it helps a lot for certain cases; CodeGen
971   // isn't smart enough to ignore the overflow, which leads to much less
972   // efficient code if the width of the subtraction is wider than the native
973   // register width.
974   //
975   // (It's possible to not widen at all by pulling out factors of 2 before
976   // the multiplication; for example, K=2 can be calculated as
977   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
978   // extra arithmetic, so it's not an obvious win, and it gets
979   // much more complicated for K > 3.)
980 
981   // Protection from insane SCEVs; this bound is conservative,
982   // but it probably doesn't matter.
983   if (K > 1000)
984     return SE.getCouldNotCompute();
985 
986   unsigned W = SE.getTypeSizeInBits(ResultTy);
987 
988   // Calculate K! / 2^T and T; we divide out the factors of two before
989   // multiplying for calculating K! / 2^T to avoid overflow.
990   // Other overflow doesn't matter because we only care about the bottom
991   // W bits of the result.
992   APInt OddFactorial(W, 1);
993   unsigned T = 1;
994   for (unsigned i = 3; i <= K; ++i) {
995     APInt Mult(W, i);
996     unsigned TwoFactors = Mult.countTrailingZeros();
997     T += TwoFactors;
998     Mult.lshrInPlace(TwoFactors);
999     OddFactorial *= Mult;
1000   }
1001 
1002   // We need at least W + T bits for the multiplication step
1003   unsigned CalculationBits = W + T;
1004 
1005   // Calculate 2^T, at width T+W.
1006   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1007 
1008   // Calculate the multiplicative inverse of K! / 2^T;
1009   // this multiplication factor will perform the exact division by
1010   // K! / 2^T.
1011   APInt Mod = APInt::getSignedMinValue(W+1);
1012   APInt MultiplyFactor = OddFactorial.zext(W+1);
1013   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1014   MultiplyFactor = MultiplyFactor.trunc(W);
1015 
1016   // Calculate the product, at width T+W
1017   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1018                                                       CalculationBits);
1019   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1020   for (unsigned i = 1; i != K; ++i) {
1021     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1022     Dividend = SE.getMulExpr(Dividend,
1023                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1024   }
1025 
1026   // Divide by 2^T
1027   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1028 
1029   // Truncate the result, and divide by K! / 2^T.
1030 
1031   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1032                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1033 }
1034 
1035 /// Return the value of this chain of recurrences at the specified iteration
1036 /// number.  We can evaluate this recurrence by multiplying each element in the
1037 /// chain by the binomial coefficient corresponding to it.  In other words, we
1038 /// can evaluate {A,+,B,+,C,+,D} as:
1039 ///
1040 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1041 ///
1042 /// where BC(It, k) stands for binomial coefficient.
1043 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1044                                                 ScalarEvolution &SE) const {
1045   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1046 }
1047 
1048 const SCEV *
1049 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1050                                     const SCEV *It, ScalarEvolution &SE) {
1051   assert(Operands.size() > 0);
1052   const SCEV *Result = Operands[0];
1053   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1054     // The computation is correct in the face of overflow provided that the
1055     // multiplication is performed _after_ the evaluation of the binomial
1056     // coefficient.
1057     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1058     if (isa<SCEVCouldNotCompute>(Coeff))
1059       return Coeff;
1060 
1061     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1062   }
1063   return Result;
1064 }
1065 
1066 //===----------------------------------------------------------------------===//
1067 //                    SCEV Expression folder implementations
1068 //===----------------------------------------------------------------------===//
1069 
1070 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1071                                                      unsigned Depth) {
1072   assert(Depth <= 1 &&
1073          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1074 
1075   // We could be called with an integer-typed operands during SCEV rewrites.
1076   // Since the operand is an integer already, just perform zext/trunc/self cast.
1077   if (!Op->getType()->isPointerTy())
1078     return Op;
1079 
1080   // What would be an ID for such a SCEV cast expression?
1081   FoldingSetNodeID ID;
1082   ID.AddInteger(scPtrToInt);
1083   ID.AddPointer(Op);
1084 
1085   void *IP = nullptr;
1086 
1087   // Is there already an expression for such a cast?
1088   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1089     return S;
1090 
1091   // It isn't legal for optimizations to construct new ptrtoint expressions
1092   // for non-integral pointers.
1093   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1094     return getCouldNotCompute();
1095 
1096   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1097 
1098   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1099   // is sufficiently wide to represent all possible pointer values.
1100   // We could theoretically teach SCEV to truncate wider pointers, but
1101   // that isn't implemented for now.
1102   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1103       getDataLayout().getTypeSizeInBits(IntPtrTy))
1104     return getCouldNotCompute();
1105 
1106   // If not, is this expression something we can't reduce any further?
1107   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1108     // Perform some basic constant folding. If the operand of the ptr2int cast
1109     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1110     // left as-is), but produce a zero constant.
1111     // NOTE: We could handle a more general case, but lack motivational cases.
1112     if (isa<ConstantPointerNull>(U->getValue()))
1113       return getZero(IntPtrTy);
1114 
1115     // Create an explicit cast node.
1116     // We can reuse the existing insert position since if we get here,
1117     // we won't have made any changes which would invalidate it.
1118     SCEV *S = new (SCEVAllocator)
1119         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1120     UniqueSCEVs.InsertNode(S, IP);
1121     registerUser(S, Op);
1122     return S;
1123   }
1124 
1125   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1126                        "non-SCEVUnknown's.");
1127 
1128   // Otherwise, we've got some expression that is more complex than just a
1129   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1130   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1131   // only, and the expressions must otherwise be integer-typed.
1132   // So sink the cast down to the SCEVUnknown's.
1133 
1134   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1135   /// which computes a pointer-typed value, and rewrites the whole expression
1136   /// tree so that *all* the computations are done on integers, and the only
1137   /// pointer-typed operands in the expression are SCEVUnknown.
1138   class SCEVPtrToIntSinkingRewriter
1139       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1140     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1141 
1142   public:
1143     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1144 
1145     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1146       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1147       return Rewriter.visit(Scev);
1148     }
1149 
1150     const SCEV *visit(const SCEV *S) {
1151       Type *STy = S->getType();
1152       // If the expression is not pointer-typed, just keep it as-is.
1153       if (!STy->isPointerTy())
1154         return S;
1155       // Else, recursively sink the cast down into it.
1156       return Base::visit(S);
1157     }
1158 
1159     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1160       SmallVector<const SCEV *, 2> Operands;
1161       bool Changed = false;
1162       for (auto *Op : Expr->operands()) {
1163         Operands.push_back(visit(Op));
1164         Changed |= Op != Operands.back();
1165       }
1166       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1167     }
1168 
1169     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1170       SmallVector<const SCEV *, 2> Operands;
1171       bool Changed = false;
1172       for (auto *Op : Expr->operands()) {
1173         Operands.push_back(visit(Op));
1174         Changed |= Op != Operands.back();
1175       }
1176       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1177     }
1178 
1179     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1180       assert(Expr->getType()->isPointerTy() &&
1181              "Should only reach pointer-typed SCEVUnknown's.");
1182       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1183     }
1184   };
1185 
1186   // And actually perform the cast sinking.
1187   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1188   assert(IntOp->getType()->isIntegerTy() &&
1189          "We must have succeeded in sinking the cast, "
1190          "and ending up with an integer-typed expression!");
1191   return IntOp;
1192 }
1193 
1194 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1195   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1196 
1197   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1198   if (isa<SCEVCouldNotCompute>(IntOp))
1199     return IntOp;
1200 
1201   return getTruncateOrZeroExtend(IntOp, Ty);
1202 }
1203 
1204 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1205                                              unsigned Depth) {
1206   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1207          "This is not a truncating conversion!");
1208   assert(isSCEVable(Ty) &&
1209          "This is not a conversion to a SCEVable type!");
1210   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1211   Ty = getEffectiveSCEVType(Ty);
1212 
1213   FoldingSetNodeID ID;
1214   ID.AddInteger(scTruncate);
1215   ID.AddPointer(Op);
1216   ID.AddPointer(Ty);
1217   void *IP = nullptr;
1218   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1219 
1220   // Fold if the operand is constant.
1221   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1222     return getConstant(
1223       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1224 
1225   // trunc(trunc(x)) --> trunc(x)
1226   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1227     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1228 
1229   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1230   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1231     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1232 
1233   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1234   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1235     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1236 
1237   if (Depth > MaxCastDepth) {
1238     SCEV *S =
1239         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1240     UniqueSCEVs.InsertNode(S, IP);
1241     registerUser(S, Op);
1242     return S;
1243   }
1244 
1245   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1246   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1247   // if after transforming we have at most one truncate, not counting truncates
1248   // that replace other casts.
1249   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1250     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1251     SmallVector<const SCEV *, 4> Operands;
1252     unsigned numTruncs = 0;
1253     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1254          ++i) {
1255       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1256       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1257           isa<SCEVTruncateExpr>(S))
1258         numTruncs++;
1259       Operands.push_back(S);
1260     }
1261     if (numTruncs < 2) {
1262       if (isa<SCEVAddExpr>(Op))
1263         return getAddExpr(Operands);
1264       else if (isa<SCEVMulExpr>(Op))
1265         return getMulExpr(Operands);
1266       else
1267         llvm_unreachable("Unexpected SCEV type for Op.");
1268     }
1269     // Although we checked in the beginning that ID is not in the cache, it is
1270     // possible that during recursion and different modification ID was inserted
1271     // into the cache. So if we find it, just return it.
1272     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1273       return S;
1274   }
1275 
1276   // If the input value is a chrec scev, truncate the chrec's operands.
1277   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1278     SmallVector<const SCEV *, 4> Operands;
1279     for (const SCEV *Op : AddRec->operands())
1280       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1281     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1282   }
1283 
1284   // Return zero if truncating to known zeros.
1285   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1286   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1287     return getZero(Ty);
1288 
1289   // The cast wasn't folded; create an explicit cast node. We can reuse
1290   // the existing insert position since if we get here, we won't have
1291   // made any changes which would invalidate it.
1292   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1293                                                  Op, Ty);
1294   UniqueSCEVs.InsertNode(S, IP);
1295   registerUser(S, Op);
1296   return S;
1297 }
1298 
1299 // Get the limit of a recurrence such that incrementing by Step cannot cause
1300 // signed overflow as long as the value of the recurrence within the
1301 // loop does not exceed this limit before incrementing.
1302 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1303                                                  ICmpInst::Predicate *Pred,
1304                                                  ScalarEvolution *SE) {
1305   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1306   if (SE->isKnownPositive(Step)) {
1307     *Pred = ICmpInst::ICMP_SLT;
1308     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1309                            SE->getSignedRangeMax(Step));
1310   }
1311   if (SE->isKnownNegative(Step)) {
1312     *Pred = ICmpInst::ICMP_SGT;
1313     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1314                            SE->getSignedRangeMin(Step));
1315   }
1316   return nullptr;
1317 }
1318 
1319 // Get the limit of a recurrence such that incrementing by Step cannot cause
1320 // unsigned overflow as long as the value of the recurrence within the loop does
1321 // not exceed this limit before incrementing.
1322 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1323                                                    ICmpInst::Predicate *Pred,
1324                                                    ScalarEvolution *SE) {
1325   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1326   *Pred = ICmpInst::ICMP_ULT;
1327 
1328   return SE->getConstant(APInt::getMinValue(BitWidth) -
1329                          SE->getUnsignedRangeMax(Step));
1330 }
1331 
1332 namespace {
1333 
1334 struct ExtendOpTraitsBase {
1335   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1336                                                           unsigned);
1337 };
1338 
1339 // Used to make code generic over signed and unsigned overflow.
1340 template <typename ExtendOp> struct ExtendOpTraits {
1341   // Members present:
1342   //
1343   // static const SCEV::NoWrapFlags WrapType;
1344   //
1345   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1346   //
1347   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1348   //                                           ICmpInst::Predicate *Pred,
1349   //                                           ScalarEvolution *SE);
1350 };
1351 
1352 template <>
1353 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1354   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1355 
1356   static const GetExtendExprTy GetExtendExpr;
1357 
1358   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1359                                              ICmpInst::Predicate *Pred,
1360                                              ScalarEvolution *SE) {
1361     return getSignedOverflowLimitForStep(Step, Pred, SE);
1362   }
1363 };
1364 
1365 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1366     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1367 
1368 template <>
1369 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1370   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1371 
1372   static const GetExtendExprTy GetExtendExpr;
1373 
1374   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1375                                              ICmpInst::Predicate *Pred,
1376                                              ScalarEvolution *SE) {
1377     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1378   }
1379 };
1380 
1381 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1382     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1383 
1384 } // end anonymous namespace
1385 
1386 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1387 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1388 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1389 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1390 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1391 // expression "Step + sext/zext(PreIncAR)" is congruent with
1392 // "sext/zext(PostIncAR)"
1393 template <typename ExtendOpTy>
1394 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1395                                         ScalarEvolution *SE, unsigned Depth) {
1396   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1397   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1398 
1399   const Loop *L = AR->getLoop();
1400   const SCEV *Start = AR->getStart();
1401   const SCEV *Step = AR->getStepRecurrence(*SE);
1402 
1403   // Check for a simple looking step prior to loop entry.
1404   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1405   if (!SA)
1406     return nullptr;
1407 
1408   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1409   // subtraction is expensive. For this purpose, perform a quick and dirty
1410   // difference, by checking for Step in the operand list.
1411   SmallVector<const SCEV *, 4> DiffOps;
1412   for (const SCEV *Op : SA->operands())
1413     if (Op != Step)
1414       DiffOps.push_back(Op);
1415 
1416   if (DiffOps.size() == SA->getNumOperands())
1417     return nullptr;
1418 
1419   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1420   // `Step`:
1421 
1422   // 1. NSW/NUW flags on the step increment.
1423   auto PreStartFlags =
1424     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1425   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1426   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1427       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1428 
1429   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1430   // "S+X does not sign/unsign-overflow".
1431   //
1432 
1433   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1434   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1435       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1436     return PreStart;
1437 
1438   // 2. Direct overflow check on the step operation's expression.
1439   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1440   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1441   const SCEV *OperandExtendedStart =
1442       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1443                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1444   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1445     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1446       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1447       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1448       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1449       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1450     }
1451     return PreStart;
1452   }
1453 
1454   // 3. Loop precondition.
1455   ICmpInst::Predicate Pred;
1456   const SCEV *OverflowLimit =
1457       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1458 
1459   if (OverflowLimit &&
1460       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1461     return PreStart;
1462 
1463   return nullptr;
1464 }
1465 
1466 // Get the normalized zero or sign extended expression for this AddRec's Start.
1467 template <typename ExtendOpTy>
1468 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1469                                         ScalarEvolution *SE,
1470                                         unsigned Depth) {
1471   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1472 
1473   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1474   if (!PreStart)
1475     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1476 
1477   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1478                                              Depth),
1479                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1480 }
1481 
1482 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1483 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1484 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1485 //
1486 // Formally:
1487 //
1488 //     {S,+,X} == {S-T,+,X} + T
1489 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1490 //
1491 // If ({S-T,+,X} + T) does not overflow  ... (1)
1492 //
1493 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1494 //
1495 // If {S-T,+,X} does not overflow  ... (2)
1496 //
1497 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1498 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1499 //
1500 // If (S-T)+T does not overflow  ... (3)
1501 //
1502 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1503 //      == {Ext(S),+,Ext(X)} == LHS
1504 //
1505 // Thus, if (1), (2) and (3) are true for some T, then
1506 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1507 //
1508 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1509 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1510 // to check for (1) and (2).
1511 //
1512 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1513 // is `Delta` (defined below).
1514 template <typename ExtendOpTy>
1515 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1516                                                 const SCEV *Step,
1517                                                 const Loop *L) {
1518   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1519 
1520   // We restrict `Start` to a constant to prevent SCEV from spending too much
1521   // time here.  It is correct (but more expensive) to continue with a
1522   // non-constant `Start` and do a general SCEV subtraction to compute
1523   // `PreStart` below.
1524   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1525   if (!StartC)
1526     return false;
1527 
1528   APInt StartAI = StartC->getAPInt();
1529 
1530   for (unsigned Delta : {-2, -1, 1, 2}) {
1531     const SCEV *PreStart = getConstant(StartAI - Delta);
1532 
1533     FoldingSetNodeID ID;
1534     ID.AddInteger(scAddRecExpr);
1535     ID.AddPointer(PreStart);
1536     ID.AddPointer(Step);
1537     ID.AddPointer(L);
1538     void *IP = nullptr;
1539     const auto *PreAR =
1540       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1541 
1542     // Give up if we don't already have the add recurrence we need because
1543     // actually constructing an add recurrence is relatively expensive.
1544     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1545       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1546       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1547       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1548           DeltaS, &Pred, this);
1549       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1550         return true;
1551     }
1552   }
1553 
1554   return false;
1555 }
1556 
1557 // Finds an integer D for an expression (C + x + y + ...) such that the top
1558 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1559 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1560 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1561 // the (C + x + y + ...) expression is \p WholeAddExpr.
1562 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1563                                             const SCEVConstant *ConstantTerm,
1564                                             const SCEVAddExpr *WholeAddExpr) {
1565   const APInt &C = ConstantTerm->getAPInt();
1566   const unsigned BitWidth = C.getBitWidth();
1567   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1568   uint32_t TZ = BitWidth;
1569   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1570     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1571   if (TZ) {
1572     // Set D to be as many least significant bits of C as possible while still
1573     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1574     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1575   }
1576   return APInt(BitWidth, 0);
1577 }
1578 
1579 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1580 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1581 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1582 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1583 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1584                                             const APInt &ConstantStart,
1585                                             const SCEV *Step) {
1586   const unsigned BitWidth = ConstantStart.getBitWidth();
1587   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1588   if (TZ)
1589     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1590                          : ConstantStart;
1591   return APInt(BitWidth, 0);
1592 }
1593 
1594 const SCEV *
1595 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1596   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1597          "This is not an extending conversion!");
1598   assert(isSCEVable(Ty) &&
1599          "This is not a conversion to a SCEVable type!");
1600   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1601   Ty = getEffectiveSCEVType(Ty);
1602 
1603   // Fold if the operand is constant.
1604   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1605     return getConstant(
1606       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1607 
1608   // zext(zext(x)) --> zext(x)
1609   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1610     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1611 
1612   // Before doing any expensive analysis, check to see if we've already
1613   // computed a SCEV for this Op and Ty.
1614   FoldingSetNodeID ID;
1615   ID.AddInteger(scZeroExtend);
1616   ID.AddPointer(Op);
1617   ID.AddPointer(Ty);
1618   void *IP = nullptr;
1619   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1620   if (Depth > MaxCastDepth) {
1621     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1622                                                      Op, Ty);
1623     UniqueSCEVs.InsertNode(S, IP);
1624     registerUser(S, Op);
1625     return S;
1626   }
1627 
1628   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1629   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1630     // It's possible the bits taken off by the truncate were all zero bits. If
1631     // so, we should be able to simplify this further.
1632     const SCEV *X = ST->getOperand();
1633     ConstantRange CR = getUnsignedRange(X);
1634     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1635     unsigned NewBits = getTypeSizeInBits(Ty);
1636     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1637             CR.zextOrTrunc(NewBits)))
1638       return getTruncateOrZeroExtend(X, Ty, Depth);
1639   }
1640 
1641   // If the input value is a chrec scev, and we can prove that the value
1642   // did not overflow the old, smaller, value, we can zero extend all of the
1643   // operands (often constants).  This allows analysis of something like
1644   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1645   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1646     if (AR->isAffine()) {
1647       const SCEV *Start = AR->getStart();
1648       const SCEV *Step = AR->getStepRecurrence(*this);
1649       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1650       const Loop *L = AR->getLoop();
1651 
1652       if (!AR->hasNoUnsignedWrap()) {
1653         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1654         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1655       }
1656 
1657       // If we have special knowledge that this addrec won't overflow,
1658       // we don't need to do any further analysis.
1659       if (AR->hasNoUnsignedWrap())
1660         return getAddRecExpr(
1661             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1662             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1663 
1664       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1665       // Note that this serves two purposes: It filters out loops that are
1666       // simply not analyzable, and it covers the case where this code is
1667       // being called from within backedge-taken count analysis, such that
1668       // attempting to ask for the backedge-taken count would likely result
1669       // in infinite recursion. In the later case, the analysis code will
1670       // cope with a conservative value, and it will take care to purge
1671       // that value once it has finished.
1672       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1673       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1674         // Manually compute the final value for AR, checking for overflow.
1675 
1676         // Check whether the backedge-taken count can be losslessly casted to
1677         // the addrec's type. The count is always unsigned.
1678         const SCEV *CastedMaxBECount =
1679             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1680         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1681             CastedMaxBECount, MaxBECount->getType(), Depth);
1682         if (MaxBECount == RecastedMaxBECount) {
1683           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1684           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1685           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1686                                         SCEV::FlagAnyWrap, Depth + 1);
1687           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1688                                                           SCEV::FlagAnyWrap,
1689                                                           Depth + 1),
1690                                                WideTy, Depth + 1);
1691           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1692           const SCEV *WideMaxBECount =
1693             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1694           const SCEV *OperandExtendedAdd =
1695             getAddExpr(WideStart,
1696                        getMulExpr(WideMaxBECount,
1697                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1698                                   SCEV::FlagAnyWrap, Depth + 1),
1699                        SCEV::FlagAnyWrap, Depth + 1);
1700           if (ZAdd == OperandExtendedAdd) {
1701             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1702             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1703             // Return the expression with the addrec on the outside.
1704             return getAddRecExpr(
1705                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1706                                                          Depth + 1),
1707                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1708                 AR->getNoWrapFlags());
1709           }
1710           // Similar to above, only this time treat the step value as signed.
1711           // This covers loops that count down.
1712           OperandExtendedAdd =
1713             getAddExpr(WideStart,
1714                        getMulExpr(WideMaxBECount,
1715                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1716                                   SCEV::FlagAnyWrap, Depth + 1),
1717                        SCEV::FlagAnyWrap, Depth + 1);
1718           if (ZAdd == OperandExtendedAdd) {
1719             // Cache knowledge of AR NW, which is propagated to this AddRec.
1720             // Negative step causes unsigned wrap, but it still can't self-wrap.
1721             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1722             // Return the expression with the addrec on the outside.
1723             return getAddRecExpr(
1724                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1725                                                          Depth + 1),
1726                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1727                 AR->getNoWrapFlags());
1728           }
1729         }
1730       }
1731 
1732       // Normally, in the cases we can prove no-overflow via a
1733       // backedge guarding condition, we can also compute a backedge
1734       // taken count for the loop.  The exceptions are assumptions and
1735       // guards present in the loop -- SCEV is not great at exploiting
1736       // these to compute max backedge taken counts, but can still use
1737       // these to prove lack of overflow.  Use this fact to avoid
1738       // doing extra work that may not pay off.
1739       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1740           !AC.assumptions().empty()) {
1741 
1742         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1743         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1744         if (AR->hasNoUnsignedWrap()) {
1745           // Same as nuw case above - duplicated here to avoid a compile time
1746           // issue.  It's not clear that the order of checks does matter, but
1747           // it's one of two issue possible causes for a change which was
1748           // reverted.  Be conservative for the moment.
1749           return getAddRecExpr(
1750                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1751                                                          Depth + 1),
1752                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1753                 AR->getNoWrapFlags());
1754         }
1755 
1756         // For a negative step, we can extend the operands iff doing so only
1757         // traverses values in the range zext([0,UINT_MAX]).
1758         if (isKnownNegative(Step)) {
1759           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1760                                       getSignedRangeMin(Step));
1761           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1762               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1763             // Cache knowledge of AR NW, which is propagated to this
1764             // AddRec.  Negative step causes unsigned wrap, but it
1765             // still can't self-wrap.
1766             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1767             // Return the expression with the addrec on the outside.
1768             return getAddRecExpr(
1769                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1770                                                          Depth + 1),
1771                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1772                 AR->getNoWrapFlags());
1773           }
1774         }
1775       }
1776 
1777       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1778       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1779       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1780       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1781         const APInt &C = SC->getAPInt();
1782         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1783         if (D != 0) {
1784           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1785           const SCEV *SResidual =
1786               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1787           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1788           return getAddExpr(SZExtD, SZExtR,
1789                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1790                             Depth + 1);
1791         }
1792       }
1793 
1794       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1795         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1796         return getAddRecExpr(
1797             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1798             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1799       }
1800     }
1801 
1802   // zext(A % B) --> zext(A) % zext(B)
1803   {
1804     const SCEV *LHS;
1805     const SCEV *RHS;
1806     if (matchURem(Op, LHS, RHS))
1807       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1808                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1809   }
1810 
1811   // zext(A / B) --> zext(A) / zext(B).
1812   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1813     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1814                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1815 
1816   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1817     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1818     if (SA->hasNoUnsignedWrap()) {
1819       // If the addition does not unsign overflow then we can, by definition,
1820       // commute the zero extension with the addition operation.
1821       SmallVector<const SCEV *, 4> Ops;
1822       for (const auto *Op : SA->operands())
1823         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1824       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1825     }
1826 
1827     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1828     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1829     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1830     //
1831     // Often address arithmetics contain expressions like
1832     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1833     // This transformation is useful while proving that such expressions are
1834     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1835     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1836       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1837       if (D != 0) {
1838         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1839         const SCEV *SResidual =
1840             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1841         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1842         return getAddExpr(SZExtD, SZExtR,
1843                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1844                           Depth + 1);
1845       }
1846     }
1847   }
1848 
1849   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1850     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1851     if (SM->hasNoUnsignedWrap()) {
1852       // If the multiply does not unsign overflow then we can, by definition,
1853       // commute the zero extension with the multiply operation.
1854       SmallVector<const SCEV *, 4> Ops;
1855       for (const auto *Op : SM->operands())
1856         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1857       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1858     }
1859 
1860     // zext(2^K * (trunc X to iN)) to iM ->
1861     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1862     //
1863     // Proof:
1864     //
1865     //     zext(2^K * (trunc X to iN)) to iM
1866     //   = zext((trunc X to iN) << K) to iM
1867     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1868     //     (because shl removes the top K bits)
1869     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1870     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1871     //
1872     if (SM->getNumOperands() == 2)
1873       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1874         if (MulLHS->getAPInt().isPowerOf2())
1875           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1876             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1877                                MulLHS->getAPInt().logBase2();
1878             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1879             return getMulExpr(
1880                 getZeroExtendExpr(MulLHS, Ty),
1881                 getZeroExtendExpr(
1882                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1883                 SCEV::FlagNUW, Depth + 1);
1884           }
1885   }
1886 
1887   // The cast wasn't folded; create an explicit cast node.
1888   // Recompute the insert position, as it may have been invalidated.
1889   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1890   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1891                                                    Op, Ty);
1892   UniqueSCEVs.InsertNode(S, IP);
1893   registerUser(S, Op);
1894   return S;
1895 }
1896 
1897 const SCEV *
1898 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1899   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1900          "This is not an extending conversion!");
1901   assert(isSCEVable(Ty) &&
1902          "This is not a conversion to a SCEVable type!");
1903   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1904   Ty = getEffectiveSCEVType(Ty);
1905 
1906   // Fold if the operand is constant.
1907   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1908     return getConstant(
1909       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1910 
1911   // sext(sext(x)) --> sext(x)
1912   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1913     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1914 
1915   // sext(zext(x)) --> zext(x)
1916   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1917     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1918 
1919   // Before doing any expensive analysis, check to see if we've already
1920   // computed a SCEV for this Op and Ty.
1921   FoldingSetNodeID ID;
1922   ID.AddInteger(scSignExtend);
1923   ID.AddPointer(Op);
1924   ID.AddPointer(Ty);
1925   void *IP = nullptr;
1926   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1927   // Limit recursion depth.
1928   if (Depth > MaxCastDepth) {
1929     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1930                                                      Op, Ty);
1931     UniqueSCEVs.InsertNode(S, IP);
1932     registerUser(S, Op);
1933     return S;
1934   }
1935 
1936   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1937   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1938     // It's possible the bits taken off by the truncate were all sign bits. If
1939     // so, we should be able to simplify this further.
1940     const SCEV *X = ST->getOperand();
1941     ConstantRange CR = getSignedRange(X);
1942     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1943     unsigned NewBits = getTypeSizeInBits(Ty);
1944     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1945             CR.sextOrTrunc(NewBits)))
1946       return getTruncateOrSignExtend(X, Ty, Depth);
1947   }
1948 
1949   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1950     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1951     if (SA->hasNoSignedWrap()) {
1952       // If the addition does not sign overflow then we can, by definition,
1953       // commute the sign extension with the addition operation.
1954       SmallVector<const SCEV *, 4> Ops;
1955       for (const auto *Op : SA->operands())
1956         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1957       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1958     }
1959 
1960     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1961     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1962     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1963     //
1964     // For instance, this will bring two seemingly different expressions:
1965     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1966     //         sext(6 + 20 * %x + 24 * %y)
1967     // to the same form:
1968     //     2 + sext(4 + 20 * %x + 24 * %y)
1969     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1970       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1971       if (D != 0) {
1972         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1973         const SCEV *SResidual =
1974             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1975         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1976         return getAddExpr(SSExtD, SSExtR,
1977                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1978                           Depth + 1);
1979       }
1980     }
1981   }
1982   // If the input value is a chrec scev, and we can prove that the value
1983   // did not overflow the old, smaller, value, we can sign extend all of the
1984   // operands (often constants).  This allows analysis of something like
1985   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1986   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1987     if (AR->isAffine()) {
1988       const SCEV *Start = AR->getStart();
1989       const SCEV *Step = AR->getStepRecurrence(*this);
1990       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1991       const Loop *L = AR->getLoop();
1992 
1993       if (!AR->hasNoSignedWrap()) {
1994         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1995         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1996       }
1997 
1998       // If we have special knowledge that this addrec won't overflow,
1999       // we don't need to do any further analysis.
2000       if (AR->hasNoSignedWrap())
2001         return getAddRecExpr(
2002             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2003             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2004 
2005       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2006       // Note that this serves two purposes: It filters out loops that are
2007       // simply not analyzable, and it covers the case where this code is
2008       // being called from within backedge-taken count analysis, such that
2009       // attempting to ask for the backedge-taken count would likely result
2010       // in infinite recursion. In the later case, the analysis code will
2011       // cope with a conservative value, and it will take care to purge
2012       // that value once it has finished.
2013       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2014       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2015         // Manually compute the final value for AR, checking for
2016         // overflow.
2017 
2018         // Check whether the backedge-taken count can be losslessly casted to
2019         // the addrec's type. The count is always unsigned.
2020         const SCEV *CastedMaxBECount =
2021             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2022         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2023             CastedMaxBECount, MaxBECount->getType(), Depth);
2024         if (MaxBECount == RecastedMaxBECount) {
2025           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2026           // Check whether Start+Step*MaxBECount has no signed overflow.
2027           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2028                                         SCEV::FlagAnyWrap, Depth + 1);
2029           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2030                                                           SCEV::FlagAnyWrap,
2031                                                           Depth + 1),
2032                                                WideTy, Depth + 1);
2033           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2034           const SCEV *WideMaxBECount =
2035             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2036           const SCEV *OperandExtendedAdd =
2037             getAddExpr(WideStart,
2038                        getMulExpr(WideMaxBECount,
2039                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2040                                   SCEV::FlagAnyWrap, Depth + 1),
2041                        SCEV::FlagAnyWrap, Depth + 1);
2042           if (SAdd == OperandExtendedAdd) {
2043             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2044             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2045             // Return the expression with the addrec on the outside.
2046             return getAddRecExpr(
2047                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2048                                                          Depth + 1),
2049                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2050                 AR->getNoWrapFlags());
2051           }
2052           // Similar to above, only this time treat the step value as unsigned.
2053           // This covers loops that count up with an unsigned step.
2054           OperandExtendedAdd =
2055             getAddExpr(WideStart,
2056                        getMulExpr(WideMaxBECount,
2057                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2058                                   SCEV::FlagAnyWrap, Depth + 1),
2059                        SCEV::FlagAnyWrap, Depth + 1);
2060           if (SAdd == OperandExtendedAdd) {
2061             // If AR wraps around then
2062             //
2063             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2064             // => SAdd != OperandExtendedAdd
2065             //
2066             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2067             // (SAdd == OperandExtendedAdd => AR is NW)
2068 
2069             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2070 
2071             // Return the expression with the addrec on the outside.
2072             return getAddRecExpr(
2073                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2074                                                          Depth + 1),
2075                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2076                 AR->getNoWrapFlags());
2077           }
2078         }
2079       }
2080 
2081       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2082       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2083       if (AR->hasNoSignedWrap()) {
2084         // Same as nsw case above - duplicated here to avoid a compile time
2085         // issue.  It's not clear that the order of checks does matter, but
2086         // it's one of two issue possible causes for a change which was
2087         // reverted.  Be conservative for the moment.
2088         return getAddRecExpr(
2089             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2090             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2091       }
2092 
2093       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2094       // if D + (C - D + Step * n) could be proven to not signed wrap
2095       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2096       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2097         const APInt &C = SC->getAPInt();
2098         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2099         if (D != 0) {
2100           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2101           const SCEV *SResidual =
2102               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2103           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2104           return getAddExpr(SSExtD, SSExtR,
2105                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2106                             Depth + 1);
2107         }
2108       }
2109 
2110       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2111         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2112         return getAddRecExpr(
2113             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2114             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2115       }
2116     }
2117 
2118   // If the input value is provably positive and we could not simplify
2119   // away the sext build a zext instead.
2120   if (isKnownNonNegative(Op))
2121     return getZeroExtendExpr(Op, Ty, Depth + 1);
2122 
2123   // The cast wasn't folded; create an explicit cast node.
2124   // Recompute the insert position, as it may have been invalidated.
2125   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2126   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2127                                                    Op, Ty);
2128   UniqueSCEVs.InsertNode(S, IP);
2129   registerUser(S, { Op });
2130   return S;
2131 }
2132 
2133 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2134                                          Type *Ty) {
2135   switch (Kind) {
2136   case scTruncate:
2137     return getTruncateExpr(Op, Ty);
2138   case scZeroExtend:
2139     return getZeroExtendExpr(Op, Ty);
2140   case scSignExtend:
2141     return getSignExtendExpr(Op, Ty);
2142   case scPtrToInt:
2143     return getPtrToIntExpr(Op, Ty);
2144   default:
2145     llvm_unreachable("Not a SCEV cast expression!");
2146   }
2147 }
2148 
2149 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2150 /// unspecified bits out to the given type.
2151 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2152                                               Type *Ty) {
2153   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2154          "This is not an extending conversion!");
2155   assert(isSCEVable(Ty) &&
2156          "This is not a conversion to a SCEVable type!");
2157   Ty = getEffectiveSCEVType(Ty);
2158 
2159   // Sign-extend negative constants.
2160   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2161     if (SC->getAPInt().isNegative())
2162       return getSignExtendExpr(Op, Ty);
2163 
2164   // Peel off a truncate cast.
2165   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2166     const SCEV *NewOp = T->getOperand();
2167     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2168       return getAnyExtendExpr(NewOp, Ty);
2169     return getTruncateOrNoop(NewOp, Ty);
2170   }
2171 
2172   // Next try a zext cast. If the cast is folded, use it.
2173   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2174   if (!isa<SCEVZeroExtendExpr>(ZExt))
2175     return ZExt;
2176 
2177   // Next try a sext cast. If the cast is folded, use it.
2178   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2179   if (!isa<SCEVSignExtendExpr>(SExt))
2180     return SExt;
2181 
2182   // Force the cast to be folded into the operands of an addrec.
2183   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2184     SmallVector<const SCEV *, 4> Ops;
2185     for (const SCEV *Op : AR->operands())
2186       Ops.push_back(getAnyExtendExpr(Op, Ty));
2187     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2188   }
2189 
2190   // If the expression is obviously signed, use the sext cast value.
2191   if (isa<SCEVSMaxExpr>(Op))
2192     return SExt;
2193 
2194   // Absent any other information, use the zext cast value.
2195   return ZExt;
2196 }
2197 
2198 /// Process the given Ops list, which is a list of operands to be added under
2199 /// the given scale, update the given map. This is a helper function for
2200 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2201 /// that would form an add expression like this:
2202 ///
2203 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2204 ///
2205 /// where A and B are constants, update the map with these values:
2206 ///
2207 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2208 ///
2209 /// and add 13 + A*B*29 to AccumulatedConstant.
2210 /// This will allow getAddRecExpr to produce this:
2211 ///
2212 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2213 ///
2214 /// This form often exposes folding opportunities that are hidden in
2215 /// the original operand list.
2216 ///
2217 /// Return true iff it appears that any interesting folding opportunities
2218 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2219 /// the common case where no interesting opportunities are present, and
2220 /// is also used as a check to avoid infinite recursion.
2221 static bool
2222 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2223                              SmallVectorImpl<const SCEV *> &NewOps,
2224                              APInt &AccumulatedConstant,
2225                              const SCEV *const *Ops, size_t NumOperands,
2226                              const APInt &Scale,
2227                              ScalarEvolution &SE) {
2228   bool Interesting = false;
2229 
2230   // Iterate over the add operands. They are sorted, with constants first.
2231   unsigned i = 0;
2232   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2233     ++i;
2234     // Pull a buried constant out to the outside.
2235     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2236       Interesting = true;
2237     AccumulatedConstant += Scale * C->getAPInt();
2238   }
2239 
2240   // Next comes everything else. We're especially interested in multiplies
2241   // here, but they're in the middle, so just visit the rest with one loop.
2242   for (; i != NumOperands; ++i) {
2243     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2244     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2245       APInt NewScale =
2246           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2247       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2248         // A multiplication of a constant with another add; recurse.
2249         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2250         Interesting |=
2251           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2252                                        Add->op_begin(), Add->getNumOperands(),
2253                                        NewScale, SE);
2254       } else {
2255         // A multiplication of a constant with some other value. Update
2256         // the map.
2257         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2258         const SCEV *Key = SE.getMulExpr(MulOps);
2259         auto Pair = M.insert({Key, NewScale});
2260         if (Pair.second) {
2261           NewOps.push_back(Pair.first->first);
2262         } else {
2263           Pair.first->second += NewScale;
2264           // The map already had an entry for this value, which may indicate
2265           // a folding opportunity.
2266           Interesting = true;
2267         }
2268       }
2269     } else {
2270       // An ordinary operand. Update the map.
2271       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2272           M.insert({Ops[i], Scale});
2273       if (Pair.second) {
2274         NewOps.push_back(Pair.first->first);
2275       } else {
2276         Pair.first->second += Scale;
2277         // The map already had an entry for this value, which may indicate
2278         // a folding opportunity.
2279         Interesting = true;
2280       }
2281     }
2282   }
2283 
2284   return Interesting;
2285 }
2286 
2287 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2288                                       const SCEV *LHS, const SCEV *RHS) {
2289   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2290                                             SCEV::NoWrapFlags, unsigned);
2291   switch (BinOp) {
2292   default:
2293     llvm_unreachable("Unsupported binary op");
2294   case Instruction::Add:
2295     Operation = &ScalarEvolution::getAddExpr;
2296     break;
2297   case Instruction::Sub:
2298     Operation = &ScalarEvolution::getMinusSCEV;
2299     break;
2300   case Instruction::Mul:
2301     Operation = &ScalarEvolution::getMulExpr;
2302     break;
2303   }
2304 
2305   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2306       Signed ? &ScalarEvolution::getSignExtendExpr
2307              : &ScalarEvolution::getZeroExtendExpr;
2308 
2309   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2310   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2311   auto *WideTy =
2312       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2313 
2314   const SCEV *A = (this->*Extension)(
2315       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2316   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2317                                      (this->*Extension)(RHS, WideTy, 0),
2318                                      SCEV::FlagAnyWrap, 0);
2319   return A == B;
2320 }
2321 
2322 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2323 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2324     const OverflowingBinaryOperator *OBO) {
2325   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2326 
2327   if (OBO->hasNoUnsignedWrap())
2328     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2329   if (OBO->hasNoSignedWrap())
2330     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2331 
2332   bool Deduced = false;
2333 
2334   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2335     return {Flags, Deduced};
2336 
2337   if (OBO->getOpcode() != Instruction::Add &&
2338       OBO->getOpcode() != Instruction::Sub &&
2339       OBO->getOpcode() != Instruction::Mul)
2340     return {Flags, Deduced};
2341 
2342   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2343   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2344 
2345   if (!OBO->hasNoUnsignedWrap() &&
2346       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2347                       /* Signed */ false, LHS, RHS)) {
2348     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2349     Deduced = true;
2350   }
2351 
2352   if (!OBO->hasNoSignedWrap() &&
2353       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2354                       /* Signed */ true, LHS, RHS)) {
2355     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2356     Deduced = true;
2357   }
2358 
2359   return {Flags, Deduced};
2360 }
2361 
2362 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2363 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2364 // can't-overflow flags for the operation if possible.
2365 static SCEV::NoWrapFlags
2366 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2367                       const ArrayRef<const SCEV *> Ops,
2368                       SCEV::NoWrapFlags Flags) {
2369   using namespace std::placeholders;
2370 
2371   using OBO = OverflowingBinaryOperator;
2372 
2373   bool CanAnalyze =
2374       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2375   (void)CanAnalyze;
2376   assert(CanAnalyze && "don't call from other places!");
2377 
2378   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2379   SCEV::NoWrapFlags SignOrUnsignWrap =
2380       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2381 
2382   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2383   auto IsKnownNonNegative = [&](const SCEV *S) {
2384     return SE->isKnownNonNegative(S);
2385   };
2386 
2387   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2388     Flags =
2389         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2390 
2391   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2392 
2393   if (SignOrUnsignWrap != SignOrUnsignMask &&
2394       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2395       isa<SCEVConstant>(Ops[0])) {
2396 
2397     auto Opcode = [&] {
2398       switch (Type) {
2399       case scAddExpr:
2400         return Instruction::Add;
2401       case scMulExpr:
2402         return Instruction::Mul;
2403       default:
2404         llvm_unreachable("Unexpected SCEV op.");
2405       }
2406     }();
2407 
2408     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2409 
2410     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2411     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2412       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2413           Opcode, C, OBO::NoSignedWrap);
2414       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2415         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2416     }
2417 
2418     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2419     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2420       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2421           Opcode, C, OBO::NoUnsignedWrap);
2422       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2423         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2424     }
2425   }
2426 
2427   // <0,+,nonnegative><nw> is also nuw
2428   // TODO: Add corresponding nsw case
2429   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2430       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2431       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2432     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2433 
2434   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2435   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2436       Ops.size() == 2) {
2437     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2438       if (UDiv->getOperand(1) == Ops[1])
2439         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2440     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2441       if (UDiv->getOperand(1) == Ops[0])
2442         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2443   }
2444 
2445   return Flags;
2446 }
2447 
2448 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2449   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2450 }
2451 
2452 /// Get a canonical add expression, or something simpler if possible.
2453 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2454                                         SCEV::NoWrapFlags OrigFlags,
2455                                         unsigned Depth) {
2456   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2457          "only nuw or nsw allowed");
2458   assert(!Ops.empty() && "Cannot get empty add!");
2459   if (Ops.size() == 1) return Ops[0];
2460 #ifndef NDEBUG
2461   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2462   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2463     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2464            "SCEVAddExpr operand types don't match!");
2465   unsigned NumPtrs = count_if(
2466       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2467   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2468 #endif
2469 
2470   // Sort by complexity, this groups all similar expression types together.
2471   GroupByComplexity(Ops, &LI, DT);
2472 
2473   // If there are any constants, fold them together.
2474   unsigned Idx = 0;
2475   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2476     ++Idx;
2477     assert(Idx < Ops.size());
2478     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2479       // We found two constants, fold them together!
2480       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2481       if (Ops.size() == 2) return Ops[0];
2482       Ops.erase(Ops.begin()+1);  // Erase the folded element
2483       LHSC = cast<SCEVConstant>(Ops[0]);
2484     }
2485 
2486     // If we are left with a constant zero being added, strip it off.
2487     if (LHSC->getValue()->isZero()) {
2488       Ops.erase(Ops.begin());
2489       --Idx;
2490     }
2491 
2492     if (Ops.size() == 1) return Ops[0];
2493   }
2494 
2495   // Delay expensive flag strengthening until necessary.
2496   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2497     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2498   };
2499 
2500   // Limit recursion calls depth.
2501   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2502     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2503 
2504   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2505     // Don't strengthen flags if we have no new information.
2506     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2507     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2508       Add->setNoWrapFlags(ComputeFlags(Ops));
2509     return S;
2510   }
2511 
2512   // Okay, check to see if the same value occurs in the operand list more than
2513   // once.  If so, merge them together into an multiply expression.  Since we
2514   // sorted the list, these values are required to be adjacent.
2515   Type *Ty = Ops[0]->getType();
2516   bool FoundMatch = false;
2517   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2518     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2519       // Scan ahead to count how many equal operands there are.
2520       unsigned Count = 2;
2521       while (i+Count != e && Ops[i+Count] == Ops[i])
2522         ++Count;
2523       // Merge the values into a multiply.
2524       const SCEV *Scale = getConstant(Ty, Count);
2525       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2526       if (Ops.size() == Count)
2527         return Mul;
2528       Ops[i] = Mul;
2529       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2530       --i; e -= Count - 1;
2531       FoundMatch = true;
2532     }
2533   if (FoundMatch)
2534     return getAddExpr(Ops, OrigFlags, Depth + 1);
2535 
2536   // Check for truncates. If all the operands are truncated from the same
2537   // type, see if factoring out the truncate would permit the result to be
2538   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2539   // if the contents of the resulting outer trunc fold to something simple.
2540   auto FindTruncSrcType = [&]() -> Type * {
2541     // We're ultimately looking to fold an addrec of truncs and muls of only
2542     // constants and truncs, so if we find any other types of SCEV
2543     // as operands of the addrec then we bail and return nullptr here.
2544     // Otherwise, we return the type of the operand of a trunc that we find.
2545     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2546       return T->getOperand()->getType();
2547     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2548       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2549       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2550         return T->getOperand()->getType();
2551     }
2552     return nullptr;
2553   };
2554   if (auto *SrcType = FindTruncSrcType()) {
2555     SmallVector<const SCEV *, 8> LargeOps;
2556     bool Ok = true;
2557     // Check all the operands to see if they can be represented in the
2558     // source type of the truncate.
2559     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2560       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2561         if (T->getOperand()->getType() != SrcType) {
2562           Ok = false;
2563           break;
2564         }
2565         LargeOps.push_back(T->getOperand());
2566       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2567         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2568       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2569         SmallVector<const SCEV *, 8> LargeMulOps;
2570         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2571           if (const SCEVTruncateExpr *T =
2572                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2573             if (T->getOperand()->getType() != SrcType) {
2574               Ok = false;
2575               break;
2576             }
2577             LargeMulOps.push_back(T->getOperand());
2578           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2579             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2580           } else {
2581             Ok = false;
2582             break;
2583           }
2584         }
2585         if (Ok)
2586           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2587       } else {
2588         Ok = false;
2589         break;
2590       }
2591     }
2592     if (Ok) {
2593       // Evaluate the expression in the larger type.
2594       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2595       // If it folds to something simple, use it. Otherwise, don't.
2596       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2597         return getTruncateExpr(Fold, Ty);
2598     }
2599   }
2600 
2601   if (Ops.size() == 2) {
2602     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2603     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2604     // C1).
2605     const SCEV *A = Ops[0];
2606     const SCEV *B = Ops[1];
2607     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2608     auto *C = dyn_cast<SCEVConstant>(A);
2609     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2610       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2611       auto C2 = C->getAPInt();
2612       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2613 
2614       APInt ConstAdd = C1 + C2;
2615       auto AddFlags = AddExpr->getNoWrapFlags();
2616       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2617       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2618           ConstAdd.ule(C1)) {
2619         PreservedFlags =
2620             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2621       }
2622 
2623       // Adding a constant with the same sign and small magnitude is NSW, if the
2624       // original AddExpr was NSW.
2625       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2626           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2627           ConstAdd.abs().ule(C1.abs())) {
2628         PreservedFlags =
2629             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2630       }
2631 
2632       if (PreservedFlags != SCEV::FlagAnyWrap) {
2633         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2634         NewOps[0] = getConstant(ConstAdd);
2635         return getAddExpr(NewOps, PreservedFlags);
2636       }
2637     }
2638   }
2639 
2640   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2641   if (Ops.size() == 2) {
2642     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2643     if (Mul && Mul->getNumOperands() == 2 &&
2644         Mul->getOperand(0)->isAllOnesValue()) {
2645       const SCEV *X;
2646       const SCEV *Y;
2647       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2648         return getMulExpr(Y, getUDivExpr(X, Y));
2649       }
2650     }
2651   }
2652 
2653   // Skip past any other cast SCEVs.
2654   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2655     ++Idx;
2656 
2657   // If there are add operands they would be next.
2658   if (Idx < Ops.size()) {
2659     bool DeletedAdd = false;
2660     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2661     // common NUW flag for expression after inlining. Other flags cannot be
2662     // preserved, because they may depend on the original order of operations.
2663     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2664     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2665       if (Ops.size() > AddOpsInlineThreshold ||
2666           Add->getNumOperands() > AddOpsInlineThreshold)
2667         break;
2668       // If we have an add, expand the add operands onto the end of the operands
2669       // list.
2670       Ops.erase(Ops.begin()+Idx);
2671       Ops.append(Add->op_begin(), Add->op_end());
2672       DeletedAdd = true;
2673       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2674     }
2675 
2676     // If we deleted at least one add, we added operands to the end of the list,
2677     // and they are not necessarily sorted.  Recurse to resort and resimplify
2678     // any operands we just acquired.
2679     if (DeletedAdd)
2680       return getAddExpr(Ops, CommonFlags, Depth + 1);
2681   }
2682 
2683   // Skip over the add expression until we get to a multiply.
2684   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2685     ++Idx;
2686 
2687   // Check to see if there are any folding opportunities present with
2688   // operands multiplied by constant values.
2689   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2690     uint64_t BitWidth = getTypeSizeInBits(Ty);
2691     DenseMap<const SCEV *, APInt> M;
2692     SmallVector<const SCEV *, 8> NewOps;
2693     APInt AccumulatedConstant(BitWidth, 0);
2694     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2695                                      Ops.data(), Ops.size(),
2696                                      APInt(BitWidth, 1), *this)) {
2697       struct APIntCompare {
2698         bool operator()(const APInt &LHS, const APInt &RHS) const {
2699           return LHS.ult(RHS);
2700         }
2701       };
2702 
2703       // Some interesting folding opportunity is present, so its worthwhile to
2704       // re-generate the operands list. Group the operands by constant scale,
2705       // to avoid multiplying by the same constant scale multiple times.
2706       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2707       for (const SCEV *NewOp : NewOps)
2708         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2709       // Re-generate the operands list.
2710       Ops.clear();
2711       if (AccumulatedConstant != 0)
2712         Ops.push_back(getConstant(AccumulatedConstant));
2713       for (auto &MulOp : MulOpLists) {
2714         if (MulOp.first == 1) {
2715           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2716         } else if (MulOp.first != 0) {
2717           Ops.push_back(getMulExpr(
2718               getConstant(MulOp.first),
2719               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2720               SCEV::FlagAnyWrap, Depth + 1));
2721         }
2722       }
2723       if (Ops.empty())
2724         return getZero(Ty);
2725       if (Ops.size() == 1)
2726         return Ops[0];
2727       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2728     }
2729   }
2730 
2731   // If we are adding something to a multiply expression, make sure the
2732   // something is not already an operand of the multiply.  If so, merge it into
2733   // the multiply.
2734   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2735     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2736     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2737       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2738       if (isa<SCEVConstant>(MulOpSCEV))
2739         continue;
2740       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2741         if (MulOpSCEV == Ops[AddOp]) {
2742           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2743           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2744           if (Mul->getNumOperands() != 2) {
2745             // If the multiply has more than two operands, we must get the
2746             // Y*Z term.
2747             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2748                                                 Mul->op_begin()+MulOp);
2749             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2750             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2751           }
2752           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2753           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2754           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2755                                             SCEV::FlagAnyWrap, Depth + 1);
2756           if (Ops.size() == 2) return OuterMul;
2757           if (AddOp < Idx) {
2758             Ops.erase(Ops.begin()+AddOp);
2759             Ops.erase(Ops.begin()+Idx-1);
2760           } else {
2761             Ops.erase(Ops.begin()+Idx);
2762             Ops.erase(Ops.begin()+AddOp-1);
2763           }
2764           Ops.push_back(OuterMul);
2765           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2766         }
2767 
2768       // Check this multiply against other multiplies being added together.
2769       for (unsigned OtherMulIdx = Idx+1;
2770            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2771            ++OtherMulIdx) {
2772         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2773         // If MulOp occurs in OtherMul, we can fold the two multiplies
2774         // together.
2775         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2776              OMulOp != e; ++OMulOp)
2777           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2778             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2779             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2780             if (Mul->getNumOperands() != 2) {
2781               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2782                                                   Mul->op_begin()+MulOp);
2783               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2784               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2785             }
2786             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2787             if (OtherMul->getNumOperands() != 2) {
2788               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2789                                                   OtherMul->op_begin()+OMulOp);
2790               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2791               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2792             }
2793             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2794             const SCEV *InnerMulSum =
2795                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2796             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2797                                               SCEV::FlagAnyWrap, Depth + 1);
2798             if (Ops.size() == 2) return OuterMul;
2799             Ops.erase(Ops.begin()+Idx);
2800             Ops.erase(Ops.begin()+OtherMulIdx-1);
2801             Ops.push_back(OuterMul);
2802             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2803           }
2804       }
2805     }
2806   }
2807 
2808   // If there are any add recurrences in the operands list, see if any other
2809   // added values are loop invariant.  If so, we can fold them into the
2810   // recurrence.
2811   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2812     ++Idx;
2813 
2814   // Scan over all recurrences, trying to fold loop invariants into them.
2815   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2816     // Scan all of the other operands to this add and add them to the vector if
2817     // they are loop invariant w.r.t. the recurrence.
2818     SmallVector<const SCEV *, 8> LIOps;
2819     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2820     const Loop *AddRecLoop = AddRec->getLoop();
2821     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2822       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2823         LIOps.push_back(Ops[i]);
2824         Ops.erase(Ops.begin()+i);
2825         --i; --e;
2826       }
2827 
2828     // If we found some loop invariants, fold them into the recurrence.
2829     if (!LIOps.empty()) {
2830       // Compute nowrap flags for the addition of the loop-invariant ops and
2831       // the addrec. Temporarily push it as an operand for that purpose. These
2832       // flags are valid in the scope of the addrec only.
2833       LIOps.push_back(AddRec);
2834       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2835       LIOps.pop_back();
2836 
2837       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2838       LIOps.push_back(AddRec->getStart());
2839 
2840       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2841 
2842       // It is not in general safe to propagate flags valid on an add within
2843       // the addrec scope to one outside it.  We must prove that the inner
2844       // scope is guaranteed to execute if the outer one does to be able to
2845       // safely propagate.  We know the program is undefined if poison is
2846       // produced on the inner scoped addrec.  We also know that *for this use*
2847       // the outer scoped add can't overflow (because of the flags we just
2848       // computed for the inner scoped add) without the program being undefined.
2849       // Proving that entry to the outer scope neccesitates entry to the inner
2850       // scope, thus proves the program undefined if the flags would be violated
2851       // in the outer scope.
2852       SCEV::NoWrapFlags AddFlags = Flags;
2853       if (AddFlags != SCEV::FlagAnyWrap) {
2854         auto *DefI = getDefiningScopeBound(LIOps);
2855         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2856         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2857           AddFlags = SCEV::FlagAnyWrap;
2858       }
2859       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2860 
2861       // Build the new addrec. Propagate the NUW and NSW flags if both the
2862       // outer add and the inner addrec are guaranteed to have no overflow.
2863       // Always propagate NW.
2864       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2865       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2866 
2867       // If all of the other operands were loop invariant, we are done.
2868       if (Ops.size() == 1) return NewRec;
2869 
2870       // Otherwise, add the folded AddRec by the non-invariant parts.
2871       for (unsigned i = 0;; ++i)
2872         if (Ops[i] == AddRec) {
2873           Ops[i] = NewRec;
2874           break;
2875         }
2876       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2877     }
2878 
2879     // Okay, if there weren't any loop invariants to be folded, check to see if
2880     // there are multiple AddRec's with the same loop induction variable being
2881     // added together.  If so, we can fold them.
2882     for (unsigned OtherIdx = Idx+1;
2883          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2884          ++OtherIdx) {
2885       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2886       // so that the 1st found AddRecExpr is dominated by all others.
2887       assert(DT.dominates(
2888            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2889            AddRec->getLoop()->getHeader()) &&
2890         "AddRecExprs are not sorted in reverse dominance order?");
2891       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2892         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2893         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2894         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2895              ++OtherIdx) {
2896           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2897           if (OtherAddRec->getLoop() == AddRecLoop) {
2898             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2899                  i != e; ++i) {
2900               if (i >= AddRecOps.size()) {
2901                 AddRecOps.append(OtherAddRec->op_begin()+i,
2902                                  OtherAddRec->op_end());
2903                 break;
2904               }
2905               SmallVector<const SCEV *, 2> TwoOps = {
2906                   AddRecOps[i], OtherAddRec->getOperand(i)};
2907               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2908             }
2909             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2910           }
2911         }
2912         // Step size has changed, so we cannot guarantee no self-wraparound.
2913         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2914         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2915       }
2916     }
2917 
2918     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2919     // next one.
2920   }
2921 
2922   // Okay, it looks like we really DO need an add expr.  Check to see if we
2923   // already have one, otherwise create a new one.
2924   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2925 }
2926 
2927 const SCEV *
2928 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2929                                     SCEV::NoWrapFlags Flags) {
2930   FoldingSetNodeID ID;
2931   ID.AddInteger(scAddExpr);
2932   for (const SCEV *Op : Ops)
2933     ID.AddPointer(Op);
2934   void *IP = nullptr;
2935   SCEVAddExpr *S =
2936       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2937   if (!S) {
2938     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2939     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2940     S = new (SCEVAllocator)
2941         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2942     UniqueSCEVs.InsertNode(S, IP);
2943     registerUser(S, Ops);
2944   }
2945   S->setNoWrapFlags(Flags);
2946   return S;
2947 }
2948 
2949 const SCEV *
2950 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2951                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2952   FoldingSetNodeID ID;
2953   ID.AddInteger(scAddRecExpr);
2954   for (const SCEV *Op : Ops)
2955     ID.AddPointer(Op);
2956   ID.AddPointer(L);
2957   void *IP = nullptr;
2958   SCEVAddRecExpr *S =
2959       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2960   if (!S) {
2961     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2962     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2963     S = new (SCEVAllocator)
2964         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2965     UniqueSCEVs.InsertNode(S, IP);
2966     LoopUsers[L].push_back(S);
2967     registerUser(S, Ops);
2968   }
2969   setNoWrapFlags(S, Flags);
2970   return S;
2971 }
2972 
2973 const SCEV *
2974 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2975                                     SCEV::NoWrapFlags Flags) {
2976   FoldingSetNodeID ID;
2977   ID.AddInteger(scMulExpr);
2978   for (const SCEV *Op : Ops)
2979     ID.AddPointer(Op);
2980   void *IP = nullptr;
2981   SCEVMulExpr *S =
2982     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2983   if (!S) {
2984     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2985     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2986     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2987                                         O, Ops.size());
2988     UniqueSCEVs.InsertNode(S, IP);
2989     registerUser(S, Ops);
2990   }
2991   S->setNoWrapFlags(Flags);
2992   return S;
2993 }
2994 
2995 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2996   uint64_t k = i*j;
2997   if (j > 1 && k / j != i) Overflow = true;
2998   return k;
2999 }
3000 
3001 /// Compute the result of "n choose k", the binomial coefficient.  If an
3002 /// intermediate computation overflows, Overflow will be set and the return will
3003 /// be garbage. Overflow is not cleared on absence of overflow.
3004 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3005   // We use the multiplicative formula:
3006   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3007   // At each iteration, we take the n-th term of the numeral and divide by the
3008   // (k-n)th term of the denominator.  This division will always produce an
3009   // integral result, and helps reduce the chance of overflow in the
3010   // intermediate computations. However, we can still overflow even when the
3011   // final result would fit.
3012 
3013   if (n == 0 || n == k) return 1;
3014   if (k > n) return 0;
3015 
3016   if (k > n/2)
3017     k = n-k;
3018 
3019   uint64_t r = 1;
3020   for (uint64_t i = 1; i <= k; ++i) {
3021     r = umul_ov(r, n-(i-1), Overflow);
3022     r /= i;
3023   }
3024   return r;
3025 }
3026 
3027 /// Determine if any of the operands in this SCEV are a constant or if
3028 /// any of the add or multiply expressions in this SCEV contain a constant.
3029 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3030   struct FindConstantInAddMulChain {
3031     bool FoundConstant = false;
3032 
3033     bool follow(const SCEV *S) {
3034       FoundConstant |= isa<SCEVConstant>(S);
3035       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3036     }
3037 
3038     bool isDone() const {
3039       return FoundConstant;
3040     }
3041   };
3042 
3043   FindConstantInAddMulChain F;
3044   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3045   ST.visitAll(StartExpr);
3046   return F.FoundConstant;
3047 }
3048 
3049 /// Get a canonical multiply expression, or something simpler if possible.
3050 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3051                                         SCEV::NoWrapFlags OrigFlags,
3052                                         unsigned Depth) {
3053   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3054          "only nuw or nsw allowed");
3055   assert(!Ops.empty() && "Cannot get empty mul!");
3056   if (Ops.size() == 1) return Ops[0];
3057 #ifndef NDEBUG
3058   Type *ETy = Ops[0]->getType();
3059   assert(!ETy->isPointerTy());
3060   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3061     assert(Ops[i]->getType() == ETy &&
3062            "SCEVMulExpr operand types don't match!");
3063 #endif
3064 
3065   // Sort by complexity, this groups all similar expression types together.
3066   GroupByComplexity(Ops, &LI, DT);
3067 
3068   // If there are any constants, fold them together.
3069   unsigned Idx = 0;
3070   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3071     ++Idx;
3072     assert(Idx < Ops.size());
3073     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3074       // We found two constants, fold them together!
3075       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3076       if (Ops.size() == 2) return Ops[0];
3077       Ops.erase(Ops.begin()+1);  // Erase the folded element
3078       LHSC = cast<SCEVConstant>(Ops[0]);
3079     }
3080 
3081     // If we have a multiply of zero, it will always be zero.
3082     if (LHSC->getValue()->isZero())
3083       return LHSC;
3084 
3085     // If we are left with a constant one being multiplied, strip it off.
3086     if (LHSC->getValue()->isOne()) {
3087       Ops.erase(Ops.begin());
3088       --Idx;
3089     }
3090 
3091     if (Ops.size() == 1)
3092       return Ops[0];
3093   }
3094 
3095   // Delay expensive flag strengthening until necessary.
3096   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3097     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3098   };
3099 
3100   // Limit recursion calls depth.
3101   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3102     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3103 
3104   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3105     // Don't strengthen flags if we have no new information.
3106     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3107     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3108       Mul->setNoWrapFlags(ComputeFlags(Ops));
3109     return S;
3110   }
3111 
3112   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3113     if (Ops.size() == 2) {
3114       // C1*(C2+V) -> C1*C2 + C1*V
3115       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3116         // If any of Add's ops are Adds or Muls with a constant, apply this
3117         // transformation as well.
3118         //
3119         // TODO: There are some cases where this transformation is not
3120         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3121         // this transformation should be narrowed down.
3122         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
3123           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
3124                                        SCEV::FlagAnyWrap, Depth + 1),
3125                             getMulExpr(LHSC, Add->getOperand(1),
3126                                        SCEV::FlagAnyWrap, Depth + 1),
3127                             SCEV::FlagAnyWrap, Depth + 1);
3128 
3129       if (Ops[0]->isAllOnesValue()) {
3130         // If we have a mul by -1 of an add, try distributing the -1 among the
3131         // add operands.
3132         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3133           SmallVector<const SCEV *, 4> NewOps;
3134           bool AnyFolded = false;
3135           for (const SCEV *AddOp : Add->operands()) {
3136             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3137                                          Depth + 1);
3138             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3139             NewOps.push_back(Mul);
3140           }
3141           if (AnyFolded)
3142             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3143         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3144           // Negation preserves a recurrence's no self-wrap property.
3145           SmallVector<const SCEV *, 4> Operands;
3146           for (const SCEV *AddRecOp : AddRec->operands())
3147             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3148                                           Depth + 1));
3149 
3150           return getAddRecExpr(Operands, AddRec->getLoop(),
3151                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3152         }
3153       }
3154     }
3155   }
3156 
3157   // Skip over the add expression until we get to a multiply.
3158   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3159     ++Idx;
3160 
3161   // If there are mul operands inline them all into this expression.
3162   if (Idx < Ops.size()) {
3163     bool DeletedMul = false;
3164     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3165       if (Ops.size() > MulOpsInlineThreshold)
3166         break;
3167       // If we have an mul, expand the mul operands onto the end of the
3168       // operands list.
3169       Ops.erase(Ops.begin()+Idx);
3170       Ops.append(Mul->op_begin(), Mul->op_end());
3171       DeletedMul = true;
3172     }
3173 
3174     // If we deleted at least one mul, we added operands to the end of the
3175     // list, and they are not necessarily sorted.  Recurse to resort and
3176     // resimplify any operands we just acquired.
3177     if (DeletedMul)
3178       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3179   }
3180 
3181   // If there are any add recurrences in the operands list, see if any other
3182   // added values are loop invariant.  If so, we can fold them into the
3183   // recurrence.
3184   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3185     ++Idx;
3186 
3187   // Scan over all recurrences, trying to fold loop invariants into them.
3188   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3189     // Scan all of the other operands to this mul and add them to the vector
3190     // if they are loop invariant w.r.t. the recurrence.
3191     SmallVector<const SCEV *, 8> LIOps;
3192     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3193     const Loop *AddRecLoop = AddRec->getLoop();
3194     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3195       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3196         LIOps.push_back(Ops[i]);
3197         Ops.erase(Ops.begin()+i);
3198         --i; --e;
3199       }
3200 
3201     // If we found some loop invariants, fold them into the recurrence.
3202     if (!LIOps.empty()) {
3203       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3204       SmallVector<const SCEV *, 4> NewOps;
3205       NewOps.reserve(AddRec->getNumOperands());
3206       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3207       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3208         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3209                                     SCEV::FlagAnyWrap, Depth + 1));
3210 
3211       // Build the new addrec. Propagate the NUW and NSW flags if both the
3212       // outer mul and the inner addrec are guaranteed to have no overflow.
3213       //
3214       // No self-wrap cannot be guaranteed after changing the step size, but
3215       // will be inferred if either NUW or NSW is true.
3216       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3217       const SCEV *NewRec = getAddRecExpr(
3218           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3219 
3220       // If all of the other operands were loop invariant, we are done.
3221       if (Ops.size() == 1) return NewRec;
3222 
3223       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3224       for (unsigned i = 0;; ++i)
3225         if (Ops[i] == AddRec) {
3226           Ops[i] = NewRec;
3227           break;
3228         }
3229       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3230     }
3231 
3232     // Okay, if there weren't any loop invariants to be folded, check to see
3233     // if there are multiple AddRec's with the same loop induction variable
3234     // being multiplied together.  If so, we can fold them.
3235 
3236     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3237     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3238     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3239     //   ]]],+,...up to x=2n}.
3240     // Note that the arguments to choose() are always integers with values
3241     // known at compile time, never SCEV objects.
3242     //
3243     // The implementation avoids pointless extra computations when the two
3244     // addrec's are of different length (mathematically, it's equivalent to
3245     // an infinite stream of zeros on the right).
3246     bool OpsModified = false;
3247     for (unsigned OtherIdx = Idx+1;
3248          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3249          ++OtherIdx) {
3250       const SCEVAddRecExpr *OtherAddRec =
3251         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3252       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3253         continue;
3254 
3255       // Limit max number of arguments to avoid creation of unreasonably big
3256       // SCEVAddRecs with very complex operands.
3257       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3258           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3259         continue;
3260 
3261       bool Overflow = false;
3262       Type *Ty = AddRec->getType();
3263       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3264       SmallVector<const SCEV*, 7> AddRecOps;
3265       for (int x = 0, xe = AddRec->getNumOperands() +
3266              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3267         SmallVector <const SCEV *, 7> SumOps;
3268         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3269           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3270           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3271                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3272                z < ze && !Overflow; ++z) {
3273             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3274             uint64_t Coeff;
3275             if (LargerThan64Bits)
3276               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3277             else
3278               Coeff = Coeff1*Coeff2;
3279             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3280             const SCEV *Term1 = AddRec->getOperand(y-z);
3281             const SCEV *Term2 = OtherAddRec->getOperand(z);
3282             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3283                                         SCEV::FlagAnyWrap, Depth + 1));
3284           }
3285         }
3286         if (SumOps.empty())
3287           SumOps.push_back(getZero(Ty));
3288         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3289       }
3290       if (!Overflow) {
3291         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3292                                               SCEV::FlagAnyWrap);
3293         if (Ops.size() == 2) return NewAddRec;
3294         Ops[Idx] = NewAddRec;
3295         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3296         OpsModified = true;
3297         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3298         if (!AddRec)
3299           break;
3300       }
3301     }
3302     if (OpsModified)
3303       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3304 
3305     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3306     // next one.
3307   }
3308 
3309   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3310   // already have one, otherwise create a new one.
3311   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3312 }
3313 
3314 /// Represents an unsigned remainder expression based on unsigned division.
3315 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3316                                          const SCEV *RHS) {
3317   assert(getEffectiveSCEVType(LHS->getType()) ==
3318          getEffectiveSCEVType(RHS->getType()) &&
3319          "SCEVURemExpr operand types don't match!");
3320 
3321   // Short-circuit easy cases
3322   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3323     // If constant is one, the result is trivial
3324     if (RHSC->getValue()->isOne())
3325       return getZero(LHS->getType()); // X urem 1 --> 0
3326 
3327     // If constant is a power of two, fold into a zext(trunc(LHS)).
3328     if (RHSC->getAPInt().isPowerOf2()) {
3329       Type *FullTy = LHS->getType();
3330       Type *TruncTy =
3331           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3332       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3333     }
3334   }
3335 
3336   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3337   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3338   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3339   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3340 }
3341 
3342 /// Get a canonical unsigned division expression, or something simpler if
3343 /// possible.
3344 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3345                                          const SCEV *RHS) {
3346   assert(!LHS->getType()->isPointerTy() &&
3347          "SCEVUDivExpr operand can't be pointer!");
3348   assert(LHS->getType() == RHS->getType() &&
3349          "SCEVUDivExpr operand types don't match!");
3350 
3351   FoldingSetNodeID ID;
3352   ID.AddInteger(scUDivExpr);
3353   ID.AddPointer(LHS);
3354   ID.AddPointer(RHS);
3355   void *IP = nullptr;
3356   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3357     return S;
3358 
3359   // 0 udiv Y == 0
3360   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3361     if (LHSC->getValue()->isZero())
3362       return LHS;
3363 
3364   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3365     if (RHSC->getValue()->isOne())
3366       return LHS;                               // X udiv 1 --> x
3367     // If the denominator is zero, the result of the udiv is undefined. Don't
3368     // try to analyze it, because the resolution chosen here may differ from
3369     // the resolution chosen in other parts of the compiler.
3370     if (!RHSC->getValue()->isZero()) {
3371       // Determine if the division can be folded into the operands of
3372       // its operands.
3373       // TODO: Generalize this to non-constants by using known-bits information.
3374       Type *Ty = LHS->getType();
3375       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3376       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3377       // For non-power-of-two values, effectively round the value up to the
3378       // nearest power of two.
3379       if (!RHSC->getAPInt().isPowerOf2())
3380         ++MaxShiftAmt;
3381       IntegerType *ExtTy =
3382         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3383       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3384         if (const SCEVConstant *Step =
3385             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3386           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3387           const APInt &StepInt = Step->getAPInt();
3388           const APInt &DivInt = RHSC->getAPInt();
3389           if (!StepInt.urem(DivInt) &&
3390               getZeroExtendExpr(AR, ExtTy) ==
3391               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3392                             getZeroExtendExpr(Step, ExtTy),
3393                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3394             SmallVector<const SCEV *, 4> Operands;
3395             for (const SCEV *Op : AR->operands())
3396               Operands.push_back(getUDivExpr(Op, RHS));
3397             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3398           }
3399           /// Get a canonical UDivExpr for a recurrence.
3400           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3401           // We can currently only fold X%N if X is constant.
3402           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3403           if (StartC && !DivInt.urem(StepInt) &&
3404               getZeroExtendExpr(AR, ExtTy) ==
3405               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3406                             getZeroExtendExpr(Step, ExtTy),
3407                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3408             const APInt &StartInt = StartC->getAPInt();
3409             const APInt &StartRem = StartInt.urem(StepInt);
3410             if (StartRem != 0) {
3411               const SCEV *NewLHS =
3412                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3413                                 AR->getLoop(), SCEV::FlagNW);
3414               if (LHS != NewLHS) {
3415                 LHS = NewLHS;
3416 
3417                 // Reset the ID to include the new LHS, and check if it is
3418                 // already cached.
3419                 ID.clear();
3420                 ID.AddInteger(scUDivExpr);
3421                 ID.AddPointer(LHS);
3422                 ID.AddPointer(RHS);
3423                 IP = nullptr;
3424                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3425                   return S;
3426               }
3427             }
3428           }
3429         }
3430       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3431       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3432         SmallVector<const SCEV *, 4> Operands;
3433         for (const SCEV *Op : M->operands())
3434           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3435         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3436           // Find an operand that's safely divisible.
3437           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3438             const SCEV *Op = M->getOperand(i);
3439             const SCEV *Div = getUDivExpr(Op, RHSC);
3440             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3441               Operands = SmallVector<const SCEV *, 4>(M->operands());
3442               Operands[i] = Div;
3443               return getMulExpr(Operands);
3444             }
3445           }
3446       }
3447 
3448       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3449       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3450         if (auto *DivisorConstant =
3451                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3452           bool Overflow = false;
3453           APInt NewRHS =
3454               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3455           if (Overflow) {
3456             return getConstant(RHSC->getType(), 0, false);
3457           }
3458           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3459         }
3460       }
3461 
3462       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3463       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3464         SmallVector<const SCEV *, 4> Operands;
3465         for (const SCEV *Op : A->operands())
3466           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3467         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3468           Operands.clear();
3469           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3470             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3471             if (isa<SCEVUDivExpr>(Op) ||
3472                 getMulExpr(Op, RHS) != A->getOperand(i))
3473               break;
3474             Operands.push_back(Op);
3475           }
3476           if (Operands.size() == A->getNumOperands())
3477             return getAddExpr(Operands);
3478         }
3479       }
3480 
3481       // Fold if both operands are constant.
3482       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3483         Constant *LHSCV = LHSC->getValue();
3484         Constant *RHSCV = RHSC->getValue();
3485         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3486                                                                    RHSCV)));
3487       }
3488     }
3489   }
3490 
3491   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3492   // changes). Make sure we get a new one.
3493   IP = nullptr;
3494   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3495   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3496                                              LHS, RHS);
3497   UniqueSCEVs.InsertNode(S, IP);
3498   registerUser(S, {LHS, RHS});
3499   return S;
3500 }
3501 
3502 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3503   APInt A = C1->getAPInt().abs();
3504   APInt B = C2->getAPInt().abs();
3505   uint32_t ABW = A.getBitWidth();
3506   uint32_t BBW = B.getBitWidth();
3507 
3508   if (ABW > BBW)
3509     B = B.zext(ABW);
3510   else if (ABW < BBW)
3511     A = A.zext(BBW);
3512 
3513   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3514 }
3515 
3516 /// Get a canonical unsigned division expression, or something simpler if
3517 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3518 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3519 /// it's not exact because the udiv may be clearing bits.
3520 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3521                                               const SCEV *RHS) {
3522   // TODO: we could try to find factors in all sorts of things, but for now we
3523   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3524   // end of this file for inspiration.
3525 
3526   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3527   if (!Mul || !Mul->hasNoUnsignedWrap())
3528     return getUDivExpr(LHS, RHS);
3529 
3530   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3531     // If the mulexpr multiplies by a constant, then that constant must be the
3532     // first element of the mulexpr.
3533     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3534       if (LHSCst == RHSCst) {
3535         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3536         return getMulExpr(Operands);
3537       }
3538 
3539       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3540       // that there's a factor provided by one of the other terms. We need to
3541       // check.
3542       APInt Factor = gcd(LHSCst, RHSCst);
3543       if (!Factor.isIntN(1)) {
3544         LHSCst =
3545             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3546         RHSCst =
3547             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3548         SmallVector<const SCEV *, 2> Operands;
3549         Operands.push_back(LHSCst);
3550         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3551         LHS = getMulExpr(Operands);
3552         RHS = RHSCst;
3553         Mul = dyn_cast<SCEVMulExpr>(LHS);
3554         if (!Mul)
3555           return getUDivExactExpr(LHS, RHS);
3556       }
3557     }
3558   }
3559 
3560   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3561     if (Mul->getOperand(i) == RHS) {
3562       SmallVector<const SCEV *, 2> Operands;
3563       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3564       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3565       return getMulExpr(Operands);
3566     }
3567   }
3568 
3569   return getUDivExpr(LHS, RHS);
3570 }
3571 
3572 /// Get an add recurrence expression for the specified loop.  Simplify the
3573 /// expression as much as possible.
3574 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3575                                            const Loop *L,
3576                                            SCEV::NoWrapFlags Flags) {
3577   SmallVector<const SCEV *, 4> Operands;
3578   Operands.push_back(Start);
3579   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3580     if (StepChrec->getLoop() == L) {
3581       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3582       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3583     }
3584 
3585   Operands.push_back(Step);
3586   return getAddRecExpr(Operands, L, Flags);
3587 }
3588 
3589 /// Get an add recurrence expression for the specified loop.  Simplify the
3590 /// expression as much as possible.
3591 const SCEV *
3592 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3593                                const Loop *L, SCEV::NoWrapFlags Flags) {
3594   if (Operands.size() == 1) return Operands[0];
3595 #ifndef NDEBUG
3596   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3597   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3598     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3599            "SCEVAddRecExpr operand types don't match!");
3600     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3601   }
3602   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3603     assert(isLoopInvariant(Operands[i], L) &&
3604            "SCEVAddRecExpr operand is not loop-invariant!");
3605 #endif
3606 
3607   if (Operands.back()->isZero()) {
3608     Operands.pop_back();
3609     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3610   }
3611 
3612   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3613   // use that information to infer NUW and NSW flags. However, computing a
3614   // BE count requires calling getAddRecExpr, so we may not yet have a
3615   // meaningful BE count at this point (and if we don't, we'd be stuck
3616   // with a SCEVCouldNotCompute as the cached BE count).
3617 
3618   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3619 
3620   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3621   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3622     const Loop *NestedLoop = NestedAR->getLoop();
3623     if (L->contains(NestedLoop)
3624             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3625             : (!NestedLoop->contains(L) &&
3626                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3627       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3628       Operands[0] = NestedAR->getStart();
3629       // AddRecs require their operands be loop-invariant with respect to their
3630       // loops. Don't perform this transformation if it would break this
3631       // requirement.
3632       bool AllInvariant = all_of(
3633           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3634 
3635       if (AllInvariant) {
3636         // Create a recurrence for the outer loop with the same step size.
3637         //
3638         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3639         // inner recurrence has the same property.
3640         SCEV::NoWrapFlags OuterFlags =
3641           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3642 
3643         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3644         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3645           return isLoopInvariant(Op, NestedLoop);
3646         });
3647 
3648         if (AllInvariant) {
3649           // Ok, both add recurrences are valid after the transformation.
3650           //
3651           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3652           // the outer recurrence has the same property.
3653           SCEV::NoWrapFlags InnerFlags =
3654             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3655           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3656         }
3657       }
3658       // Reset Operands to its original state.
3659       Operands[0] = NestedAR;
3660     }
3661   }
3662 
3663   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3664   // already have one, otherwise create a new one.
3665   return getOrCreateAddRecExpr(Operands, L, Flags);
3666 }
3667 
3668 const SCEV *
3669 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3670                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3671   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3672   // getSCEV(Base)->getType() has the same address space as Base->getType()
3673   // because SCEV::getType() preserves the address space.
3674   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3675   const bool AssumeInBoundsFlags = [&]() {
3676     if (!GEP->isInBounds())
3677       return false;
3678 
3679     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3680     // but to do that, we have to ensure that said flag is valid in the entire
3681     // defined scope of the SCEV.
3682     auto *GEPI = dyn_cast<Instruction>(GEP);
3683     // TODO: non-instructions have global scope.  We might be able to prove
3684     // some global scope cases
3685     return GEPI && isSCEVExprNeverPoison(GEPI);
3686   }();
3687 
3688   SCEV::NoWrapFlags OffsetWrap =
3689     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3690 
3691   Type *CurTy = GEP->getType();
3692   bool FirstIter = true;
3693   SmallVector<const SCEV *, 4> Offsets;
3694   for (const SCEV *IndexExpr : IndexExprs) {
3695     // Compute the (potentially symbolic) offset in bytes for this index.
3696     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3697       // For a struct, add the member offset.
3698       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3699       unsigned FieldNo = Index->getZExtValue();
3700       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3701       Offsets.push_back(FieldOffset);
3702 
3703       // Update CurTy to the type of the field at Index.
3704       CurTy = STy->getTypeAtIndex(Index);
3705     } else {
3706       // Update CurTy to its element type.
3707       if (FirstIter) {
3708         assert(isa<PointerType>(CurTy) &&
3709                "The first index of a GEP indexes a pointer");
3710         CurTy = GEP->getSourceElementType();
3711         FirstIter = false;
3712       } else {
3713         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3714       }
3715       // For an array, add the element offset, explicitly scaled.
3716       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3717       // Getelementptr indices are signed.
3718       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3719 
3720       // Multiply the index by the element size to compute the element offset.
3721       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3722       Offsets.push_back(LocalOffset);
3723     }
3724   }
3725 
3726   // Handle degenerate case of GEP without offsets.
3727   if (Offsets.empty())
3728     return BaseExpr;
3729 
3730   // Add the offsets together, assuming nsw if inbounds.
3731   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3732   // Add the base address and the offset. We cannot use the nsw flag, as the
3733   // base address is unsigned. However, if we know that the offset is
3734   // non-negative, we can use nuw.
3735   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3736                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3737   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3738   assert(BaseExpr->getType() == GEPExpr->getType() &&
3739          "GEP should not change type mid-flight.");
3740   return GEPExpr;
3741 }
3742 
3743 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3744                                                ArrayRef<const SCEV *> Ops) {
3745   FoldingSetNodeID ID;
3746   ID.AddInteger(SCEVType);
3747   for (const SCEV *Op : Ops)
3748     ID.AddPointer(Op);
3749   void *IP = nullptr;
3750   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3751 }
3752 
3753 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3754   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3755   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3756 }
3757 
3758 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3759                                            SmallVectorImpl<const SCEV *> &Ops) {
3760   assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3761   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3762   if (Ops.size() == 1) return Ops[0];
3763 #ifndef NDEBUG
3764   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3765   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3766     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3767            "Operand types don't match!");
3768     assert(Ops[0]->getType()->isPointerTy() ==
3769                Ops[i]->getType()->isPointerTy() &&
3770            "min/max should be consistently pointerish");
3771   }
3772 #endif
3773 
3774   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3775   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3776 
3777   // Sort by complexity, this groups all similar expression types together.
3778   GroupByComplexity(Ops, &LI, DT);
3779 
3780   // Check if we have created the same expression before.
3781   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3782     return S;
3783   }
3784 
3785   // If there are any constants, fold them together.
3786   unsigned Idx = 0;
3787   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3788     ++Idx;
3789     assert(Idx < Ops.size());
3790     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3791       if (Kind == scSMaxExpr)
3792         return APIntOps::smax(LHS, RHS);
3793       else if (Kind == scSMinExpr)
3794         return APIntOps::smin(LHS, RHS);
3795       else if (Kind == scUMaxExpr)
3796         return APIntOps::umax(LHS, RHS);
3797       else if (Kind == scUMinExpr)
3798         return APIntOps::umin(LHS, RHS);
3799       llvm_unreachable("Unknown SCEV min/max opcode");
3800     };
3801 
3802     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3803       // We found two constants, fold them together!
3804       ConstantInt *Fold = ConstantInt::get(
3805           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3806       Ops[0] = getConstant(Fold);
3807       Ops.erase(Ops.begin()+1);  // Erase the folded element
3808       if (Ops.size() == 1) return Ops[0];
3809       LHSC = cast<SCEVConstant>(Ops[0]);
3810     }
3811 
3812     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3813     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3814 
3815     if (IsMax ? IsMinV : IsMaxV) {
3816       // If we are left with a constant minimum(/maximum)-int, strip it off.
3817       Ops.erase(Ops.begin());
3818       --Idx;
3819     } else if (IsMax ? IsMaxV : IsMinV) {
3820       // If we have a max(/min) with a constant maximum(/minimum)-int,
3821       // it will always be the extremum.
3822       return LHSC;
3823     }
3824 
3825     if (Ops.size() == 1) return Ops[0];
3826   }
3827 
3828   // Find the first operation of the same kind
3829   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3830     ++Idx;
3831 
3832   // Check to see if one of the operands is of the same kind. If so, expand its
3833   // operands onto our operand list, and recurse to simplify.
3834   if (Idx < Ops.size()) {
3835     bool DeletedAny = false;
3836     while (Ops[Idx]->getSCEVType() == Kind) {
3837       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3838       Ops.erase(Ops.begin()+Idx);
3839       Ops.append(SMME->op_begin(), SMME->op_end());
3840       DeletedAny = true;
3841     }
3842 
3843     if (DeletedAny)
3844       return getMinMaxExpr(Kind, Ops);
3845   }
3846 
3847   // Okay, check to see if the same value occurs in the operand list twice.  If
3848   // so, delete one.  Since we sorted the list, these values are required to
3849   // be adjacent.
3850   llvm::CmpInst::Predicate GEPred =
3851       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3852   llvm::CmpInst::Predicate LEPred =
3853       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3854   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3855   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3856   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3857     if (Ops[i] == Ops[i + 1] ||
3858         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3859       //  X op Y op Y  -->  X op Y
3860       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3861       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3862       --i;
3863       --e;
3864     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3865                                                Ops[i + 1])) {
3866       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3867       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3868       --i;
3869       --e;
3870     }
3871   }
3872 
3873   if (Ops.size() == 1) return Ops[0];
3874 
3875   assert(!Ops.empty() && "Reduced smax down to nothing!");
3876 
3877   // Okay, it looks like we really DO need an expr.  Check to see if we
3878   // already have one, otherwise create a new one.
3879   FoldingSetNodeID ID;
3880   ID.AddInteger(Kind);
3881   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3882     ID.AddPointer(Ops[i]);
3883   void *IP = nullptr;
3884   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3885   if (ExistingSCEV)
3886     return ExistingSCEV;
3887   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3888   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3889   SCEV *S = new (SCEVAllocator)
3890       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3891 
3892   UniqueSCEVs.InsertNode(S, IP);
3893   registerUser(S, Ops);
3894   return S;
3895 }
3896 
3897 namespace {
3898 
3899 class SCEVSequentialMinMaxDeduplicatingVisitor final
3900     : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3901                          Optional<const SCEV *>> {
3902   using RetVal = Optional<const SCEV *>;
3903   using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3904 
3905   ScalarEvolution &SE;
3906   const SCEVTypes RootKind; // Must be a sequential min/max expression.
3907   const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3908   SmallPtrSet<const SCEV *, 16> SeenOps;
3909 
3910   bool canRecurseInto(SCEVTypes Kind) const {
3911     // We can only recurse into the SCEV expression of the same effective type
3912     // as the type of our root SCEV expression.
3913     return RootKind == Kind || NonSequentialRootKind == Kind;
3914   };
3915 
3916   RetVal visitAnyMinMaxExpr(const SCEV *S) {
3917     assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3918            "Only for min/max expressions.");
3919     SCEVTypes Kind = S->getSCEVType();
3920 
3921     if (!canRecurseInto(Kind))
3922       return S;
3923 
3924     auto *NAry = cast<SCEVNAryExpr>(S);
3925     SmallVector<const SCEV *> NewOps;
3926     bool Changed =
3927         visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps);
3928 
3929     if (!Changed)
3930       return S;
3931     if (NewOps.empty())
3932       return None;
3933 
3934     return isa<SCEVSequentialMinMaxExpr>(S)
3935                ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3936                : SE.getMinMaxExpr(Kind, NewOps);
3937   }
3938 
3939   RetVal visit(const SCEV *S) {
3940     // Has the whole operand been seen already?
3941     if (!SeenOps.insert(S).second)
3942       return None;
3943     return Base::visit(S);
3944   }
3945 
3946 public:
3947   SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3948                                            SCEVTypes RootKind)
3949       : SE(SE), RootKind(RootKind),
3950         NonSequentialRootKind(
3951             SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
3952                 RootKind)) {}
3953 
3954   bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
3955                          SmallVectorImpl<const SCEV *> &NewOps) {
3956     bool Changed = false;
3957     SmallVector<const SCEV *> Ops;
3958     Ops.reserve(OrigOps.size());
3959 
3960     for (const SCEV *Op : OrigOps) {
3961       RetVal NewOp = visit(Op);
3962       if (NewOp != Op)
3963         Changed = true;
3964       if (NewOp)
3965         Ops.emplace_back(*NewOp);
3966     }
3967 
3968     if (Changed)
3969       NewOps = std::move(Ops);
3970     return Changed;
3971   }
3972 
3973   RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
3974 
3975   RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
3976 
3977   RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
3978 
3979   RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
3980 
3981   RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
3982 
3983   RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
3984 
3985   RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
3986 
3987   RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
3988 
3989   RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
3990 
3991   RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
3992     return visitAnyMinMaxExpr(Expr);
3993   }
3994 
3995   RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
3996     return visitAnyMinMaxExpr(Expr);
3997   }
3998 
3999   RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4000     return visitAnyMinMaxExpr(Expr);
4001   }
4002 
4003   RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4004     return visitAnyMinMaxExpr(Expr);
4005   }
4006 
4007   RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4008     return visitAnyMinMaxExpr(Expr);
4009   }
4010 
4011   RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4012 
4013   RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4014 };
4015 
4016 } // namespace
4017 
4018 /// Return true if V is poison given that AssumedPoison is already poison.
4019 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4020   // The only way poison may be introduced in a SCEV expression is from a
4021   // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4022   // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4023   // introduce poison -- they encode guaranteed, non-speculated knowledge.
4024   //
4025   // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4026   // with the notable exception of umin_seq, where only poison from the first
4027   // operand is (unconditionally) propagated.
4028   struct SCEVPoisonCollector {
4029     bool LookThroughSeq;
4030     SmallPtrSet<const SCEV *, 4> MaybePoison;
4031     SCEVPoisonCollector(bool LookThroughSeq) : LookThroughSeq(LookThroughSeq) {}
4032 
4033     bool follow(const SCEV *S) {
4034       // TODO: We can always follow the first operand, but the SCEVTraversal
4035       // API doesn't support this.
4036       if (!LookThroughSeq && isa<SCEVSequentialMinMaxExpr>(S))
4037         return false;
4038 
4039       if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4040         if (!isGuaranteedNotToBePoison(SU->getValue()))
4041           MaybePoison.insert(S);
4042       }
4043       return true;
4044     }
4045     bool isDone() const { return false; }
4046   };
4047 
4048   // First collect all SCEVs that might result in AssumedPoison to be poison.
4049   // We need to look through umin_seq here, because we want to find all SCEVs
4050   // that *might* result in poison, not only those that are *required* to.
4051   SCEVPoisonCollector PC1(/* LookThroughSeq */ true);
4052   visitAll(AssumedPoison, PC1);
4053 
4054   // AssumedPoison is never poison. As the assumption is false, the implication
4055   // is true. Don't bother walking the other SCEV in this case.
4056   if (PC1.MaybePoison.empty())
4057     return true;
4058 
4059   // Collect all SCEVs in S that, if poison, *will* result in S being poison
4060   // as well. We cannot look through umin_seq here, as its argument only *may*
4061   // make the result poison.
4062   SCEVPoisonCollector PC2(/* LookThroughSeq */ false);
4063   visitAll(S, PC2);
4064 
4065   // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4066   // it will also make S poison by being part of PC2.MaybePoison.
4067   return all_of(PC1.MaybePoison,
4068                 [&](const SCEV *S) { return PC2.MaybePoison.contains(S); });
4069 }
4070 
4071 const SCEV *
4072 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4073                                          SmallVectorImpl<const SCEV *> &Ops) {
4074   assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4075          "Not a SCEVSequentialMinMaxExpr!");
4076   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4077   if (Ops.size() == 1)
4078     return Ops[0];
4079   if (Ops.size() == 2 &&
4080       any_of(Ops, [](const SCEV *Op) { return isa<SCEVConstant>(Op); }))
4081     return getMinMaxExpr(
4082         SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4083         Ops);
4084 #ifndef NDEBUG
4085   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4086   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4087     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4088            "Operand types don't match!");
4089     assert(Ops[0]->getType()->isPointerTy() ==
4090                Ops[i]->getType()->isPointerTy() &&
4091            "min/max should be consistently pointerish");
4092   }
4093 #endif
4094 
4095   // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4096   // so we can *NOT* do any kind of sorting of the expressions!
4097 
4098   // Check if we have created the same expression before.
4099   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4100     return S;
4101 
4102   // FIXME: there are *some* simplifications that we can do here.
4103 
4104   // Keep only the first instance of an operand.
4105   {
4106     SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4107     bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4108     if (Changed)
4109       return getSequentialMinMaxExpr(Kind, Ops);
4110   }
4111 
4112   // Check to see if one of the operands is of the same kind. If so, expand its
4113   // operands onto our operand list, and recurse to simplify.
4114   {
4115     unsigned Idx = 0;
4116     bool DeletedAny = false;
4117     while (Idx < Ops.size()) {
4118       if (Ops[Idx]->getSCEVType() != Kind) {
4119         ++Idx;
4120         continue;
4121       }
4122       const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4123       Ops.erase(Ops.begin() + Idx);
4124       Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end());
4125       DeletedAny = true;
4126     }
4127 
4128     if (DeletedAny)
4129       return getSequentialMinMaxExpr(Kind, Ops);
4130   }
4131 
4132   // In %x umin_seq %y, if %y being poison implies %x is also poison, we can
4133   // use a non-sequential umin instead.
4134   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4135     if (::impliesPoison(Ops[i], Ops[i - 1])) {
4136       SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4137       Ops[i - 1] = getMinMaxExpr(
4138           SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4139           SeqOps);
4140       Ops.erase(Ops.begin() + i);
4141       return getSequentialMinMaxExpr(Kind, Ops);
4142     }
4143   }
4144 
4145   // Okay, it looks like we really DO need an expr.  Check to see if we
4146   // already have one, otherwise create a new one.
4147   FoldingSetNodeID ID;
4148   ID.AddInteger(Kind);
4149   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4150     ID.AddPointer(Ops[i]);
4151   void *IP = nullptr;
4152   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4153   if (ExistingSCEV)
4154     return ExistingSCEV;
4155 
4156   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4157   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4158   SCEV *S = new (SCEVAllocator)
4159       SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4160 
4161   UniqueSCEVs.InsertNode(S, IP);
4162   registerUser(S, Ops);
4163   return S;
4164 }
4165 
4166 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4167   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4168   return getSMaxExpr(Ops);
4169 }
4170 
4171 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4172   return getMinMaxExpr(scSMaxExpr, Ops);
4173 }
4174 
4175 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4176   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4177   return getUMaxExpr(Ops);
4178 }
4179 
4180 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4181   return getMinMaxExpr(scUMaxExpr, Ops);
4182 }
4183 
4184 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4185                                          const SCEV *RHS) {
4186   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4187   return getSMinExpr(Ops);
4188 }
4189 
4190 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4191   return getMinMaxExpr(scSMinExpr, Ops);
4192 }
4193 
4194 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4195                                          bool Sequential) {
4196   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4197   return getUMinExpr(Ops, Sequential);
4198 }
4199 
4200 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4201                                          bool Sequential) {
4202   return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4203                     : getMinMaxExpr(scUMinExpr, Ops);
4204 }
4205 
4206 const SCEV *
4207 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
4208                                              ScalableVectorType *ScalableTy) {
4209   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
4210   Constant *One = ConstantInt::get(IntTy, 1);
4211   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
4212   // Note that the expression we created is the final expression, we don't
4213   // want to simplify it any further Also, if we call a normal getSCEV(),
4214   // we'll end up in an endless recursion. So just create an SCEVUnknown.
4215   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
4216 }
4217 
4218 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4219   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
4220     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
4221   // We can bypass creating a target-independent constant expression and then
4222   // folding it back into a ConstantInt. This is just a compile-time
4223   // optimization.
4224   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4225 }
4226 
4227 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4228   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
4229     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
4230   // We can bypass creating a target-independent constant expression and then
4231   // folding it back into a ConstantInt. This is just a compile-time
4232   // optimization.
4233   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4234 }
4235 
4236 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4237                                              StructType *STy,
4238                                              unsigned FieldNo) {
4239   // We can bypass creating a target-independent constant expression and then
4240   // folding it back into a ConstantInt. This is just a compile-time
4241   // optimization.
4242   return getConstant(
4243       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
4244 }
4245 
4246 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4247   // Don't attempt to do anything other than create a SCEVUnknown object
4248   // here.  createSCEV only calls getUnknown after checking for all other
4249   // interesting possibilities, and any other code that calls getUnknown
4250   // is doing so in order to hide a value from SCEV canonicalization.
4251 
4252   FoldingSetNodeID ID;
4253   ID.AddInteger(scUnknown);
4254   ID.AddPointer(V);
4255   void *IP = nullptr;
4256   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4257     assert(cast<SCEVUnknown>(S)->getValue() == V &&
4258            "Stale SCEVUnknown in uniquing map!");
4259     return S;
4260   }
4261   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4262                                             FirstUnknown);
4263   FirstUnknown = cast<SCEVUnknown>(S);
4264   UniqueSCEVs.InsertNode(S, IP);
4265   return S;
4266 }
4267 
4268 //===----------------------------------------------------------------------===//
4269 //            Basic SCEV Analysis and PHI Idiom Recognition Code
4270 //
4271 
4272 /// Test if values of the given type are analyzable within the SCEV
4273 /// framework. This primarily includes integer types, and it can optionally
4274 /// include pointer types if the ScalarEvolution class has access to
4275 /// target-specific information.
4276 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4277   // Integers and pointers are always SCEVable.
4278   return Ty->isIntOrPtrTy();
4279 }
4280 
4281 /// Return the size in bits of the specified type, for which isSCEVable must
4282 /// return true.
4283 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4284   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4285   if (Ty->isPointerTy())
4286     return getDataLayout().getIndexTypeSizeInBits(Ty);
4287   return getDataLayout().getTypeSizeInBits(Ty);
4288 }
4289 
4290 /// Return a type with the same bitwidth as the given type and which represents
4291 /// how SCEV will treat the given type, for which isSCEVable must return
4292 /// true. For pointer types, this is the pointer index sized integer type.
4293 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4294   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4295 
4296   if (Ty->isIntegerTy())
4297     return Ty;
4298 
4299   // The only other support type is pointer.
4300   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4301   return getDataLayout().getIndexType(Ty);
4302 }
4303 
4304 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4305   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4306 }
4307 
4308 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4309                                                          const SCEV *B) {
4310   /// For a valid use point to exist, the defining scope of one operand
4311   /// must dominate the other.
4312   bool PreciseA, PreciseB;
4313   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4314   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4315   if (!PreciseA || !PreciseB)
4316     // Can't tell.
4317     return false;
4318   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4319     DT.dominates(ScopeB, ScopeA);
4320 }
4321 
4322 
4323 const SCEV *ScalarEvolution::getCouldNotCompute() {
4324   return CouldNotCompute.get();
4325 }
4326 
4327 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4328   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4329     auto *SU = dyn_cast<SCEVUnknown>(S);
4330     return SU && SU->getValue() == nullptr;
4331   });
4332 
4333   return !ContainsNulls;
4334 }
4335 
4336 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4337   HasRecMapType::iterator I = HasRecMap.find(S);
4338   if (I != HasRecMap.end())
4339     return I->second;
4340 
4341   bool FoundAddRec =
4342       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4343   HasRecMap.insert({S, FoundAddRec});
4344   return FoundAddRec;
4345 }
4346 
4347 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4348 /// by the value and offset from any ValueOffsetPair in the set.
4349 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4350   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4351   if (SI == ExprValueMap.end())
4352     return None;
4353 #ifndef NDEBUG
4354   if (VerifySCEVMap) {
4355     // Check there is no dangling Value in the set returned.
4356     for (Value *V : SI->second)
4357       assert(ValueExprMap.count(V));
4358   }
4359 #endif
4360   return SI->second.getArrayRef();
4361 }
4362 
4363 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4364 /// cannot be used separately. eraseValueFromMap should be used to remove
4365 /// V from ValueExprMap and ExprValueMap at the same time.
4366 void ScalarEvolution::eraseValueFromMap(Value *V) {
4367   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4368   if (I != ValueExprMap.end()) {
4369     auto EVIt = ExprValueMap.find(I->second);
4370     bool Removed = EVIt->second.remove(V);
4371     (void) Removed;
4372     assert(Removed && "Value not in ExprValueMap?");
4373     ValueExprMap.erase(I);
4374   }
4375 }
4376 
4377 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4378   // A recursive query may have already computed the SCEV. It should be
4379   // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4380   // inferred nowrap flags.
4381   auto It = ValueExprMap.find_as(V);
4382   if (It == ValueExprMap.end()) {
4383     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4384     ExprValueMap[S].insert(V);
4385   }
4386 }
4387 
4388 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4389 /// create a new one.
4390 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4391   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4392 
4393   const SCEV *S = getExistingSCEV(V);
4394   if (S == nullptr) {
4395     S = createSCEV(V);
4396     // During PHI resolution, it is possible to create two SCEVs for the same
4397     // V, so it is needed to double check whether V->S is inserted into
4398     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4399     std::pair<ValueExprMapType::iterator, bool> Pair =
4400         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4401     if (Pair.second)
4402       ExprValueMap[S].insert(V);
4403   }
4404   return S;
4405 }
4406 
4407 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4408   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4409 
4410   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4411   if (I != ValueExprMap.end()) {
4412     const SCEV *S = I->second;
4413     assert(checkValidity(S) &&
4414            "existing SCEV has not been properly invalidated");
4415     return S;
4416   }
4417   return nullptr;
4418 }
4419 
4420 /// Return a SCEV corresponding to -V = -1*V
4421 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4422                                              SCEV::NoWrapFlags Flags) {
4423   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4424     return getConstant(
4425                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4426 
4427   Type *Ty = V->getType();
4428   Ty = getEffectiveSCEVType(Ty);
4429   return getMulExpr(V, getMinusOne(Ty), Flags);
4430 }
4431 
4432 /// If Expr computes ~A, return A else return nullptr
4433 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4434   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4435   if (!Add || Add->getNumOperands() != 2 ||
4436       !Add->getOperand(0)->isAllOnesValue())
4437     return nullptr;
4438 
4439   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4440   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4441       !AddRHS->getOperand(0)->isAllOnesValue())
4442     return nullptr;
4443 
4444   return AddRHS->getOperand(1);
4445 }
4446 
4447 /// Return a SCEV corresponding to ~V = -1-V
4448 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4449   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4450 
4451   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4452     return getConstant(
4453                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4454 
4455   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4456   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4457     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4458       SmallVector<const SCEV *, 2> MatchedOperands;
4459       for (const SCEV *Operand : MME->operands()) {
4460         const SCEV *Matched = MatchNotExpr(Operand);
4461         if (!Matched)
4462           return (const SCEV *)nullptr;
4463         MatchedOperands.push_back(Matched);
4464       }
4465       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4466                            MatchedOperands);
4467     };
4468     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4469       return Replaced;
4470   }
4471 
4472   Type *Ty = V->getType();
4473   Ty = getEffectiveSCEVType(Ty);
4474   return getMinusSCEV(getMinusOne(Ty), V);
4475 }
4476 
4477 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4478   assert(P->getType()->isPointerTy());
4479 
4480   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4481     // The base of an AddRec is the first operand.
4482     SmallVector<const SCEV *> Ops{AddRec->operands()};
4483     Ops[0] = removePointerBase(Ops[0]);
4484     // Don't try to transfer nowrap flags for now. We could in some cases
4485     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4486     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4487   }
4488   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4489     // The base of an Add is the pointer operand.
4490     SmallVector<const SCEV *> Ops{Add->operands()};
4491     const SCEV **PtrOp = nullptr;
4492     for (const SCEV *&AddOp : Ops) {
4493       if (AddOp->getType()->isPointerTy()) {
4494         assert(!PtrOp && "Cannot have multiple pointer ops");
4495         PtrOp = &AddOp;
4496       }
4497     }
4498     *PtrOp = removePointerBase(*PtrOp);
4499     // Don't try to transfer nowrap flags for now. We could in some cases
4500     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4501     return getAddExpr(Ops);
4502   }
4503   // Any other expression must be a pointer base.
4504   return getZero(P->getType());
4505 }
4506 
4507 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4508                                           SCEV::NoWrapFlags Flags,
4509                                           unsigned Depth) {
4510   // Fast path: X - X --> 0.
4511   if (LHS == RHS)
4512     return getZero(LHS->getType());
4513 
4514   // If we subtract two pointers with different pointer bases, bail.
4515   // Eventually, we're going to add an assertion to getMulExpr that we
4516   // can't multiply by a pointer.
4517   if (RHS->getType()->isPointerTy()) {
4518     if (!LHS->getType()->isPointerTy() ||
4519         getPointerBase(LHS) != getPointerBase(RHS))
4520       return getCouldNotCompute();
4521     LHS = removePointerBase(LHS);
4522     RHS = removePointerBase(RHS);
4523   }
4524 
4525   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4526   // makes it so that we cannot make much use of NUW.
4527   auto AddFlags = SCEV::FlagAnyWrap;
4528   const bool RHSIsNotMinSigned =
4529       !getSignedRangeMin(RHS).isMinSignedValue();
4530   if (hasFlags(Flags, SCEV::FlagNSW)) {
4531     // Let M be the minimum representable signed value. Then (-1)*RHS
4532     // signed-wraps if and only if RHS is M. That can happen even for
4533     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4534     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4535     // (-1)*RHS, we need to prove that RHS != M.
4536     //
4537     // If LHS is non-negative and we know that LHS - RHS does not
4538     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4539     // either by proving that RHS > M or that LHS >= 0.
4540     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4541       AddFlags = SCEV::FlagNSW;
4542     }
4543   }
4544 
4545   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4546   // RHS is NSW and LHS >= 0.
4547   //
4548   // The difficulty here is that the NSW flag may have been proven
4549   // relative to a loop that is to be found in a recurrence in LHS and
4550   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4551   // larger scope than intended.
4552   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4553 
4554   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4555 }
4556 
4557 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4558                                                      unsigned Depth) {
4559   Type *SrcTy = V->getType();
4560   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4561          "Cannot truncate or zero extend with non-integer arguments!");
4562   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4563     return V;  // No conversion
4564   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4565     return getTruncateExpr(V, Ty, Depth);
4566   return getZeroExtendExpr(V, Ty, Depth);
4567 }
4568 
4569 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4570                                                      unsigned Depth) {
4571   Type *SrcTy = V->getType();
4572   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4573          "Cannot truncate or zero extend with non-integer arguments!");
4574   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4575     return V;  // No conversion
4576   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4577     return getTruncateExpr(V, Ty, Depth);
4578   return getSignExtendExpr(V, Ty, Depth);
4579 }
4580 
4581 const SCEV *
4582 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4583   Type *SrcTy = V->getType();
4584   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4585          "Cannot noop or zero extend with non-integer arguments!");
4586   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4587          "getNoopOrZeroExtend cannot truncate!");
4588   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4589     return V;  // No conversion
4590   return getZeroExtendExpr(V, Ty);
4591 }
4592 
4593 const SCEV *
4594 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4595   Type *SrcTy = V->getType();
4596   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4597          "Cannot noop or sign extend with non-integer arguments!");
4598   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4599          "getNoopOrSignExtend cannot truncate!");
4600   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4601     return V;  // No conversion
4602   return getSignExtendExpr(V, Ty);
4603 }
4604 
4605 const SCEV *
4606 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4607   Type *SrcTy = V->getType();
4608   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4609          "Cannot noop or any extend with non-integer arguments!");
4610   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4611          "getNoopOrAnyExtend cannot truncate!");
4612   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4613     return V;  // No conversion
4614   return getAnyExtendExpr(V, Ty);
4615 }
4616 
4617 const SCEV *
4618 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4619   Type *SrcTy = V->getType();
4620   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4621          "Cannot truncate or noop with non-integer arguments!");
4622   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4623          "getTruncateOrNoop cannot extend!");
4624   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4625     return V;  // No conversion
4626   return getTruncateExpr(V, Ty);
4627 }
4628 
4629 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4630                                                         const SCEV *RHS) {
4631   const SCEV *PromotedLHS = LHS;
4632   const SCEV *PromotedRHS = RHS;
4633 
4634   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4635     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4636   else
4637     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4638 
4639   return getUMaxExpr(PromotedLHS, PromotedRHS);
4640 }
4641 
4642 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4643                                                         const SCEV *RHS,
4644                                                         bool Sequential) {
4645   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4646   return getUMinFromMismatchedTypes(Ops, Sequential);
4647 }
4648 
4649 const SCEV *
4650 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4651                                             bool Sequential) {
4652   assert(!Ops.empty() && "At least one operand must be!");
4653   // Trivial case.
4654   if (Ops.size() == 1)
4655     return Ops[0];
4656 
4657   // Find the max type first.
4658   Type *MaxType = nullptr;
4659   for (auto *S : Ops)
4660     if (MaxType)
4661       MaxType = getWiderType(MaxType, S->getType());
4662     else
4663       MaxType = S->getType();
4664   assert(MaxType && "Failed to find maximum type!");
4665 
4666   // Extend all ops to max type.
4667   SmallVector<const SCEV *, 2> PromotedOps;
4668   for (auto *S : Ops)
4669     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4670 
4671   // Generate umin.
4672   return getUMinExpr(PromotedOps, Sequential);
4673 }
4674 
4675 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4676   // A pointer operand may evaluate to a nonpointer expression, such as null.
4677   if (!V->getType()->isPointerTy())
4678     return V;
4679 
4680   while (true) {
4681     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4682       V = AddRec->getStart();
4683     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4684       const SCEV *PtrOp = nullptr;
4685       for (const SCEV *AddOp : Add->operands()) {
4686         if (AddOp->getType()->isPointerTy()) {
4687           assert(!PtrOp && "Cannot have multiple pointer ops");
4688           PtrOp = AddOp;
4689         }
4690       }
4691       assert(PtrOp && "Must have pointer op");
4692       V = PtrOp;
4693     } else // Not something we can look further into.
4694       return V;
4695   }
4696 }
4697 
4698 /// Push users of the given Instruction onto the given Worklist.
4699 static void PushDefUseChildren(Instruction *I,
4700                                SmallVectorImpl<Instruction *> &Worklist,
4701                                SmallPtrSetImpl<Instruction *> &Visited) {
4702   // Push the def-use children onto the Worklist stack.
4703   for (User *U : I->users()) {
4704     auto *UserInsn = cast<Instruction>(U);
4705     if (Visited.insert(UserInsn).second)
4706       Worklist.push_back(UserInsn);
4707   }
4708 }
4709 
4710 namespace {
4711 
4712 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4713 /// expression in case its Loop is L. If it is not L then
4714 /// if IgnoreOtherLoops is true then use AddRec itself
4715 /// otherwise rewrite cannot be done.
4716 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4717 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4718 public:
4719   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4720                              bool IgnoreOtherLoops = true) {
4721     SCEVInitRewriter Rewriter(L, SE);
4722     const SCEV *Result = Rewriter.visit(S);
4723     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4724       return SE.getCouldNotCompute();
4725     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4726                ? SE.getCouldNotCompute()
4727                : Result;
4728   }
4729 
4730   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4731     if (!SE.isLoopInvariant(Expr, L))
4732       SeenLoopVariantSCEVUnknown = true;
4733     return Expr;
4734   }
4735 
4736   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4737     // Only re-write AddRecExprs for this loop.
4738     if (Expr->getLoop() == L)
4739       return Expr->getStart();
4740     SeenOtherLoops = true;
4741     return Expr;
4742   }
4743 
4744   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4745 
4746   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4747 
4748 private:
4749   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4750       : SCEVRewriteVisitor(SE), L(L) {}
4751 
4752   const Loop *L;
4753   bool SeenLoopVariantSCEVUnknown = false;
4754   bool SeenOtherLoops = false;
4755 };
4756 
4757 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4758 /// increment expression in case its Loop is L. If it is not L then
4759 /// use AddRec itself.
4760 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4761 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4762 public:
4763   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4764     SCEVPostIncRewriter Rewriter(L, SE);
4765     const SCEV *Result = Rewriter.visit(S);
4766     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4767         ? SE.getCouldNotCompute()
4768         : Result;
4769   }
4770 
4771   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4772     if (!SE.isLoopInvariant(Expr, L))
4773       SeenLoopVariantSCEVUnknown = true;
4774     return Expr;
4775   }
4776 
4777   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4778     // Only re-write AddRecExprs for this loop.
4779     if (Expr->getLoop() == L)
4780       return Expr->getPostIncExpr(SE);
4781     SeenOtherLoops = true;
4782     return Expr;
4783   }
4784 
4785   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4786 
4787   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4788 
4789 private:
4790   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4791       : SCEVRewriteVisitor(SE), L(L) {}
4792 
4793   const Loop *L;
4794   bool SeenLoopVariantSCEVUnknown = false;
4795   bool SeenOtherLoops = false;
4796 };
4797 
4798 /// This class evaluates the compare condition by matching it against the
4799 /// condition of loop latch. If there is a match we assume a true value
4800 /// for the condition while building SCEV nodes.
4801 class SCEVBackedgeConditionFolder
4802     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4803 public:
4804   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4805                              ScalarEvolution &SE) {
4806     bool IsPosBECond = false;
4807     Value *BECond = nullptr;
4808     if (BasicBlock *Latch = L->getLoopLatch()) {
4809       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4810       if (BI && BI->isConditional()) {
4811         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4812                "Both outgoing branches should not target same header!");
4813         BECond = BI->getCondition();
4814         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4815       } else {
4816         return S;
4817       }
4818     }
4819     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4820     return Rewriter.visit(S);
4821   }
4822 
4823   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4824     const SCEV *Result = Expr;
4825     bool InvariantF = SE.isLoopInvariant(Expr, L);
4826 
4827     if (!InvariantF) {
4828       Instruction *I = cast<Instruction>(Expr->getValue());
4829       switch (I->getOpcode()) {
4830       case Instruction::Select: {
4831         SelectInst *SI = cast<SelectInst>(I);
4832         Optional<const SCEV *> Res =
4833             compareWithBackedgeCondition(SI->getCondition());
4834         if (Res.hasValue()) {
4835           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4836           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4837         }
4838         break;
4839       }
4840       default: {
4841         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4842         if (Res.hasValue())
4843           Result = Res.getValue();
4844         break;
4845       }
4846       }
4847     }
4848     return Result;
4849   }
4850 
4851 private:
4852   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4853                                        bool IsPosBECond, ScalarEvolution &SE)
4854       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4855         IsPositiveBECond(IsPosBECond) {}
4856 
4857   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4858 
4859   const Loop *L;
4860   /// Loop back condition.
4861   Value *BackedgeCond = nullptr;
4862   /// Set to true if loop back is on positive branch condition.
4863   bool IsPositiveBECond;
4864 };
4865 
4866 Optional<const SCEV *>
4867 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4868 
4869   // If value matches the backedge condition for loop latch,
4870   // then return a constant evolution node based on loopback
4871   // branch taken.
4872   if (BackedgeCond == IC)
4873     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4874                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4875   return None;
4876 }
4877 
4878 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4879 public:
4880   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4881                              ScalarEvolution &SE) {
4882     SCEVShiftRewriter Rewriter(L, SE);
4883     const SCEV *Result = Rewriter.visit(S);
4884     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4885   }
4886 
4887   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4888     // Only allow AddRecExprs for this loop.
4889     if (!SE.isLoopInvariant(Expr, L))
4890       Valid = false;
4891     return Expr;
4892   }
4893 
4894   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4895     if (Expr->getLoop() == L && Expr->isAffine())
4896       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4897     Valid = false;
4898     return Expr;
4899   }
4900 
4901   bool isValid() { return Valid; }
4902 
4903 private:
4904   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4905       : SCEVRewriteVisitor(SE), L(L) {}
4906 
4907   const Loop *L;
4908   bool Valid = true;
4909 };
4910 
4911 } // end anonymous namespace
4912 
4913 SCEV::NoWrapFlags
4914 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4915   if (!AR->isAffine())
4916     return SCEV::FlagAnyWrap;
4917 
4918   using OBO = OverflowingBinaryOperator;
4919 
4920   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4921 
4922   if (!AR->hasNoSignedWrap()) {
4923     ConstantRange AddRecRange = getSignedRange(AR);
4924     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4925 
4926     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4927         Instruction::Add, IncRange, OBO::NoSignedWrap);
4928     if (NSWRegion.contains(AddRecRange))
4929       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4930   }
4931 
4932   if (!AR->hasNoUnsignedWrap()) {
4933     ConstantRange AddRecRange = getUnsignedRange(AR);
4934     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4935 
4936     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4937         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4938     if (NUWRegion.contains(AddRecRange))
4939       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4940   }
4941 
4942   return Result;
4943 }
4944 
4945 SCEV::NoWrapFlags
4946 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4947   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4948 
4949   if (AR->hasNoSignedWrap())
4950     return Result;
4951 
4952   if (!AR->isAffine())
4953     return Result;
4954 
4955   const SCEV *Step = AR->getStepRecurrence(*this);
4956   const Loop *L = AR->getLoop();
4957 
4958   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4959   // Note that this serves two purposes: It filters out loops that are
4960   // simply not analyzable, and it covers the case where this code is
4961   // being called from within backedge-taken count analysis, such that
4962   // attempting to ask for the backedge-taken count would likely result
4963   // in infinite recursion. In the later case, the analysis code will
4964   // cope with a conservative value, and it will take care to purge
4965   // that value once it has finished.
4966   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4967 
4968   // Normally, in the cases we can prove no-overflow via a
4969   // backedge guarding condition, we can also compute a backedge
4970   // taken count for the loop.  The exceptions are assumptions and
4971   // guards present in the loop -- SCEV is not great at exploiting
4972   // these to compute max backedge taken counts, but can still use
4973   // these to prove lack of overflow.  Use this fact to avoid
4974   // doing extra work that may not pay off.
4975 
4976   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4977       AC.assumptions().empty())
4978     return Result;
4979 
4980   // If the backedge is guarded by a comparison with the pre-inc  value the
4981   // addrec is safe. Also, if the entry is guarded by a comparison with the
4982   // start value and the backedge is guarded by a comparison with the post-inc
4983   // value, the addrec is safe.
4984   ICmpInst::Predicate Pred;
4985   const SCEV *OverflowLimit =
4986     getSignedOverflowLimitForStep(Step, &Pred, this);
4987   if (OverflowLimit &&
4988       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4989        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4990     Result = setFlags(Result, SCEV::FlagNSW);
4991   }
4992   return Result;
4993 }
4994 SCEV::NoWrapFlags
4995 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4996   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4997 
4998   if (AR->hasNoUnsignedWrap())
4999     return Result;
5000 
5001   if (!AR->isAffine())
5002     return Result;
5003 
5004   const SCEV *Step = AR->getStepRecurrence(*this);
5005   unsigned BitWidth = getTypeSizeInBits(AR->getType());
5006   const Loop *L = AR->getLoop();
5007 
5008   // Check whether the backedge-taken count is SCEVCouldNotCompute.
5009   // Note that this serves two purposes: It filters out loops that are
5010   // simply not analyzable, and it covers the case where this code is
5011   // being called from within backedge-taken count analysis, such that
5012   // attempting to ask for the backedge-taken count would likely result
5013   // in infinite recursion. In the later case, the analysis code will
5014   // cope with a conservative value, and it will take care to purge
5015   // that value once it has finished.
5016   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5017 
5018   // Normally, in the cases we can prove no-overflow via a
5019   // backedge guarding condition, we can also compute a backedge
5020   // taken count for the loop.  The exceptions are assumptions and
5021   // guards present in the loop -- SCEV is not great at exploiting
5022   // these to compute max backedge taken counts, but can still use
5023   // these to prove lack of overflow.  Use this fact to avoid
5024   // doing extra work that may not pay off.
5025 
5026   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5027       AC.assumptions().empty())
5028     return Result;
5029 
5030   // If the backedge is guarded by a comparison with the pre-inc  value the
5031   // addrec is safe. Also, if the entry is guarded by a comparison with the
5032   // start value and the backedge is guarded by a comparison with the post-inc
5033   // value, the addrec is safe.
5034   if (isKnownPositive(Step)) {
5035     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5036                                 getUnsignedRangeMax(Step));
5037     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5038         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5039       Result = setFlags(Result, SCEV::FlagNUW);
5040     }
5041   }
5042 
5043   return Result;
5044 }
5045 
5046 namespace {
5047 
5048 /// Represents an abstract binary operation.  This may exist as a
5049 /// normal instruction or constant expression, or may have been
5050 /// derived from an expression tree.
5051 struct BinaryOp {
5052   unsigned Opcode;
5053   Value *LHS;
5054   Value *RHS;
5055   bool IsNSW = false;
5056   bool IsNUW = false;
5057 
5058   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5059   /// constant expression.
5060   Operator *Op = nullptr;
5061 
5062   explicit BinaryOp(Operator *Op)
5063       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5064         Op(Op) {
5065     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5066       IsNSW = OBO->hasNoSignedWrap();
5067       IsNUW = OBO->hasNoUnsignedWrap();
5068     }
5069   }
5070 
5071   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5072                     bool IsNUW = false)
5073       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5074 };
5075 
5076 } // end anonymous namespace
5077 
5078 /// Try to map \p V into a BinaryOp, and return \c None on failure.
5079 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
5080   auto *Op = dyn_cast<Operator>(V);
5081   if (!Op)
5082     return None;
5083 
5084   // Implementation detail: all the cleverness here should happen without
5085   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5086   // SCEV expressions when possible, and we should not break that.
5087 
5088   switch (Op->getOpcode()) {
5089   case Instruction::Add:
5090   case Instruction::Sub:
5091   case Instruction::Mul:
5092   case Instruction::UDiv:
5093   case Instruction::URem:
5094   case Instruction::And:
5095   case Instruction::Or:
5096   case Instruction::AShr:
5097   case Instruction::Shl:
5098     return BinaryOp(Op);
5099 
5100   case Instruction::Xor:
5101     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5102       // If the RHS of the xor is a signmask, then this is just an add.
5103       // Instcombine turns add of signmask into xor as a strength reduction step.
5104       if (RHSC->getValue().isSignMask())
5105         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5106     // Binary `xor` is a bit-wise `add`.
5107     if (V->getType()->isIntegerTy(1))
5108       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5109     return BinaryOp(Op);
5110 
5111   case Instruction::LShr:
5112     // Turn logical shift right of a constant into a unsigned divide.
5113     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5114       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5115 
5116       // If the shift count is not less than the bitwidth, the result of
5117       // the shift is undefined. Don't try to analyze it, because the
5118       // resolution chosen here may differ from the resolution chosen in
5119       // other parts of the compiler.
5120       if (SA->getValue().ult(BitWidth)) {
5121         Constant *X =
5122             ConstantInt::get(SA->getContext(),
5123                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5124         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5125       }
5126     }
5127     return BinaryOp(Op);
5128 
5129   case Instruction::ExtractValue: {
5130     auto *EVI = cast<ExtractValueInst>(Op);
5131     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5132       break;
5133 
5134     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5135     if (!WO)
5136       break;
5137 
5138     Instruction::BinaryOps BinOp = WO->getBinaryOp();
5139     bool Signed = WO->isSigned();
5140     // TODO: Should add nuw/nsw flags for mul as well.
5141     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5142       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5143 
5144     // Now that we know that all uses of the arithmetic-result component of
5145     // CI are guarded by the overflow check, we can go ahead and pretend
5146     // that the arithmetic is non-overflowing.
5147     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5148                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5149   }
5150 
5151   default:
5152     break;
5153   }
5154 
5155   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5156   // semantics as a Sub, return a binary sub expression.
5157   if (auto *II = dyn_cast<IntrinsicInst>(V))
5158     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5159       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5160 
5161   return None;
5162 }
5163 
5164 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5165 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5166 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5167 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5168 /// follows one of the following patterns:
5169 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5170 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5171 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5172 /// we return the type of the truncation operation, and indicate whether the
5173 /// truncated type should be treated as signed/unsigned by setting
5174 /// \p Signed to true/false, respectively.
5175 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5176                                bool &Signed, ScalarEvolution &SE) {
5177   // The case where Op == SymbolicPHI (that is, with no type conversions on
5178   // the way) is handled by the regular add recurrence creating logic and
5179   // would have already been triggered in createAddRecForPHI. Reaching it here
5180   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5181   // because one of the other operands of the SCEVAddExpr updating this PHI is
5182   // not invariant).
5183   //
5184   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5185   // this case predicates that allow us to prove that Op == SymbolicPHI will
5186   // be added.
5187   if (Op == SymbolicPHI)
5188     return nullptr;
5189 
5190   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5191   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5192   if (SourceBits != NewBits)
5193     return nullptr;
5194 
5195   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5196   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5197   if (!SExt && !ZExt)
5198     return nullptr;
5199   const SCEVTruncateExpr *Trunc =
5200       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5201            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5202   if (!Trunc)
5203     return nullptr;
5204   const SCEV *X = Trunc->getOperand();
5205   if (X != SymbolicPHI)
5206     return nullptr;
5207   Signed = SExt != nullptr;
5208   return Trunc->getType();
5209 }
5210 
5211 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5212   if (!PN->getType()->isIntegerTy())
5213     return nullptr;
5214   const Loop *L = LI.getLoopFor(PN->getParent());
5215   if (!L || L->getHeader() != PN->getParent())
5216     return nullptr;
5217   return L;
5218 }
5219 
5220 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5221 // computation that updates the phi follows the following pattern:
5222 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5223 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5224 // If so, try to see if it can be rewritten as an AddRecExpr under some
5225 // Predicates. If successful, return them as a pair. Also cache the results
5226 // of the analysis.
5227 //
5228 // Example usage scenario:
5229 //    Say the Rewriter is called for the following SCEV:
5230 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5231 //    where:
5232 //         %X = phi i64 (%Start, %BEValue)
5233 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5234 //    and call this function with %SymbolicPHI = %X.
5235 //
5236 //    The analysis will find that the value coming around the backedge has
5237 //    the following SCEV:
5238 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5239 //    Upon concluding that this matches the desired pattern, the function
5240 //    will return the pair {NewAddRec, SmallPredsVec} where:
5241 //         NewAddRec = {%Start,+,%Step}
5242 //         SmallPredsVec = {P1, P2, P3} as follows:
5243 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5244 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5245 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5246 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5247 //    under the predicates {P1,P2,P3}.
5248 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5249 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5250 //
5251 // TODO's:
5252 //
5253 // 1) Extend the Induction descriptor to also support inductions that involve
5254 //    casts: When needed (namely, when we are called in the context of the
5255 //    vectorizer induction analysis), a Set of cast instructions will be
5256 //    populated by this method, and provided back to isInductionPHI. This is
5257 //    needed to allow the vectorizer to properly record them to be ignored by
5258 //    the cost model and to avoid vectorizing them (otherwise these casts,
5259 //    which are redundant under the runtime overflow checks, will be
5260 //    vectorized, which can be costly).
5261 //
5262 // 2) Support additional induction/PHISCEV patterns: We also want to support
5263 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5264 //    after the induction update operation (the induction increment):
5265 //
5266 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5267 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5268 //
5269 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5270 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5271 //
5272 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5273 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5274 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5275   SmallVector<const SCEVPredicate *, 3> Predicates;
5276 
5277   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5278   // return an AddRec expression under some predicate.
5279 
5280   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5281   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5282   assert(L && "Expecting an integer loop header phi");
5283 
5284   // The loop may have multiple entrances or multiple exits; we can analyze
5285   // this phi as an addrec if it has a unique entry value and a unique
5286   // backedge value.
5287   Value *BEValueV = nullptr, *StartValueV = nullptr;
5288   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5289     Value *V = PN->getIncomingValue(i);
5290     if (L->contains(PN->getIncomingBlock(i))) {
5291       if (!BEValueV) {
5292         BEValueV = V;
5293       } else if (BEValueV != V) {
5294         BEValueV = nullptr;
5295         break;
5296       }
5297     } else if (!StartValueV) {
5298       StartValueV = V;
5299     } else if (StartValueV != V) {
5300       StartValueV = nullptr;
5301       break;
5302     }
5303   }
5304   if (!BEValueV || !StartValueV)
5305     return None;
5306 
5307   const SCEV *BEValue = getSCEV(BEValueV);
5308 
5309   // If the value coming around the backedge is an add with the symbolic
5310   // value we just inserted, possibly with casts that we can ignore under
5311   // an appropriate runtime guard, then we found a simple induction variable!
5312   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5313   if (!Add)
5314     return None;
5315 
5316   // If there is a single occurrence of the symbolic value, possibly
5317   // casted, replace it with a recurrence.
5318   unsigned FoundIndex = Add->getNumOperands();
5319   Type *TruncTy = nullptr;
5320   bool Signed;
5321   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5322     if ((TruncTy =
5323              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5324       if (FoundIndex == e) {
5325         FoundIndex = i;
5326         break;
5327       }
5328 
5329   if (FoundIndex == Add->getNumOperands())
5330     return None;
5331 
5332   // Create an add with everything but the specified operand.
5333   SmallVector<const SCEV *, 8> Ops;
5334   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5335     if (i != FoundIndex)
5336       Ops.push_back(Add->getOperand(i));
5337   const SCEV *Accum = getAddExpr(Ops);
5338 
5339   // The runtime checks will not be valid if the step amount is
5340   // varying inside the loop.
5341   if (!isLoopInvariant(Accum, L))
5342     return None;
5343 
5344   // *** Part2: Create the predicates
5345 
5346   // Analysis was successful: we have a phi-with-cast pattern for which we
5347   // can return an AddRec expression under the following predicates:
5348   //
5349   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5350   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5351   // P2: An Equal predicate that guarantees that
5352   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5353   // P3: An Equal predicate that guarantees that
5354   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5355   //
5356   // As we next prove, the above predicates guarantee that:
5357   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5358   //
5359   //
5360   // More formally, we want to prove that:
5361   //     Expr(i+1) = Start + (i+1) * Accum
5362   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5363   //
5364   // Given that:
5365   // 1) Expr(0) = Start
5366   // 2) Expr(1) = Start + Accum
5367   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5368   // 3) Induction hypothesis (step i):
5369   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5370   //
5371   // Proof:
5372   //  Expr(i+1) =
5373   //   = Start + (i+1)*Accum
5374   //   = (Start + i*Accum) + Accum
5375   //   = Expr(i) + Accum
5376   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5377   //                                                             :: from step i
5378   //
5379   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5380   //
5381   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5382   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5383   //     + Accum                                                     :: from P3
5384   //
5385   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5386   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5387   //
5388   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5389   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5390   //
5391   // By induction, the same applies to all iterations 1<=i<n:
5392   //
5393 
5394   // Create a truncated addrec for which we will add a no overflow check (P1).
5395   const SCEV *StartVal = getSCEV(StartValueV);
5396   const SCEV *PHISCEV =
5397       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5398                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5399 
5400   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5401   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5402   // will be constant.
5403   //
5404   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5405   // add P1.
5406   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5407     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5408         Signed ? SCEVWrapPredicate::IncrementNSSW
5409                : SCEVWrapPredicate::IncrementNUSW;
5410     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5411     Predicates.push_back(AddRecPred);
5412   }
5413 
5414   // Create the Equal Predicates P2,P3:
5415 
5416   // It is possible that the predicates P2 and/or P3 are computable at
5417   // compile time due to StartVal and/or Accum being constants.
5418   // If either one is, then we can check that now and escape if either P2
5419   // or P3 is false.
5420 
5421   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5422   // for each of StartVal and Accum
5423   auto getExtendedExpr = [&](const SCEV *Expr,
5424                              bool CreateSignExtend) -> const SCEV * {
5425     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5426     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5427     const SCEV *ExtendedExpr =
5428         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5429                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5430     return ExtendedExpr;
5431   };
5432 
5433   // Given:
5434   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5435   //               = getExtendedExpr(Expr)
5436   // Determine whether the predicate P: Expr == ExtendedExpr
5437   // is known to be false at compile time
5438   auto PredIsKnownFalse = [&](const SCEV *Expr,
5439                               const SCEV *ExtendedExpr) -> bool {
5440     return Expr != ExtendedExpr &&
5441            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5442   };
5443 
5444   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5445   if (PredIsKnownFalse(StartVal, StartExtended)) {
5446     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5447     return None;
5448   }
5449 
5450   // The Step is always Signed (because the overflow checks are either
5451   // NSSW or NUSW)
5452   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5453   if (PredIsKnownFalse(Accum, AccumExtended)) {
5454     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5455     return None;
5456   }
5457 
5458   auto AppendPredicate = [&](const SCEV *Expr,
5459                              const SCEV *ExtendedExpr) -> void {
5460     if (Expr != ExtendedExpr &&
5461         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5462       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5463       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5464       Predicates.push_back(Pred);
5465     }
5466   };
5467 
5468   AppendPredicate(StartVal, StartExtended);
5469   AppendPredicate(Accum, AccumExtended);
5470 
5471   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5472   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5473   // into NewAR if it will also add the runtime overflow checks specified in
5474   // Predicates.
5475   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5476 
5477   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5478       std::make_pair(NewAR, Predicates);
5479   // Remember the result of the analysis for this SCEV at this locayyytion.
5480   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5481   return PredRewrite;
5482 }
5483 
5484 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5485 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5486   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5487   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5488   if (!L)
5489     return None;
5490 
5491   // Check to see if we already analyzed this PHI.
5492   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5493   if (I != PredicatedSCEVRewrites.end()) {
5494     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5495         I->second;
5496     // Analysis was done before and failed to create an AddRec:
5497     if (Rewrite.first == SymbolicPHI)
5498       return None;
5499     // Analysis was done before and succeeded to create an AddRec under
5500     // a predicate:
5501     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5502     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5503     return Rewrite;
5504   }
5505 
5506   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5507     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5508 
5509   // Record in the cache that the analysis failed
5510   if (!Rewrite) {
5511     SmallVector<const SCEVPredicate *, 3> Predicates;
5512     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5513     return None;
5514   }
5515 
5516   return Rewrite;
5517 }
5518 
5519 // FIXME: This utility is currently required because the Rewriter currently
5520 // does not rewrite this expression:
5521 // {0, +, (sext ix (trunc iy to ix) to iy)}
5522 // into {0, +, %step},
5523 // even when the following Equal predicate exists:
5524 // "%step == (sext ix (trunc iy to ix) to iy)".
5525 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5526     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5527   if (AR1 == AR2)
5528     return true;
5529 
5530   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5531     if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5532         !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5533       return false;
5534     return true;
5535   };
5536 
5537   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5538       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5539     return false;
5540   return true;
5541 }
5542 
5543 /// A helper function for createAddRecFromPHI to handle simple cases.
5544 ///
5545 /// This function tries to find an AddRec expression for the simplest (yet most
5546 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5547 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5548 /// technique for finding the AddRec expression.
5549 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5550                                                       Value *BEValueV,
5551                                                       Value *StartValueV) {
5552   const Loop *L = LI.getLoopFor(PN->getParent());
5553   assert(L && L->getHeader() == PN->getParent());
5554   assert(BEValueV && StartValueV);
5555 
5556   auto BO = MatchBinaryOp(BEValueV, DT);
5557   if (!BO)
5558     return nullptr;
5559 
5560   if (BO->Opcode != Instruction::Add)
5561     return nullptr;
5562 
5563   const SCEV *Accum = nullptr;
5564   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5565     Accum = getSCEV(BO->RHS);
5566   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5567     Accum = getSCEV(BO->LHS);
5568 
5569   if (!Accum)
5570     return nullptr;
5571 
5572   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5573   if (BO->IsNUW)
5574     Flags = setFlags(Flags, SCEV::FlagNUW);
5575   if (BO->IsNSW)
5576     Flags = setFlags(Flags, SCEV::FlagNSW);
5577 
5578   const SCEV *StartVal = getSCEV(StartValueV);
5579   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5580   insertValueToMap(PN, PHISCEV);
5581 
5582   // We can add Flags to the post-inc expression only if we
5583   // know that it is *undefined behavior* for BEValueV to
5584   // overflow.
5585   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5586     assert(isLoopInvariant(Accum, L) &&
5587            "Accum is defined outside L, but is not invariant?");
5588     if (isAddRecNeverPoison(BEInst, L))
5589       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5590   }
5591 
5592   return PHISCEV;
5593 }
5594 
5595 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5596   const Loop *L = LI.getLoopFor(PN->getParent());
5597   if (!L || L->getHeader() != PN->getParent())
5598     return nullptr;
5599 
5600   // The loop may have multiple entrances or multiple exits; we can analyze
5601   // this phi as an addrec if it has a unique entry value and a unique
5602   // backedge value.
5603   Value *BEValueV = nullptr, *StartValueV = nullptr;
5604   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5605     Value *V = PN->getIncomingValue(i);
5606     if (L->contains(PN->getIncomingBlock(i))) {
5607       if (!BEValueV) {
5608         BEValueV = V;
5609       } else if (BEValueV != V) {
5610         BEValueV = nullptr;
5611         break;
5612       }
5613     } else if (!StartValueV) {
5614       StartValueV = V;
5615     } else if (StartValueV != V) {
5616       StartValueV = nullptr;
5617       break;
5618     }
5619   }
5620   if (!BEValueV || !StartValueV)
5621     return nullptr;
5622 
5623   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5624          "PHI node already processed?");
5625 
5626   // First, try to find AddRec expression without creating a fictituos symbolic
5627   // value for PN.
5628   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5629     return S;
5630 
5631   // Handle PHI node value symbolically.
5632   const SCEV *SymbolicName = getUnknown(PN);
5633   insertValueToMap(PN, SymbolicName);
5634 
5635   // Using this symbolic name for the PHI, analyze the value coming around
5636   // the back-edge.
5637   const SCEV *BEValue = getSCEV(BEValueV);
5638 
5639   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5640   // has a special value for the first iteration of the loop.
5641 
5642   // If the value coming around the backedge is an add with the symbolic
5643   // value we just inserted, then we found a simple induction variable!
5644   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5645     // If there is a single occurrence of the symbolic value, replace it
5646     // with a recurrence.
5647     unsigned FoundIndex = Add->getNumOperands();
5648     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5649       if (Add->getOperand(i) == SymbolicName)
5650         if (FoundIndex == e) {
5651           FoundIndex = i;
5652           break;
5653         }
5654 
5655     if (FoundIndex != Add->getNumOperands()) {
5656       // Create an add with everything but the specified operand.
5657       SmallVector<const SCEV *, 8> Ops;
5658       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5659         if (i != FoundIndex)
5660           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5661                                                              L, *this));
5662       const SCEV *Accum = getAddExpr(Ops);
5663 
5664       // This is not a valid addrec if the step amount is varying each
5665       // loop iteration, but is not itself an addrec in this loop.
5666       if (isLoopInvariant(Accum, L) ||
5667           (isa<SCEVAddRecExpr>(Accum) &&
5668            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5669         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5670 
5671         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5672           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5673             if (BO->IsNUW)
5674               Flags = setFlags(Flags, SCEV::FlagNUW);
5675             if (BO->IsNSW)
5676               Flags = setFlags(Flags, SCEV::FlagNSW);
5677           }
5678         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5679           // If the increment is an inbounds GEP, then we know the address
5680           // space cannot be wrapped around. We cannot make any guarantee
5681           // about signed or unsigned overflow because pointers are
5682           // unsigned but we may have a negative index from the base
5683           // pointer. We can guarantee that no unsigned wrap occurs if the
5684           // indices form a positive value.
5685           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5686             Flags = setFlags(Flags, SCEV::FlagNW);
5687 
5688             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5689             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5690               Flags = setFlags(Flags, SCEV::FlagNUW);
5691           }
5692 
5693           // We cannot transfer nuw and nsw flags from subtraction
5694           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5695           // for instance.
5696         }
5697 
5698         const SCEV *StartVal = getSCEV(StartValueV);
5699         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5700 
5701         // Okay, for the entire analysis of this edge we assumed the PHI
5702         // to be symbolic.  We now need to go back and purge all of the
5703         // entries for the scalars that use the symbolic expression.
5704         forgetMemoizedResults(SymbolicName);
5705         insertValueToMap(PN, PHISCEV);
5706 
5707         // We can add Flags to the post-inc expression only if we
5708         // know that it is *undefined behavior* for BEValueV to
5709         // overflow.
5710         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5711           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5712             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5713 
5714         return PHISCEV;
5715       }
5716     }
5717   } else {
5718     // Otherwise, this could be a loop like this:
5719     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5720     // In this case, j = {1,+,1}  and BEValue is j.
5721     // Because the other in-value of i (0) fits the evolution of BEValue
5722     // i really is an addrec evolution.
5723     //
5724     // We can generalize this saying that i is the shifted value of BEValue
5725     // by one iteration:
5726     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5727     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5728     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5729     if (Shifted != getCouldNotCompute() &&
5730         Start != getCouldNotCompute()) {
5731       const SCEV *StartVal = getSCEV(StartValueV);
5732       if (Start == StartVal) {
5733         // Okay, for the entire analysis of this edge we assumed the PHI
5734         // to be symbolic.  We now need to go back and purge all of the
5735         // entries for the scalars that use the symbolic expression.
5736         forgetMemoizedResults(SymbolicName);
5737         insertValueToMap(PN, Shifted);
5738         return Shifted;
5739       }
5740     }
5741   }
5742 
5743   // Remove the temporary PHI node SCEV that has been inserted while intending
5744   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5745   // as it will prevent later (possibly simpler) SCEV expressions to be added
5746   // to the ValueExprMap.
5747   eraseValueFromMap(PN);
5748 
5749   return nullptr;
5750 }
5751 
5752 // Checks if the SCEV S is available at BB.  S is considered available at BB
5753 // if S can be materialized at BB without introducing a fault.
5754 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5755                                BasicBlock *BB) {
5756   struct CheckAvailable {
5757     bool TraversalDone = false;
5758     bool Available = true;
5759 
5760     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5761     BasicBlock *BB = nullptr;
5762     DominatorTree &DT;
5763 
5764     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5765       : L(L), BB(BB), DT(DT) {}
5766 
5767     bool setUnavailable() {
5768       TraversalDone = true;
5769       Available = false;
5770       return false;
5771     }
5772 
5773     bool follow(const SCEV *S) {
5774       switch (S->getSCEVType()) {
5775       case scConstant:
5776       case scPtrToInt:
5777       case scTruncate:
5778       case scZeroExtend:
5779       case scSignExtend:
5780       case scAddExpr:
5781       case scMulExpr:
5782       case scUMaxExpr:
5783       case scSMaxExpr:
5784       case scUMinExpr:
5785       case scSMinExpr:
5786       case scSequentialUMinExpr:
5787         // These expressions are available if their operand(s) is/are.
5788         return true;
5789 
5790       case scAddRecExpr: {
5791         // We allow add recurrences that are on the loop BB is in, or some
5792         // outer loop.  This guarantees availability because the value of the
5793         // add recurrence at BB is simply the "current" value of the induction
5794         // variable.  We can relax this in the future; for instance an add
5795         // recurrence on a sibling dominating loop is also available at BB.
5796         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5797         if (L && (ARLoop == L || ARLoop->contains(L)))
5798           return true;
5799 
5800         return setUnavailable();
5801       }
5802 
5803       case scUnknown: {
5804         // For SCEVUnknown, we check for simple dominance.
5805         const auto *SU = cast<SCEVUnknown>(S);
5806         Value *V = SU->getValue();
5807 
5808         if (isa<Argument>(V))
5809           return false;
5810 
5811         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5812           return false;
5813 
5814         return setUnavailable();
5815       }
5816 
5817       case scUDivExpr:
5818       case scCouldNotCompute:
5819         // We do not try to smart about these at all.
5820         return setUnavailable();
5821       }
5822       llvm_unreachable("Unknown SCEV kind!");
5823     }
5824 
5825     bool isDone() { return TraversalDone; }
5826   };
5827 
5828   CheckAvailable CA(L, BB, DT);
5829   SCEVTraversal<CheckAvailable> ST(CA);
5830 
5831   ST.visitAll(S);
5832   return CA.Available;
5833 }
5834 
5835 // Try to match a control flow sequence that branches out at BI and merges back
5836 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5837 // match.
5838 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5839                           Value *&C, Value *&LHS, Value *&RHS) {
5840   C = BI->getCondition();
5841 
5842   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5843   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5844 
5845   if (!LeftEdge.isSingleEdge())
5846     return false;
5847 
5848   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5849 
5850   Use &LeftUse = Merge->getOperandUse(0);
5851   Use &RightUse = Merge->getOperandUse(1);
5852 
5853   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5854     LHS = LeftUse;
5855     RHS = RightUse;
5856     return true;
5857   }
5858 
5859   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5860     LHS = RightUse;
5861     RHS = LeftUse;
5862     return true;
5863   }
5864 
5865   return false;
5866 }
5867 
5868 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5869   auto IsReachable =
5870       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5871   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5872     const Loop *L = LI.getLoopFor(PN->getParent());
5873 
5874     // We don't want to break LCSSA, even in a SCEV expression tree.
5875     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5876       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5877         return nullptr;
5878 
5879     // Try to match
5880     //
5881     //  br %cond, label %left, label %right
5882     // left:
5883     //  br label %merge
5884     // right:
5885     //  br label %merge
5886     // merge:
5887     //  V = phi [ %x, %left ], [ %y, %right ]
5888     //
5889     // as "select %cond, %x, %y"
5890 
5891     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5892     assert(IDom && "At least the entry block should dominate PN");
5893 
5894     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5895     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5896 
5897     if (BI && BI->isConditional() &&
5898         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5899         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5900         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5901       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5902   }
5903 
5904   return nullptr;
5905 }
5906 
5907 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5908   if (const SCEV *S = createAddRecFromPHI(PN))
5909     return S;
5910 
5911   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5912     return S;
5913 
5914   // If the PHI has a single incoming value, follow that value, unless the
5915   // PHI's incoming blocks are in a different loop, in which case doing so
5916   // risks breaking LCSSA form. Instcombine would normally zap these, but
5917   // it doesn't have DominatorTree information, so it may miss cases.
5918   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5919     if (LI.replacementPreservesLCSSAForm(PN, V))
5920       return getSCEV(V);
5921 
5922   // If it's not a loop phi, we can't handle it yet.
5923   return getUnknown(PN);
5924 }
5925 
5926 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5927                             SCEVTypes RootKind) {
5928   struct FindClosure {
5929     const SCEV *OperandToFind;
5930     const SCEVTypes RootKind; // Must be a sequential min/max expression.
5931     const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5932 
5933     bool Found = false;
5934 
5935     bool canRecurseInto(SCEVTypes Kind) const {
5936       // We can only recurse into the SCEV expression of the same effective type
5937       // as the type of our root SCEV expression, and into zero-extensions.
5938       return RootKind == Kind || NonSequentialRootKind == Kind ||
5939              scZeroExtend == Kind;
5940     };
5941 
5942     FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5943         : OperandToFind(OperandToFind), RootKind(RootKind),
5944           NonSequentialRootKind(
5945               SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5946                   RootKind)) {}
5947 
5948     bool follow(const SCEV *S) {
5949       Found = S == OperandToFind;
5950 
5951       return !isDone() && canRecurseInto(S->getSCEVType());
5952     }
5953 
5954     bool isDone() const { return Found; }
5955   };
5956 
5957   FindClosure FC(OperandToFind, RootKind);
5958   visitAll(Root, FC);
5959   return FC.Found;
5960 }
5961 
5962 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(
5963     Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) {
5964   // Try to match some simple smax or umax patterns.
5965   auto *ICI = Cond;
5966 
5967   Value *LHS = ICI->getOperand(0);
5968   Value *RHS = ICI->getOperand(1);
5969 
5970   switch (ICI->getPredicate()) {
5971   case ICmpInst::ICMP_SLT:
5972   case ICmpInst::ICMP_SLE:
5973   case ICmpInst::ICMP_ULT:
5974   case ICmpInst::ICMP_ULE:
5975     std::swap(LHS, RHS);
5976     LLVM_FALLTHROUGH;
5977   case ICmpInst::ICMP_SGT:
5978   case ICmpInst::ICMP_SGE:
5979   case ICmpInst::ICMP_UGT:
5980   case ICmpInst::ICMP_UGE:
5981     // a > b ? a+x : b+x  ->  max(a, b)+x
5982     // a > b ? b+x : a+x  ->  min(a, b)+x
5983     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5984       bool Signed = ICI->isSigned();
5985       const SCEV *LA = getSCEV(TrueVal);
5986       const SCEV *RA = getSCEV(FalseVal);
5987       const SCEV *LS = getSCEV(LHS);
5988       const SCEV *RS = getSCEV(RHS);
5989       if (LA->getType()->isPointerTy()) {
5990         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5991         // Need to make sure we can't produce weird expressions involving
5992         // negated pointers.
5993         if (LA == LS && RA == RS)
5994           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5995         if (LA == RS && RA == LS)
5996           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5997       }
5998       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5999         if (Op->getType()->isPointerTy()) {
6000           Op = getLosslessPtrToIntExpr(Op);
6001           if (isa<SCEVCouldNotCompute>(Op))
6002             return Op;
6003         }
6004         if (Signed)
6005           Op = getNoopOrSignExtend(Op, I->getType());
6006         else
6007           Op = getNoopOrZeroExtend(Op, I->getType());
6008         return Op;
6009       };
6010       LS = CoerceOperand(LS);
6011       RS = CoerceOperand(RS);
6012       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6013         break;
6014       const SCEV *LDiff = getMinusSCEV(LA, LS);
6015       const SCEV *RDiff = getMinusSCEV(RA, RS);
6016       if (LDiff == RDiff)
6017         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6018                           LDiff);
6019       LDiff = getMinusSCEV(LA, RS);
6020       RDiff = getMinusSCEV(RA, LS);
6021       if (LDiff == RDiff)
6022         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6023                           LDiff);
6024     }
6025     break;
6026   case ICmpInst::ICMP_NE:
6027     // x != 0 ? x+y : C+y  ->  x == 0 ? C+y : x+y
6028     std::swap(TrueVal, FalseVal);
6029     LLVM_FALLTHROUGH;
6030   case ICmpInst::ICMP_EQ:
6031     // x == 0 ? C+y : x+y  ->  umax(x, C)+y   iff C u<= 1
6032     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
6033         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6034       const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
6035       const SCEV *TrueValExpr = getSCEV(TrueVal);    // C+y
6036       const SCEV *FalseValExpr = getSCEV(FalseVal);  // x+y
6037       const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6038       const SCEV *C = getMinusSCEV(TrueValExpr, Y);  // C = (C+y)-y
6039       if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6040         return getAddExpr(getUMaxExpr(X, C), Y);
6041     }
6042     // x == 0 ? 0 : umin    (..., x, ...)  ->  umin_seq(x, umin    (...))
6043     // x == 0 ? 0 : umin_seq(..., x, ...)  ->  umin_seq(x, umin_seq(...))
6044     // x == 0 ? 0 : umin    (..., umin_seq(..., x, ...), ...)
6045     //                    ->  umin_seq(x, umin (..., umin_seq(...), ...))
6046     if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6047         isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6048       const SCEV *X = getSCEV(LHS);
6049       while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6050         X = ZExt->getOperand();
6051       if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) {
6052         const SCEV *FalseValExpr = getSCEV(FalseVal);
6053         if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6054           return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr,
6055                              /*Sequential=*/true);
6056       }
6057     }
6058     break;
6059   default:
6060     break;
6061   }
6062 
6063   return getUnknown(I);
6064 }
6065 
6066 static Optional<const SCEV *>
6067 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6068                               const SCEV *TrueExpr, const SCEV *FalseExpr) {
6069   assert(CondExpr->getType()->isIntegerTy(1) &&
6070          TrueExpr->getType() == FalseExpr->getType() &&
6071          TrueExpr->getType()->isIntegerTy(1) &&
6072          "Unexpected operands of a select.");
6073 
6074   // i1 cond ? i1 x : i1 C  -->  C + (i1  cond ? (i1 x - i1 C) : i1 0)
6075   //                        -->  C + (umin_seq  cond, x - C)
6076   //
6077   // i1 cond ? i1 C : i1 x  -->  C + (i1  cond ? i1 0 : (i1 x - i1 C))
6078   //                        -->  C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6079   //                        -->  C + (umin_seq ~cond, x - C)
6080 
6081   // FIXME: while we can't legally model the case where both of the hands
6082   // are fully variable, we only require that the *difference* is constant.
6083   if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6084     return None;
6085 
6086   const SCEV *X, *C;
6087   if (isa<SCEVConstant>(TrueExpr)) {
6088     CondExpr = SE->getNotSCEV(CondExpr);
6089     X = FalseExpr;
6090     C = TrueExpr;
6091   } else {
6092     X = TrueExpr;
6093     C = FalseExpr;
6094   }
6095   return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6096                                            /*Sequential=*/true));
6097 }
6098 
6099 static Optional<const SCEV *> createNodeForSelectViaUMinSeq(ScalarEvolution *SE,
6100                                                             Value *Cond,
6101                                                             Value *TrueVal,
6102                                                             Value *FalseVal) {
6103   if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6104     return None;
6105 
6106   return createNodeForSelectViaUMinSeq(
6107       SE, SE->getSCEV(Cond), SE->getSCEV(TrueVal), SE->getSCEV(FalseVal));
6108 }
6109 
6110 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6111     Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6112   assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6113   assert(TrueVal->getType() == FalseVal->getType() &&
6114          V->getType() == TrueVal->getType() &&
6115          "Types of select hands and of the result must match.");
6116 
6117   // For now, only deal with i1-typed `select`s.
6118   if (!V->getType()->isIntegerTy(1))
6119     return getUnknown(V);
6120 
6121   if (Optional<const SCEV *> S =
6122           createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6123     return *S;
6124 
6125   return getUnknown(V);
6126 }
6127 
6128 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6129                                                       Value *TrueVal,
6130                                                       Value *FalseVal) {
6131   // Handle "constant" branch or select. This can occur for instance when a
6132   // loop pass transforms an inner loop and moves on to process the outer loop.
6133   if (auto *CI = dyn_cast<ConstantInt>(Cond))
6134     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6135 
6136   if (auto *I = dyn_cast<Instruction>(V)) {
6137     if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6138       const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond(
6139           I, ICI, TrueVal, FalseVal);
6140       if (!isa<SCEVUnknown>(S))
6141         return S;
6142     }
6143   }
6144 
6145   return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6146 }
6147 
6148 /// Expand GEP instructions into add and multiply operations. This allows them
6149 /// to be analyzed by regular SCEV code.
6150 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6151   // Don't attempt to analyze GEPs over unsized objects.
6152   if (!GEP->getSourceElementType()->isSized())
6153     return getUnknown(GEP);
6154 
6155   SmallVector<const SCEV *, 4> IndexExprs;
6156   for (Value *Index : GEP->indices())
6157     IndexExprs.push_back(getSCEV(Index));
6158   return getGEPExpr(GEP, IndexExprs);
6159 }
6160 
6161 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
6162   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6163     return C->getAPInt().countTrailingZeros();
6164 
6165   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
6166     return GetMinTrailingZeros(I->getOperand());
6167 
6168   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
6169     return std::min(GetMinTrailingZeros(T->getOperand()),
6170                     (uint32_t)getTypeSizeInBits(T->getType()));
6171 
6172   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
6173     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6174     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6175                ? getTypeSizeInBits(E->getType())
6176                : OpRes;
6177   }
6178 
6179   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
6180     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6181     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6182                ? getTypeSizeInBits(E->getType())
6183                : OpRes;
6184   }
6185 
6186   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
6187     // The result is the min of all operands results.
6188     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6189     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6190       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6191     return MinOpRes;
6192   }
6193 
6194   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
6195     // The result is the sum of all operands results.
6196     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
6197     uint32_t BitWidth = getTypeSizeInBits(M->getType());
6198     for (unsigned i = 1, e = M->getNumOperands();
6199          SumOpRes != BitWidth && i != e; ++i)
6200       SumOpRes =
6201           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
6202     return SumOpRes;
6203   }
6204 
6205   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
6206     // The result is the min of all operands results.
6207     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6208     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6209       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6210     return MinOpRes;
6211   }
6212 
6213   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
6214     // The result is the min of all operands results.
6215     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6216     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6217       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6218     return MinOpRes;
6219   }
6220 
6221   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
6222     // The result is the min of all operands results.
6223     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6224     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6225       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6226     return MinOpRes;
6227   }
6228 
6229   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6230     // For a SCEVUnknown, ask ValueTracking.
6231     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
6232     return Known.countMinTrailingZeros();
6233   }
6234 
6235   // SCEVUDivExpr
6236   return 0;
6237 }
6238 
6239 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
6240   auto I = MinTrailingZerosCache.find(S);
6241   if (I != MinTrailingZerosCache.end())
6242     return I->second;
6243 
6244   uint32_t Result = GetMinTrailingZerosImpl(S);
6245   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
6246   assert(InsertPair.second && "Should insert a new key");
6247   return InsertPair.first->second;
6248 }
6249 
6250 /// Helper method to assign a range to V from metadata present in the IR.
6251 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6252   if (Instruction *I = dyn_cast<Instruction>(V))
6253     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6254       return getConstantRangeFromMetadata(*MD);
6255 
6256   return None;
6257 }
6258 
6259 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6260                                      SCEV::NoWrapFlags Flags) {
6261   if (AddRec->getNoWrapFlags(Flags) != Flags) {
6262     AddRec->setNoWrapFlags(Flags);
6263     UnsignedRanges.erase(AddRec);
6264     SignedRanges.erase(AddRec);
6265   }
6266 }
6267 
6268 ConstantRange ScalarEvolution::
6269 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6270   const DataLayout &DL = getDataLayout();
6271 
6272   unsigned BitWidth = getTypeSizeInBits(U->getType());
6273   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6274 
6275   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6276   // use information about the trip count to improve our available range.  Note
6277   // that the trip count independent cases are already handled by known bits.
6278   // WARNING: The definition of recurrence used here is subtly different than
6279   // the one used by AddRec (and thus most of this file).  Step is allowed to
6280   // be arbitrarily loop varying here, where AddRec allows only loop invariant
6281   // and other addrecs in the same loop (for non-affine addrecs).  The code
6282   // below intentionally handles the case where step is not loop invariant.
6283   auto *P = dyn_cast<PHINode>(U->getValue());
6284   if (!P)
6285     return FullSet;
6286 
6287   // Make sure that no Phi input comes from an unreachable block. Otherwise,
6288   // even the values that are not available in these blocks may come from them,
6289   // and this leads to false-positive recurrence test.
6290   for (auto *Pred : predecessors(P->getParent()))
6291     if (!DT.isReachableFromEntry(Pred))
6292       return FullSet;
6293 
6294   BinaryOperator *BO;
6295   Value *Start, *Step;
6296   if (!matchSimpleRecurrence(P, BO, Start, Step))
6297     return FullSet;
6298 
6299   // If we found a recurrence in reachable code, we must be in a loop. Note
6300   // that BO might be in some subloop of L, and that's completely okay.
6301   auto *L = LI.getLoopFor(P->getParent());
6302   assert(L && L->getHeader() == P->getParent());
6303   if (!L->contains(BO->getParent()))
6304     // NOTE: This bailout should be an assert instead.  However, asserting
6305     // the condition here exposes a case where LoopFusion is querying SCEV
6306     // with malformed loop information during the midst of the transform.
6307     // There doesn't appear to be an obvious fix, so for the moment bailout
6308     // until the caller issue can be fixed.  PR49566 tracks the bug.
6309     return FullSet;
6310 
6311   // TODO: Extend to other opcodes such as mul, and div
6312   switch (BO->getOpcode()) {
6313   default:
6314     return FullSet;
6315   case Instruction::AShr:
6316   case Instruction::LShr:
6317   case Instruction::Shl:
6318     break;
6319   };
6320 
6321   if (BO->getOperand(0) != P)
6322     // TODO: Handle the power function forms some day.
6323     return FullSet;
6324 
6325   unsigned TC = getSmallConstantMaxTripCount(L);
6326   if (!TC || TC >= BitWidth)
6327     return FullSet;
6328 
6329   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6330   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6331   assert(KnownStart.getBitWidth() == BitWidth &&
6332          KnownStep.getBitWidth() == BitWidth);
6333 
6334   // Compute total shift amount, being careful of overflow and bitwidths.
6335   auto MaxShiftAmt = KnownStep.getMaxValue();
6336   APInt TCAP(BitWidth, TC-1);
6337   bool Overflow = false;
6338   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6339   if (Overflow)
6340     return FullSet;
6341 
6342   switch (BO->getOpcode()) {
6343   default:
6344     llvm_unreachable("filtered out above");
6345   case Instruction::AShr: {
6346     // For each ashr, three cases:
6347     //   shift = 0 => unchanged value
6348     //   saturation => 0 or -1
6349     //   other => a value closer to zero (of the same sign)
6350     // Thus, the end value is closer to zero than the start.
6351     auto KnownEnd = KnownBits::ashr(KnownStart,
6352                                     KnownBits::makeConstant(TotalShift));
6353     if (KnownStart.isNonNegative())
6354       // Analogous to lshr (simply not yet canonicalized)
6355       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6356                                         KnownStart.getMaxValue() + 1);
6357     if (KnownStart.isNegative())
6358       // End >=u Start && End <=s Start
6359       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6360                                         KnownEnd.getMaxValue() + 1);
6361     break;
6362   }
6363   case Instruction::LShr: {
6364     // For each lshr, three cases:
6365     //   shift = 0 => unchanged value
6366     //   saturation => 0
6367     //   other => a smaller positive number
6368     // Thus, the low end of the unsigned range is the last value produced.
6369     auto KnownEnd = KnownBits::lshr(KnownStart,
6370                                     KnownBits::makeConstant(TotalShift));
6371     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6372                                       KnownStart.getMaxValue() + 1);
6373   }
6374   case Instruction::Shl: {
6375     // Iff no bits are shifted out, value increases on every shift.
6376     auto KnownEnd = KnownBits::shl(KnownStart,
6377                                    KnownBits::makeConstant(TotalShift));
6378     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6379       return ConstantRange(KnownStart.getMinValue(),
6380                            KnownEnd.getMaxValue() + 1);
6381     break;
6382   }
6383   };
6384   return FullSet;
6385 }
6386 
6387 /// Determine the range for a particular SCEV.  If SignHint is
6388 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6389 /// with a "cleaner" unsigned (resp. signed) representation.
6390 const ConstantRange &
6391 ScalarEvolution::getRangeRef(const SCEV *S,
6392                              ScalarEvolution::RangeSignHint SignHint) {
6393   DenseMap<const SCEV *, ConstantRange> &Cache =
6394       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6395                                                        : SignedRanges;
6396   ConstantRange::PreferredRangeType RangeType =
6397       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
6398           ? ConstantRange::Unsigned : ConstantRange::Signed;
6399 
6400   // See if we've computed this range already.
6401   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6402   if (I != Cache.end())
6403     return I->second;
6404 
6405   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6406     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6407 
6408   unsigned BitWidth = getTypeSizeInBits(S->getType());
6409   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6410   using OBO = OverflowingBinaryOperator;
6411 
6412   // If the value has known zeros, the maximum value will have those known zeros
6413   // as well.
6414   uint32_t TZ = GetMinTrailingZeros(S);
6415   if (TZ != 0) {
6416     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6417       ConservativeResult =
6418           ConstantRange(APInt::getMinValue(BitWidth),
6419                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6420     else
6421       ConservativeResult = ConstantRange(
6422           APInt::getSignedMinValue(BitWidth),
6423           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6424   }
6425 
6426   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6427     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6428     unsigned WrapType = OBO::AnyWrap;
6429     if (Add->hasNoSignedWrap())
6430       WrapType |= OBO::NoSignedWrap;
6431     if (Add->hasNoUnsignedWrap())
6432       WrapType |= OBO::NoUnsignedWrap;
6433     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6434       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6435                           WrapType, RangeType);
6436     return setRange(Add, SignHint,
6437                     ConservativeResult.intersectWith(X, RangeType));
6438   }
6439 
6440   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6441     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6442     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6443       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6444     return setRange(Mul, SignHint,
6445                     ConservativeResult.intersectWith(X, RangeType));
6446   }
6447 
6448   if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) {
6449     Intrinsic::ID ID;
6450     switch (S->getSCEVType()) {
6451     case scUMaxExpr:
6452       ID = Intrinsic::umax;
6453       break;
6454     case scSMaxExpr:
6455       ID = Intrinsic::smax;
6456       break;
6457     case scUMinExpr:
6458     case scSequentialUMinExpr:
6459       ID = Intrinsic::umin;
6460       break;
6461     case scSMinExpr:
6462       ID = Intrinsic::smin;
6463       break;
6464     default:
6465       llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6466     }
6467 
6468     const auto *NAry = cast<SCEVNAryExpr>(S);
6469     ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint);
6470     for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6471       X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)});
6472     return setRange(S, SignHint,
6473                     ConservativeResult.intersectWith(X, RangeType));
6474   }
6475 
6476   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6477     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6478     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6479     return setRange(UDiv, SignHint,
6480                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6481   }
6482 
6483   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6484     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6485     return setRange(ZExt, SignHint,
6486                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6487                                                      RangeType));
6488   }
6489 
6490   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6491     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6492     return setRange(SExt, SignHint,
6493                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6494                                                      RangeType));
6495   }
6496 
6497   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6498     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6499     return setRange(PtrToInt, SignHint, X);
6500   }
6501 
6502   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6503     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6504     return setRange(Trunc, SignHint,
6505                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6506                                                      RangeType));
6507   }
6508 
6509   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6510     // If there's no unsigned wrap, the value will never be less than its
6511     // initial value.
6512     if (AddRec->hasNoUnsignedWrap()) {
6513       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6514       if (!UnsignedMinValue.isZero())
6515         ConservativeResult = ConservativeResult.intersectWith(
6516             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6517     }
6518 
6519     // If there's no signed wrap, and all the operands except initial value have
6520     // the same sign or zero, the value won't ever be:
6521     // 1: smaller than initial value if operands are non negative,
6522     // 2: bigger than initial value if operands are non positive.
6523     // For both cases, value can not cross signed min/max boundary.
6524     if (AddRec->hasNoSignedWrap()) {
6525       bool AllNonNeg = true;
6526       bool AllNonPos = true;
6527       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6528         if (!isKnownNonNegative(AddRec->getOperand(i)))
6529           AllNonNeg = false;
6530         if (!isKnownNonPositive(AddRec->getOperand(i)))
6531           AllNonPos = false;
6532       }
6533       if (AllNonNeg)
6534         ConservativeResult = ConservativeResult.intersectWith(
6535             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6536                                        APInt::getSignedMinValue(BitWidth)),
6537             RangeType);
6538       else if (AllNonPos)
6539         ConservativeResult = ConservativeResult.intersectWith(
6540             ConstantRange::getNonEmpty(
6541                 APInt::getSignedMinValue(BitWidth),
6542                 getSignedRangeMax(AddRec->getStart()) + 1),
6543             RangeType);
6544     }
6545 
6546     // TODO: non-affine addrec
6547     if (AddRec->isAffine()) {
6548       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6549       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6550           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6551         auto RangeFromAffine = getRangeForAffineAR(
6552             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6553             BitWidth);
6554         ConservativeResult =
6555             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6556 
6557         auto RangeFromFactoring = getRangeViaFactoring(
6558             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6559             BitWidth);
6560         ConservativeResult =
6561             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6562       }
6563 
6564       // Now try symbolic BE count and more powerful methods.
6565       if (UseExpensiveRangeSharpening) {
6566         const SCEV *SymbolicMaxBECount =
6567             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6568         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6569             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6570             AddRec->hasNoSelfWrap()) {
6571           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6572               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6573           ConservativeResult =
6574               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6575         }
6576       }
6577     }
6578 
6579     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6580   }
6581 
6582   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6583 
6584     // Check if the IR explicitly contains !range metadata.
6585     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6586     if (MDRange.hasValue())
6587       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6588                                                             RangeType);
6589 
6590     // Use facts about recurrences in the underlying IR.  Note that add
6591     // recurrences are AddRecExprs and thus don't hit this path.  This
6592     // primarily handles shift recurrences.
6593     auto CR = getRangeForUnknownRecurrence(U);
6594     ConservativeResult = ConservativeResult.intersectWith(CR);
6595 
6596     // See if ValueTracking can give us a useful range.
6597     const DataLayout &DL = getDataLayout();
6598     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6599     if (Known.getBitWidth() != BitWidth)
6600       Known = Known.zextOrTrunc(BitWidth);
6601 
6602     // ValueTracking may be able to compute a tighter result for the number of
6603     // sign bits than for the value of those sign bits.
6604     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6605     if (U->getType()->isPointerTy()) {
6606       // If the pointer size is larger than the index size type, this can cause
6607       // NS to be larger than BitWidth. So compensate for this.
6608       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6609       int ptrIdxDiff = ptrSize - BitWidth;
6610       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6611         NS -= ptrIdxDiff;
6612     }
6613 
6614     if (NS > 1) {
6615       // If we know any of the sign bits, we know all of the sign bits.
6616       if (!Known.Zero.getHiBits(NS).isZero())
6617         Known.Zero.setHighBits(NS);
6618       if (!Known.One.getHiBits(NS).isZero())
6619         Known.One.setHighBits(NS);
6620     }
6621 
6622     if (Known.getMinValue() != Known.getMaxValue() + 1)
6623       ConservativeResult = ConservativeResult.intersectWith(
6624           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6625           RangeType);
6626     if (NS > 1)
6627       ConservativeResult = ConservativeResult.intersectWith(
6628           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6629                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6630           RangeType);
6631 
6632     // A range of Phi is a subset of union of all ranges of its input.
6633     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6634       // Make sure that we do not run over cycled Phis.
6635       if (PendingPhiRanges.insert(Phi).second) {
6636         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6637         for (auto &Op : Phi->operands()) {
6638           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6639           RangeFromOps = RangeFromOps.unionWith(OpRange);
6640           // No point to continue if we already have a full set.
6641           if (RangeFromOps.isFullSet())
6642             break;
6643         }
6644         ConservativeResult =
6645             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6646         bool Erased = PendingPhiRanges.erase(Phi);
6647         assert(Erased && "Failed to erase Phi properly?");
6648         (void) Erased;
6649       }
6650     }
6651 
6652     return setRange(U, SignHint, std::move(ConservativeResult));
6653   }
6654 
6655   return setRange(S, SignHint, std::move(ConservativeResult));
6656 }
6657 
6658 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6659 // values that the expression can take. Initially, the expression has a value
6660 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6661 // argument defines if we treat Step as signed or unsigned.
6662 static ConstantRange getRangeForAffineARHelper(APInt Step,
6663                                                const ConstantRange &StartRange,
6664                                                const APInt &MaxBECount,
6665                                                unsigned BitWidth, bool Signed) {
6666   // If either Step or MaxBECount is 0, then the expression won't change, and we
6667   // just need to return the initial range.
6668   if (Step == 0 || MaxBECount == 0)
6669     return StartRange;
6670 
6671   // If we don't know anything about the initial value (i.e. StartRange is
6672   // FullRange), then we don't know anything about the final range either.
6673   // Return FullRange.
6674   if (StartRange.isFullSet())
6675     return ConstantRange::getFull(BitWidth);
6676 
6677   // If Step is signed and negative, then we use its absolute value, but we also
6678   // note that we're moving in the opposite direction.
6679   bool Descending = Signed && Step.isNegative();
6680 
6681   if (Signed)
6682     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6683     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6684     // This equations hold true due to the well-defined wrap-around behavior of
6685     // APInt.
6686     Step = Step.abs();
6687 
6688   // Check if Offset is more than full span of BitWidth. If it is, the
6689   // expression is guaranteed to overflow.
6690   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6691     return ConstantRange::getFull(BitWidth);
6692 
6693   // Offset is by how much the expression can change. Checks above guarantee no
6694   // overflow here.
6695   APInt Offset = Step * MaxBECount;
6696 
6697   // Minimum value of the final range will match the minimal value of StartRange
6698   // if the expression is increasing and will be decreased by Offset otherwise.
6699   // Maximum value of the final range will match the maximal value of StartRange
6700   // if the expression is decreasing and will be increased by Offset otherwise.
6701   APInt StartLower = StartRange.getLower();
6702   APInt StartUpper = StartRange.getUpper() - 1;
6703   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6704                                    : (StartUpper + std::move(Offset));
6705 
6706   // It's possible that the new minimum/maximum value will fall into the initial
6707   // range (due to wrap around). This means that the expression can take any
6708   // value in this bitwidth, and we have to return full range.
6709   if (StartRange.contains(MovedBoundary))
6710     return ConstantRange::getFull(BitWidth);
6711 
6712   APInt NewLower =
6713       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6714   APInt NewUpper =
6715       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6716   NewUpper += 1;
6717 
6718   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6719   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6720 }
6721 
6722 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6723                                                    const SCEV *Step,
6724                                                    const SCEV *MaxBECount,
6725                                                    unsigned BitWidth) {
6726   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6727          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6728          "Precondition!");
6729 
6730   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6731   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6732 
6733   // First, consider step signed.
6734   ConstantRange StartSRange = getSignedRange(Start);
6735   ConstantRange StepSRange = getSignedRange(Step);
6736 
6737   // If Step can be both positive and negative, we need to find ranges for the
6738   // maximum absolute step values in both directions and union them.
6739   ConstantRange SR =
6740       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6741                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6742   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6743                                               StartSRange, MaxBECountValue,
6744                                               BitWidth, /* Signed = */ true));
6745 
6746   // Next, consider step unsigned.
6747   ConstantRange UR = getRangeForAffineARHelper(
6748       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6749       MaxBECountValue, BitWidth, /* Signed = */ false);
6750 
6751   // Finally, intersect signed and unsigned ranges.
6752   return SR.intersectWith(UR, ConstantRange::Smallest);
6753 }
6754 
6755 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6756     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6757     ScalarEvolution::RangeSignHint SignHint) {
6758   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6759   assert(AddRec->hasNoSelfWrap() &&
6760          "This only works for non-self-wrapping AddRecs!");
6761   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6762   const SCEV *Step = AddRec->getStepRecurrence(*this);
6763   // Only deal with constant step to save compile time.
6764   if (!isa<SCEVConstant>(Step))
6765     return ConstantRange::getFull(BitWidth);
6766   // Let's make sure that we can prove that we do not self-wrap during
6767   // MaxBECount iterations. We need this because MaxBECount is a maximum
6768   // iteration count estimate, and we might infer nw from some exit for which we
6769   // do not know max exit count (or any other side reasoning).
6770   // TODO: Turn into assert at some point.
6771   if (getTypeSizeInBits(MaxBECount->getType()) >
6772       getTypeSizeInBits(AddRec->getType()))
6773     return ConstantRange::getFull(BitWidth);
6774   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6775   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6776   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6777   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6778   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6779                                          MaxItersWithoutWrap))
6780     return ConstantRange::getFull(BitWidth);
6781 
6782   ICmpInst::Predicate LEPred =
6783       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6784   ICmpInst::Predicate GEPred =
6785       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6786   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6787 
6788   // We know that there is no self-wrap. Let's take Start and End values and
6789   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6790   // the iteration. They either lie inside the range [Min(Start, End),
6791   // Max(Start, End)] or outside it:
6792   //
6793   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6794   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6795   //
6796   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6797   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6798   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6799   // Start <= End and step is positive, or Start >= End and step is negative.
6800   const SCEV *Start = AddRec->getStart();
6801   ConstantRange StartRange = getRangeRef(Start, SignHint);
6802   ConstantRange EndRange = getRangeRef(End, SignHint);
6803   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6804   // If they already cover full iteration space, we will know nothing useful
6805   // even if we prove what we want to prove.
6806   if (RangeBetween.isFullSet())
6807     return RangeBetween;
6808   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6809   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6810                                : RangeBetween.isWrappedSet();
6811   if (IsWrappedSet)
6812     return ConstantRange::getFull(BitWidth);
6813 
6814   if (isKnownPositive(Step) &&
6815       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6816     return RangeBetween;
6817   else if (isKnownNegative(Step) &&
6818            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6819     return RangeBetween;
6820   return ConstantRange::getFull(BitWidth);
6821 }
6822 
6823 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6824                                                     const SCEV *Step,
6825                                                     const SCEV *MaxBECount,
6826                                                     unsigned BitWidth) {
6827   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6828   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6829 
6830   struct SelectPattern {
6831     Value *Condition = nullptr;
6832     APInt TrueValue;
6833     APInt FalseValue;
6834 
6835     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6836                            const SCEV *S) {
6837       Optional<unsigned> CastOp;
6838       APInt Offset(BitWidth, 0);
6839 
6840       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6841              "Should be!");
6842 
6843       // Peel off a constant offset:
6844       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6845         // In the future we could consider being smarter here and handle
6846         // {Start+Step,+,Step} too.
6847         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6848           return;
6849 
6850         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6851         S = SA->getOperand(1);
6852       }
6853 
6854       // Peel off a cast operation
6855       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6856         CastOp = SCast->getSCEVType();
6857         S = SCast->getOperand();
6858       }
6859 
6860       using namespace llvm::PatternMatch;
6861 
6862       auto *SU = dyn_cast<SCEVUnknown>(S);
6863       const APInt *TrueVal, *FalseVal;
6864       if (!SU ||
6865           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6866                                           m_APInt(FalseVal)))) {
6867         Condition = nullptr;
6868         return;
6869       }
6870 
6871       TrueValue = *TrueVal;
6872       FalseValue = *FalseVal;
6873 
6874       // Re-apply the cast we peeled off earlier
6875       if (CastOp.hasValue())
6876         switch (*CastOp) {
6877         default:
6878           llvm_unreachable("Unknown SCEV cast type!");
6879 
6880         case scTruncate:
6881           TrueValue = TrueValue.trunc(BitWidth);
6882           FalseValue = FalseValue.trunc(BitWidth);
6883           break;
6884         case scZeroExtend:
6885           TrueValue = TrueValue.zext(BitWidth);
6886           FalseValue = FalseValue.zext(BitWidth);
6887           break;
6888         case scSignExtend:
6889           TrueValue = TrueValue.sext(BitWidth);
6890           FalseValue = FalseValue.sext(BitWidth);
6891           break;
6892         }
6893 
6894       // Re-apply the constant offset we peeled off earlier
6895       TrueValue += Offset;
6896       FalseValue += Offset;
6897     }
6898 
6899     bool isRecognized() { return Condition != nullptr; }
6900   };
6901 
6902   SelectPattern StartPattern(*this, BitWidth, Start);
6903   if (!StartPattern.isRecognized())
6904     return ConstantRange::getFull(BitWidth);
6905 
6906   SelectPattern StepPattern(*this, BitWidth, Step);
6907   if (!StepPattern.isRecognized())
6908     return ConstantRange::getFull(BitWidth);
6909 
6910   if (StartPattern.Condition != StepPattern.Condition) {
6911     // We don't handle this case today; but we could, by considering four
6912     // possibilities below instead of two. I'm not sure if there are cases where
6913     // that will help over what getRange already does, though.
6914     return ConstantRange::getFull(BitWidth);
6915   }
6916 
6917   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6918   // construct arbitrary general SCEV expressions here.  This function is called
6919   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6920   // say) can end up caching a suboptimal value.
6921 
6922   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6923   // C2352 and C2512 (otherwise it isn't needed).
6924 
6925   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6926   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6927   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6928   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6929 
6930   ConstantRange TrueRange =
6931       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6932   ConstantRange FalseRange =
6933       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6934 
6935   return TrueRange.unionWith(FalseRange);
6936 }
6937 
6938 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6939   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6940   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6941 
6942   // Return early if there are no flags to propagate to the SCEV.
6943   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6944   if (BinOp->hasNoUnsignedWrap())
6945     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6946   if (BinOp->hasNoSignedWrap())
6947     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6948   if (Flags == SCEV::FlagAnyWrap)
6949     return SCEV::FlagAnyWrap;
6950 
6951   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6952 }
6953 
6954 const Instruction *
6955 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
6956   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
6957     return &*AddRec->getLoop()->getHeader()->begin();
6958   if (auto *U = dyn_cast<SCEVUnknown>(S))
6959     if (auto *I = dyn_cast<Instruction>(U->getValue()))
6960       return I;
6961   return nullptr;
6962 }
6963 
6964 /// Fills \p Ops with unique operands of \p S, if it has operands. If not,
6965 /// \p Ops remains unmodified.
6966 static void collectUniqueOps(const SCEV *S,
6967                              SmallVectorImpl<const SCEV *> &Ops) {
6968   SmallPtrSet<const SCEV *, 4> Unique;
6969   auto InsertUnique = [&](const SCEV *S) {
6970     if (Unique.insert(S).second)
6971       Ops.push_back(S);
6972   };
6973   if (auto *S2 = dyn_cast<SCEVCastExpr>(S))
6974     for (auto *Op : S2->operands())
6975       InsertUnique(Op);
6976   else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S))
6977     for (auto *Op : S2->operands())
6978       InsertUnique(Op);
6979   else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S))
6980     for (auto *Op : S2->operands())
6981       InsertUnique(Op);
6982 }
6983 
6984 const Instruction *
6985 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
6986                                        bool &Precise) {
6987   Precise = true;
6988   // Do a bounded search of the def relation of the requested SCEVs.
6989   SmallSet<const SCEV *, 16> Visited;
6990   SmallVector<const SCEV *> Worklist;
6991   auto pushOp = [&](const SCEV *S) {
6992     if (!Visited.insert(S).second)
6993       return;
6994     // Threshold of 30 here is arbitrary.
6995     if (Visited.size() > 30) {
6996       Precise = false;
6997       return;
6998     }
6999     Worklist.push_back(S);
7000   };
7001 
7002   for (auto *S : Ops)
7003     pushOp(S);
7004 
7005   const Instruction *Bound = nullptr;
7006   while (!Worklist.empty()) {
7007     auto *S = Worklist.pop_back_val();
7008     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7009       if (!Bound || DT.dominates(Bound, DefI))
7010         Bound = DefI;
7011     } else {
7012       SmallVector<const SCEV *, 4> Ops;
7013       collectUniqueOps(S, Ops);
7014       for (auto *Op : Ops)
7015         pushOp(Op);
7016     }
7017   }
7018   return Bound ? Bound : &*F.getEntryBlock().begin();
7019 }
7020 
7021 const Instruction *
7022 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7023   bool Discard;
7024   return getDefiningScopeBound(Ops, Discard);
7025 }
7026 
7027 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7028                                                         const Instruction *B) {
7029   if (A->getParent() == B->getParent() &&
7030       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7031                                                  B->getIterator()))
7032     return true;
7033 
7034   auto *BLoop = LI.getLoopFor(B->getParent());
7035   if (BLoop && BLoop->getHeader() == B->getParent() &&
7036       BLoop->getLoopPreheader() == A->getParent() &&
7037       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7038                                                  A->getParent()->end()) &&
7039       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7040                                                  B->getIterator()))
7041     return true;
7042   return false;
7043 }
7044 
7045 
7046 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7047   // Only proceed if we can prove that I does not yield poison.
7048   if (!programUndefinedIfPoison(I))
7049     return false;
7050 
7051   // At this point we know that if I is executed, then it does not wrap
7052   // according to at least one of NSW or NUW. If I is not executed, then we do
7053   // not know if the calculation that I represents would wrap. Multiple
7054   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7055   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7056   // derived from other instructions that map to the same SCEV. We cannot make
7057   // that guarantee for cases where I is not executed. So we need to find a
7058   // upper bound on the defining scope for the SCEV, and prove that I is
7059   // executed every time we enter that scope.  When the bounding scope is a
7060   // loop (the common case), this is equivalent to proving I executes on every
7061   // iteration of that loop.
7062   SmallVector<const SCEV *> SCEVOps;
7063   for (const Use &Op : I->operands()) {
7064     // I could be an extractvalue from a call to an overflow intrinsic.
7065     // TODO: We can do better here in some cases.
7066     if (isSCEVable(Op->getType()))
7067       SCEVOps.push_back(getSCEV(Op));
7068   }
7069   auto *DefI = getDefiningScopeBound(SCEVOps);
7070   return isGuaranteedToTransferExecutionTo(DefI, I);
7071 }
7072 
7073 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7074   // If we know that \c I can never be poison period, then that's enough.
7075   if (isSCEVExprNeverPoison(I))
7076     return true;
7077 
7078   // For an add recurrence specifically, we assume that infinite loops without
7079   // side effects are undefined behavior, and then reason as follows:
7080   //
7081   // If the add recurrence is poison in any iteration, it is poison on all
7082   // future iterations (since incrementing poison yields poison). If the result
7083   // of the add recurrence is fed into the loop latch condition and the loop
7084   // does not contain any throws or exiting blocks other than the latch, we now
7085   // have the ability to "choose" whether the backedge is taken or not (by
7086   // choosing a sufficiently evil value for the poison feeding into the branch)
7087   // for every iteration including and after the one in which \p I first became
7088   // poison.  There are two possibilities (let's call the iteration in which \p
7089   // I first became poison as K):
7090   //
7091   //  1. In the set of iterations including and after K, the loop body executes
7092   //     no side effects.  In this case executing the backege an infinte number
7093   //     of times will yield undefined behavior.
7094   //
7095   //  2. In the set of iterations including and after K, the loop body executes
7096   //     at least one side effect.  In this case, that specific instance of side
7097   //     effect is control dependent on poison, which also yields undefined
7098   //     behavior.
7099 
7100   auto *ExitingBB = L->getExitingBlock();
7101   auto *LatchBB = L->getLoopLatch();
7102   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
7103     return false;
7104 
7105   SmallPtrSet<const Instruction *, 16> Pushed;
7106   SmallVector<const Instruction *, 8> PoisonStack;
7107 
7108   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
7109   // things that are known to be poison under that assumption go on the
7110   // PoisonStack.
7111   Pushed.insert(I);
7112   PoisonStack.push_back(I);
7113 
7114   bool LatchControlDependentOnPoison = false;
7115   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
7116     const Instruction *Poison = PoisonStack.pop_back_val();
7117 
7118     for (auto *PoisonUser : Poison->users()) {
7119       if (propagatesPoison(cast<Operator>(PoisonUser))) {
7120         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
7121           PoisonStack.push_back(cast<Instruction>(PoisonUser));
7122       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
7123         assert(BI->isConditional() && "Only possibility!");
7124         if (BI->getParent() == LatchBB) {
7125           LatchControlDependentOnPoison = true;
7126           break;
7127         }
7128       }
7129     }
7130   }
7131 
7132   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
7133 }
7134 
7135 ScalarEvolution::LoopProperties
7136 ScalarEvolution::getLoopProperties(const Loop *L) {
7137   using LoopProperties = ScalarEvolution::LoopProperties;
7138 
7139   auto Itr = LoopPropertiesCache.find(L);
7140   if (Itr == LoopPropertiesCache.end()) {
7141     auto HasSideEffects = [](Instruction *I) {
7142       if (auto *SI = dyn_cast<StoreInst>(I))
7143         return !SI->isSimple();
7144 
7145       return I->mayThrow() || I->mayWriteToMemory();
7146     };
7147 
7148     LoopProperties LP = {/* HasNoAbnormalExits */ true,
7149                          /*HasNoSideEffects*/ true};
7150 
7151     for (auto *BB : L->getBlocks())
7152       for (auto &I : *BB) {
7153         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7154           LP.HasNoAbnormalExits = false;
7155         if (HasSideEffects(&I))
7156           LP.HasNoSideEffects = false;
7157         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7158           break; // We're already as pessimistic as we can get.
7159       }
7160 
7161     auto InsertPair = LoopPropertiesCache.insert({L, LP});
7162     assert(InsertPair.second && "We just checked!");
7163     Itr = InsertPair.first;
7164   }
7165 
7166   return Itr->second;
7167 }
7168 
7169 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7170   // A mustprogress loop without side effects must be finite.
7171   // TODO: The check used here is very conservative.  It's only *specific*
7172   // side effects which are well defined in infinite loops.
7173   return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7174 }
7175 
7176 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7177   if (!isSCEVable(V->getType()))
7178     return getUnknown(V);
7179 
7180   if (Instruction *I = dyn_cast<Instruction>(V)) {
7181     // Don't attempt to analyze instructions in blocks that aren't
7182     // reachable. Such instructions don't matter, and they aren't required
7183     // to obey basic rules for definitions dominating uses which this
7184     // analysis depends on.
7185     if (!DT.isReachableFromEntry(I->getParent()))
7186       return getUnknown(UndefValue::get(V->getType()));
7187   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7188     return getConstant(CI);
7189   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
7190     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
7191   else if (!isa<ConstantExpr>(V))
7192     return getUnknown(V);
7193 
7194   Operator *U = cast<Operator>(V);
7195   if (auto BO = MatchBinaryOp(U, DT)) {
7196     switch (BO->Opcode) {
7197     case Instruction::Add: {
7198       // The simple thing to do would be to just call getSCEV on both operands
7199       // and call getAddExpr with the result. However if we're looking at a
7200       // bunch of things all added together, this can be quite inefficient,
7201       // because it leads to N-1 getAddExpr calls for N ultimate operands.
7202       // Instead, gather up all the operands and make a single getAddExpr call.
7203       // LLVM IR canonical form means we need only traverse the left operands.
7204       SmallVector<const SCEV *, 4> AddOps;
7205       do {
7206         if (BO->Op) {
7207           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7208             AddOps.push_back(OpSCEV);
7209             break;
7210           }
7211 
7212           // If a NUW or NSW flag can be applied to the SCEV for this
7213           // addition, then compute the SCEV for this addition by itself
7214           // with a separate call to getAddExpr. We need to do that
7215           // instead of pushing the operands of the addition onto AddOps,
7216           // since the flags are only known to apply to this particular
7217           // addition - they may not apply to other additions that can be
7218           // formed with operands from AddOps.
7219           const SCEV *RHS = getSCEV(BO->RHS);
7220           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7221           if (Flags != SCEV::FlagAnyWrap) {
7222             const SCEV *LHS = getSCEV(BO->LHS);
7223             if (BO->Opcode == Instruction::Sub)
7224               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7225             else
7226               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7227             break;
7228           }
7229         }
7230 
7231         if (BO->Opcode == Instruction::Sub)
7232           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7233         else
7234           AddOps.push_back(getSCEV(BO->RHS));
7235 
7236         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7237         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7238                        NewBO->Opcode != Instruction::Sub)) {
7239           AddOps.push_back(getSCEV(BO->LHS));
7240           break;
7241         }
7242         BO = NewBO;
7243       } while (true);
7244 
7245       return getAddExpr(AddOps);
7246     }
7247 
7248     case Instruction::Mul: {
7249       SmallVector<const SCEV *, 4> MulOps;
7250       do {
7251         if (BO->Op) {
7252           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7253             MulOps.push_back(OpSCEV);
7254             break;
7255           }
7256 
7257           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7258           if (Flags != SCEV::FlagAnyWrap) {
7259             MulOps.push_back(
7260                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
7261             break;
7262           }
7263         }
7264 
7265         MulOps.push_back(getSCEV(BO->RHS));
7266         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7267         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7268           MulOps.push_back(getSCEV(BO->LHS));
7269           break;
7270         }
7271         BO = NewBO;
7272       } while (true);
7273 
7274       return getMulExpr(MulOps);
7275     }
7276     case Instruction::UDiv:
7277       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7278     case Instruction::URem:
7279       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7280     case Instruction::Sub: {
7281       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7282       if (BO->Op)
7283         Flags = getNoWrapFlagsFromUB(BO->Op);
7284       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
7285     }
7286     case Instruction::And:
7287       // For an expression like x&255 that merely masks off the high bits,
7288       // use zext(trunc(x)) as the SCEV expression.
7289       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7290         if (CI->isZero())
7291           return getSCEV(BO->RHS);
7292         if (CI->isMinusOne())
7293           return getSCEV(BO->LHS);
7294         const APInt &A = CI->getValue();
7295 
7296         // Instcombine's ShrinkDemandedConstant may strip bits out of
7297         // constants, obscuring what would otherwise be a low-bits mask.
7298         // Use computeKnownBits to compute what ShrinkDemandedConstant
7299         // knew about to reconstruct a low-bits mask value.
7300         unsigned LZ = A.countLeadingZeros();
7301         unsigned TZ = A.countTrailingZeros();
7302         unsigned BitWidth = A.getBitWidth();
7303         KnownBits Known(BitWidth);
7304         computeKnownBits(BO->LHS, Known, getDataLayout(),
7305                          0, &AC, nullptr, &DT);
7306 
7307         APInt EffectiveMask =
7308             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7309         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7310           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7311           const SCEV *LHS = getSCEV(BO->LHS);
7312           const SCEV *ShiftedLHS = nullptr;
7313           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7314             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7315               // For an expression like (x * 8) & 8, simplify the multiply.
7316               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
7317               unsigned GCD = std::min(MulZeros, TZ);
7318               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7319               SmallVector<const SCEV*, 4> MulOps;
7320               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7321               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
7322               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7323               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7324             }
7325           }
7326           if (!ShiftedLHS)
7327             ShiftedLHS = getUDivExpr(LHS, MulCount);
7328           return getMulExpr(
7329               getZeroExtendExpr(
7330                   getTruncateExpr(ShiftedLHS,
7331                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7332                   BO->LHS->getType()),
7333               MulCount);
7334         }
7335       }
7336       // Binary `and` is a bit-wise `umin`.
7337       if (BO->LHS->getType()->isIntegerTy(1))
7338         return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7339       break;
7340 
7341     case Instruction::Or:
7342       // If the RHS of the Or is a constant, we may have something like:
7343       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
7344       // optimizations will transparently handle this case.
7345       //
7346       // In order for this transformation to be safe, the LHS must be of the
7347       // form X*(2^n) and the Or constant must be less than 2^n.
7348       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7349         const SCEV *LHS = getSCEV(BO->LHS);
7350         const APInt &CIVal = CI->getValue();
7351         if (GetMinTrailingZeros(LHS) >=
7352             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
7353           // Build a plain add SCEV.
7354           return getAddExpr(LHS, getSCEV(CI),
7355                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
7356         }
7357       }
7358       // Binary `or` is a bit-wise `umax`.
7359       if (BO->LHS->getType()->isIntegerTy(1))
7360         return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7361       break;
7362 
7363     case Instruction::Xor:
7364       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7365         // If the RHS of xor is -1, then this is a not operation.
7366         if (CI->isMinusOne())
7367           return getNotSCEV(getSCEV(BO->LHS));
7368 
7369         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7370         // This is a variant of the check for xor with -1, and it handles
7371         // the case where instcombine has trimmed non-demanded bits out
7372         // of an xor with -1.
7373         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7374           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7375             if (LBO->getOpcode() == Instruction::And &&
7376                 LCI->getValue() == CI->getValue())
7377               if (const SCEVZeroExtendExpr *Z =
7378                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7379                 Type *UTy = BO->LHS->getType();
7380                 const SCEV *Z0 = Z->getOperand();
7381                 Type *Z0Ty = Z0->getType();
7382                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7383 
7384                 // If C is a low-bits mask, the zero extend is serving to
7385                 // mask off the high bits. Complement the operand and
7386                 // re-apply the zext.
7387                 if (CI->getValue().isMask(Z0TySize))
7388                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7389 
7390                 // If C is a single bit, it may be in the sign-bit position
7391                 // before the zero-extend. In this case, represent the xor
7392                 // using an add, which is equivalent, and re-apply the zext.
7393                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7394                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7395                     Trunc.isSignMask())
7396                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7397                                            UTy);
7398               }
7399       }
7400       break;
7401 
7402     case Instruction::Shl:
7403       // Turn shift left of a constant amount into a multiply.
7404       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7405         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7406 
7407         // If the shift count is not less than the bitwidth, the result of
7408         // the shift is undefined. Don't try to analyze it, because the
7409         // resolution chosen here may differ from the resolution chosen in
7410         // other parts of the compiler.
7411         if (SA->getValue().uge(BitWidth))
7412           break;
7413 
7414         // We can safely preserve the nuw flag in all cases. It's also safe to
7415         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7416         // requires special handling. It can be preserved as long as we're not
7417         // left shifting by bitwidth - 1.
7418         auto Flags = SCEV::FlagAnyWrap;
7419         if (BO->Op) {
7420           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7421           if ((MulFlags & SCEV::FlagNSW) &&
7422               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7423             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7424           if (MulFlags & SCEV::FlagNUW)
7425             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7426         }
7427 
7428         ConstantInt *X = ConstantInt::get(
7429             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7430         return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7431       }
7432       break;
7433 
7434     case Instruction::AShr: {
7435       // AShr X, C, where C is a constant.
7436       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7437       if (!CI)
7438         break;
7439 
7440       Type *OuterTy = BO->LHS->getType();
7441       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7442       // If the shift count is not less than the bitwidth, the result of
7443       // the shift is undefined. Don't try to analyze it, because the
7444       // resolution chosen here may differ from the resolution chosen in
7445       // other parts of the compiler.
7446       if (CI->getValue().uge(BitWidth))
7447         break;
7448 
7449       if (CI->isZero())
7450         return getSCEV(BO->LHS); // shift by zero --> noop
7451 
7452       uint64_t AShrAmt = CI->getZExtValue();
7453       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7454 
7455       Operator *L = dyn_cast<Operator>(BO->LHS);
7456       if (L && L->getOpcode() == Instruction::Shl) {
7457         // X = Shl A, n
7458         // Y = AShr X, m
7459         // Both n and m are constant.
7460 
7461         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7462         if (L->getOperand(1) == BO->RHS)
7463           // For a two-shift sext-inreg, i.e. n = m,
7464           // use sext(trunc(x)) as the SCEV expression.
7465           return getSignExtendExpr(
7466               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7467 
7468         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7469         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7470           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7471           if (ShlAmt > AShrAmt) {
7472             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7473             // expression. We already checked that ShlAmt < BitWidth, so
7474             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7475             // ShlAmt - AShrAmt < Amt.
7476             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7477                                             ShlAmt - AShrAmt);
7478             return getSignExtendExpr(
7479                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7480                 getConstant(Mul)), OuterTy);
7481           }
7482         }
7483       }
7484       break;
7485     }
7486     }
7487   }
7488 
7489   switch (U->getOpcode()) {
7490   case Instruction::Trunc:
7491     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7492 
7493   case Instruction::ZExt:
7494     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7495 
7496   case Instruction::SExt:
7497     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7498       // The NSW flag of a subtract does not always survive the conversion to
7499       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7500       // more likely to preserve NSW and allow later AddRec optimisations.
7501       //
7502       // NOTE: This is effectively duplicating this logic from getSignExtend:
7503       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7504       // but by that point the NSW information has potentially been lost.
7505       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7506         Type *Ty = U->getType();
7507         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7508         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7509         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7510       }
7511     }
7512     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7513 
7514   case Instruction::BitCast:
7515     // BitCasts are no-op casts so we just eliminate the cast.
7516     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7517       return getSCEV(U->getOperand(0));
7518     break;
7519 
7520   case Instruction::PtrToInt: {
7521     // Pointer to integer cast is straight-forward, so do model it.
7522     const SCEV *Op = getSCEV(U->getOperand(0));
7523     Type *DstIntTy = U->getType();
7524     // But only if effective SCEV (integer) type is wide enough to represent
7525     // all possible pointer values.
7526     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7527     if (isa<SCEVCouldNotCompute>(IntOp))
7528       return getUnknown(V);
7529     return IntOp;
7530   }
7531   case Instruction::IntToPtr:
7532     // Just don't deal with inttoptr casts.
7533     return getUnknown(V);
7534 
7535   case Instruction::SDiv:
7536     // If both operands are non-negative, this is just an udiv.
7537     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7538         isKnownNonNegative(getSCEV(U->getOperand(1))))
7539       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7540     break;
7541 
7542   case Instruction::SRem:
7543     // If both operands are non-negative, this is just an urem.
7544     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7545         isKnownNonNegative(getSCEV(U->getOperand(1))))
7546       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7547     break;
7548 
7549   case Instruction::GetElementPtr:
7550     return createNodeForGEP(cast<GEPOperator>(U));
7551 
7552   case Instruction::PHI:
7553     return createNodeForPHI(cast<PHINode>(U));
7554 
7555   case Instruction::Select:
7556     return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
7557                                     U->getOperand(2));
7558 
7559   case Instruction::Call:
7560   case Instruction::Invoke:
7561     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7562       return getSCEV(RV);
7563 
7564     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7565       switch (II->getIntrinsicID()) {
7566       case Intrinsic::abs:
7567         return getAbsExpr(
7568             getSCEV(II->getArgOperand(0)),
7569             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7570       case Intrinsic::umax:
7571         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7572                            getSCEV(II->getArgOperand(1)));
7573       case Intrinsic::umin:
7574         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7575                            getSCEV(II->getArgOperand(1)));
7576       case Intrinsic::smax:
7577         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7578                            getSCEV(II->getArgOperand(1)));
7579       case Intrinsic::smin:
7580         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7581                            getSCEV(II->getArgOperand(1)));
7582       case Intrinsic::usub_sat: {
7583         const SCEV *X = getSCEV(II->getArgOperand(0));
7584         const SCEV *Y = getSCEV(II->getArgOperand(1));
7585         const SCEV *ClampedY = getUMinExpr(X, Y);
7586         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7587       }
7588       case Intrinsic::uadd_sat: {
7589         const SCEV *X = getSCEV(II->getArgOperand(0));
7590         const SCEV *Y = getSCEV(II->getArgOperand(1));
7591         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7592         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7593       }
7594       case Intrinsic::start_loop_iterations:
7595         // A start_loop_iterations is just equivalent to the first operand for
7596         // SCEV purposes.
7597         return getSCEV(II->getArgOperand(0));
7598       default:
7599         break;
7600       }
7601     }
7602     break;
7603   }
7604 
7605   return getUnknown(V);
7606 }
7607 
7608 //===----------------------------------------------------------------------===//
7609 //                   Iteration Count Computation Code
7610 //
7611 
7612 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
7613                                                        bool Extend) {
7614   if (isa<SCEVCouldNotCompute>(ExitCount))
7615     return getCouldNotCompute();
7616 
7617   auto *ExitCountType = ExitCount->getType();
7618   assert(ExitCountType->isIntegerTy());
7619 
7620   if (!Extend)
7621     return getAddExpr(ExitCount, getOne(ExitCountType));
7622 
7623   auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
7624                                     1 + ExitCountType->getScalarSizeInBits());
7625   return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
7626                     getOne(WiderType));
7627 }
7628 
7629 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7630   if (!ExitCount)
7631     return 0;
7632 
7633   ConstantInt *ExitConst = ExitCount->getValue();
7634 
7635   // Guard against huge trip counts.
7636   if (ExitConst->getValue().getActiveBits() > 32)
7637     return 0;
7638 
7639   // In case of integer overflow, this returns 0, which is correct.
7640   return ((unsigned)ExitConst->getZExtValue()) + 1;
7641 }
7642 
7643 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7644   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7645   return getConstantTripCount(ExitCount);
7646 }
7647 
7648 unsigned
7649 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7650                                            const BasicBlock *ExitingBlock) {
7651   assert(ExitingBlock && "Must pass a non-null exiting block!");
7652   assert(L->isLoopExiting(ExitingBlock) &&
7653          "Exiting block must actually branch out of the loop!");
7654   const SCEVConstant *ExitCount =
7655       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7656   return getConstantTripCount(ExitCount);
7657 }
7658 
7659 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7660   const auto *MaxExitCount =
7661       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7662   return getConstantTripCount(MaxExitCount);
7663 }
7664 
7665 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
7666   // We can't infer from Array in Irregular Loop.
7667   // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
7668   if (!L->isLoopSimplifyForm() || !L->isInnermost())
7669     return getCouldNotCompute();
7670 
7671   // FIXME: To make the scene more typical, we only analysis loops that have
7672   // one exiting block and that block must be the latch. To make it easier to
7673   // capture loops that have memory access and memory access will be executed
7674   // in each iteration.
7675   const BasicBlock *LoopLatch = L->getLoopLatch();
7676   assert(LoopLatch && "See defination of simplify form loop.");
7677   if (L->getExitingBlock() != LoopLatch)
7678     return getCouldNotCompute();
7679 
7680   const DataLayout &DL = getDataLayout();
7681   SmallVector<const SCEV *> InferCountColl;
7682   for (auto *BB : L->getBlocks()) {
7683     // Go here, we can know that Loop is a single exiting and simplified form
7684     // loop. Make sure that infer from Memory Operation in those BBs must be
7685     // executed in loop. First step, we can make sure that max execution time
7686     // of MemAccessBB in loop represents latch max excution time.
7687     // If MemAccessBB does not dom Latch, skip.
7688     //            Entry
7689     //              │
7690     //        ┌─────▼─────┐
7691     //        │Loop Header◄─────┐
7692     //        └──┬──────┬─┘     │
7693     //           │      │       │
7694     //  ┌────────▼──┐ ┌─▼─────┐ │
7695     //  │MemAccessBB│ │OtherBB│ │
7696     //  └────────┬──┘ └─┬─────┘ │
7697     //           │      │       │
7698     //         ┌─▼──────▼─┐     │
7699     //         │Loop Latch├─────┘
7700     //         └────┬─────┘
7701     //              ▼
7702     //             Exit
7703     if (!DT.dominates(BB, LoopLatch))
7704       continue;
7705 
7706     for (Instruction &Inst : *BB) {
7707       // Find Memory Operation Instruction.
7708       auto *GEP = getLoadStorePointerOperand(&Inst);
7709       if (!GEP)
7710         continue;
7711 
7712       auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
7713       // Do not infer from scalar type, eg."ElemSize = sizeof()".
7714       if (!ElemSize)
7715         continue;
7716 
7717       // Use a existing polynomial recurrence on the trip count.
7718       auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
7719       if (!AddRec)
7720         continue;
7721       auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
7722       auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
7723       if (!ArrBase || !Step)
7724         continue;
7725       assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
7726 
7727       // Only handle { %array + step },
7728       // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
7729       if (AddRec->getStart() != ArrBase)
7730         continue;
7731 
7732       // Memory operation pattern which have gaps.
7733       // Or repeat memory opreation.
7734       // And index of GEP wraps arround.
7735       if (Step->getAPInt().getActiveBits() > 32 ||
7736           Step->getAPInt().getZExtValue() !=
7737               ElemSize->getAPInt().getZExtValue() ||
7738           Step->isZero() || Step->getAPInt().isNegative())
7739         continue;
7740 
7741       // Only infer from stack array which has certain size.
7742       // Make sure alloca instruction is not excuted in loop.
7743       AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
7744       if (!AllocateInst || L->contains(AllocateInst->getParent()))
7745         continue;
7746 
7747       // Make sure only handle normal array.
7748       auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
7749       auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
7750       if (!Ty || !ArrSize || !ArrSize->isOne())
7751         continue;
7752 
7753       // FIXME: Since gep indices are silently zext to the indexing type,
7754       // we will have a narrow gep index which wraps around rather than
7755       // increasing strictly, we shoule ensure that step is increasing
7756       // strictly by the loop iteration.
7757       // Now we can infer a max execution time by MemLength/StepLength.
7758       const SCEV *MemSize =
7759           getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
7760       auto *MaxExeCount =
7761           dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
7762       if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
7763         continue;
7764 
7765       // If the loop reaches the maximum number of executions, we can not
7766       // access bytes starting outside the statically allocated size without
7767       // being immediate UB. But it is allowed to enter loop header one more
7768       // time.
7769       auto *InferCount = dyn_cast<SCEVConstant>(
7770           getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
7771       // Discard the maximum number of execution times under 32bits.
7772       if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
7773         continue;
7774 
7775       InferCountColl.push_back(InferCount);
7776     }
7777   }
7778 
7779   if (InferCountColl.size() == 0)
7780     return getCouldNotCompute();
7781 
7782   return getUMinFromMismatchedTypes(InferCountColl);
7783 }
7784 
7785 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7786   SmallVector<BasicBlock *, 8> ExitingBlocks;
7787   L->getExitingBlocks(ExitingBlocks);
7788 
7789   Optional<unsigned> Res = None;
7790   for (auto *ExitingBB : ExitingBlocks) {
7791     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7792     if (!Res)
7793       Res = Multiple;
7794     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7795   }
7796   return Res.getValueOr(1);
7797 }
7798 
7799 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7800                                                        const SCEV *ExitCount) {
7801   if (ExitCount == getCouldNotCompute())
7802     return 1;
7803 
7804   // Get the trip count
7805   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7806 
7807   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7808   if (!TC)
7809     // Attempt to factor more general cases. Returns the greatest power of
7810     // two divisor. If overflow happens, the trip count expression is still
7811     // divisible by the greatest power of 2 divisor returned.
7812     return 1U << std::min((uint32_t)31,
7813                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7814 
7815   ConstantInt *Result = TC->getValue();
7816 
7817   // Guard against huge trip counts (this requires checking
7818   // for zero to handle the case where the trip count == -1 and the
7819   // addition wraps).
7820   if (!Result || Result->getValue().getActiveBits() > 32 ||
7821       Result->getValue().getActiveBits() == 0)
7822     return 1;
7823 
7824   return (unsigned)Result->getZExtValue();
7825 }
7826 
7827 /// Returns the largest constant divisor of the trip count of this loop as a
7828 /// normal unsigned value, if possible. This means that the actual trip count is
7829 /// always a multiple of the returned value (don't forget the trip count could
7830 /// very well be zero as well!).
7831 ///
7832 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7833 /// multiple of a constant (which is also the case if the trip count is simply
7834 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7835 /// if the trip count is very large (>= 2^32).
7836 ///
7837 /// As explained in the comments for getSmallConstantTripCount, this assumes
7838 /// that control exits the loop via ExitingBlock.
7839 unsigned
7840 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7841                                               const BasicBlock *ExitingBlock) {
7842   assert(ExitingBlock && "Must pass a non-null exiting block!");
7843   assert(L->isLoopExiting(ExitingBlock) &&
7844          "Exiting block must actually branch out of the loop!");
7845   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7846   return getSmallConstantTripMultiple(L, ExitCount);
7847 }
7848 
7849 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7850                                           const BasicBlock *ExitingBlock,
7851                                           ExitCountKind Kind) {
7852   switch (Kind) {
7853   case Exact:
7854   case SymbolicMaximum:
7855     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7856   case ConstantMaximum:
7857     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7858   };
7859   llvm_unreachable("Invalid ExitCountKind!");
7860 }
7861 
7862 const SCEV *
7863 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7864                                                  SmallVector<const SCEVPredicate *, 4> &Preds) {
7865   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7866 }
7867 
7868 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7869                                                    ExitCountKind Kind) {
7870   switch (Kind) {
7871   case Exact:
7872     return getBackedgeTakenInfo(L).getExact(L, this);
7873   case ConstantMaximum:
7874     return getBackedgeTakenInfo(L).getConstantMax(this);
7875   case SymbolicMaximum:
7876     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7877   };
7878   llvm_unreachable("Invalid ExitCountKind!");
7879 }
7880 
7881 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7882   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7883 }
7884 
7885 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7886 static void PushLoopPHIs(const Loop *L,
7887                          SmallVectorImpl<Instruction *> &Worklist,
7888                          SmallPtrSetImpl<Instruction *> &Visited) {
7889   BasicBlock *Header = L->getHeader();
7890 
7891   // Push all Loop-header PHIs onto the Worklist stack.
7892   for (PHINode &PN : Header->phis())
7893     if (Visited.insert(&PN).second)
7894       Worklist.push_back(&PN);
7895 }
7896 
7897 const ScalarEvolution::BackedgeTakenInfo &
7898 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7899   auto &BTI = getBackedgeTakenInfo(L);
7900   if (BTI.hasFullInfo())
7901     return BTI;
7902 
7903   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7904 
7905   if (!Pair.second)
7906     return Pair.first->second;
7907 
7908   BackedgeTakenInfo Result =
7909       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7910 
7911   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7912 }
7913 
7914 ScalarEvolution::BackedgeTakenInfo &
7915 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7916   // Initially insert an invalid entry for this loop. If the insertion
7917   // succeeds, proceed to actually compute a backedge-taken count and
7918   // update the value. The temporary CouldNotCompute value tells SCEV
7919   // code elsewhere that it shouldn't attempt to request a new
7920   // backedge-taken count, which could result in infinite recursion.
7921   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7922       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7923   if (!Pair.second)
7924     return Pair.first->second;
7925 
7926   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7927   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7928   // must be cleared in this scope.
7929   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7930 
7931   // In product build, there are no usage of statistic.
7932   (void)NumTripCountsComputed;
7933   (void)NumTripCountsNotComputed;
7934 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7935   const SCEV *BEExact = Result.getExact(L, this);
7936   if (BEExact != getCouldNotCompute()) {
7937     assert(isLoopInvariant(BEExact, L) &&
7938            isLoopInvariant(Result.getConstantMax(this), L) &&
7939            "Computed backedge-taken count isn't loop invariant for loop!");
7940     ++NumTripCountsComputed;
7941   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7942              isa<PHINode>(L->getHeader()->begin())) {
7943     // Only count loops that have phi nodes as not being computable.
7944     ++NumTripCountsNotComputed;
7945   }
7946 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7947 
7948   // Now that we know more about the trip count for this loop, forget any
7949   // existing SCEV values for PHI nodes in this loop since they are only
7950   // conservative estimates made without the benefit of trip count
7951   // information. This invalidation is not necessary for correctness, and is
7952   // only done to produce more precise results.
7953   if (Result.hasAnyInfo()) {
7954     // Invalidate any expression using an addrec in this loop.
7955     SmallVector<const SCEV *, 8> ToForget;
7956     auto LoopUsersIt = LoopUsers.find(L);
7957     if (LoopUsersIt != LoopUsers.end())
7958       append_range(ToForget, LoopUsersIt->second);
7959     forgetMemoizedResults(ToForget);
7960 
7961     // Invalidate constant-evolved loop header phis.
7962     for (PHINode &PN : L->getHeader()->phis())
7963       ConstantEvolutionLoopExitValue.erase(&PN);
7964   }
7965 
7966   // Re-lookup the insert position, since the call to
7967   // computeBackedgeTakenCount above could result in a
7968   // recusive call to getBackedgeTakenInfo (on a different
7969   // loop), which would invalidate the iterator computed
7970   // earlier.
7971   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7972 }
7973 
7974 void ScalarEvolution::forgetAllLoops() {
7975   // This method is intended to forget all info about loops. It should
7976   // invalidate caches as if the following happened:
7977   // - The trip counts of all loops have changed arbitrarily
7978   // - Every llvm::Value has been updated in place to produce a different
7979   // result.
7980   BackedgeTakenCounts.clear();
7981   PredicatedBackedgeTakenCounts.clear();
7982   BECountUsers.clear();
7983   LoopPropertiesCache.clear();
7984   ConstantEvolutionLoopExitValue.clear();
7985   ValueExprMap.clear();
7986   ValuesAtScopes.clear();
7987   ValuesAtScopesUsers.clear();
7988   LoopDispositions.clear();
7989   BlockDispositions.clear();
7990   UnsignedRanges.clear();
7991   SignedRanges.clear();
7992   ExprValueMap.clear();
7993   HasRecMap.clear();
7994   MinTrailingZerosCache.clear();
7995   PredicatedSCEVRewrites.clear();
7996 }
7997 
7998 void ScalarEvolution::forgetLoop(const Loop *L) {
7999   SmallVector<const Loop *, 16> LoopWorklist(1, L);
8000   SmallVector<Instruction *, 32> Worklist;
8001   SmallPtrSet<Instruction *, 16> Visited;
8002   SmallVector<const SCEV *, 16> ToForget;
8003 
8004   // Iterate over all the loops and sub-loops to drop SCEV information.
8005   while (!LoopWorklist.empty()) {
8006     auto *CurrL = LoopWorklist.pop_back_val();
8007 
8008     // Drop any stored trip count value.
8009     forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8010     forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8011 
8012     // Drop information about predicated SCEV rewrites for this loop.
8013     for (auto I = PredicatedSCEVRewrites.begin();
8014          I != PredicatedSCEVRewrites.end();) {
8015       std::pair<const SCEV *, const Loop *> Entry = I->first;
8016       if (Entry.second == CurrL)
8017         PredicatedSCEVRewrites.erase(I++);
8018       else
8019         ++I;
8020     }
8021 
8022     auto LoopUsersItr = LoopUsers.find(CurrL);
8023     if (LoopUsersItr != LoopUsers.end()) {
8024       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8025                 LoopUsersItr->second.end());
8026     }
8027 
8028     // Drop information about expressions based on loop-header PHIs.
8029     PushLoopPHIs(CurrL, Worklist, Visited);
8030 
8031     while (!Worklist.empty()) {
8032       Instruction *I = Worklist.pop_back_val();
8033 
8034       ValueExprMapType::iterator It =
8035           ValueExprMap.find_as(static_cast<Value *>(I));
8036       if (It != ValueExprMap.end()) {
8037         eraseValueFromMap(It->first);
8038         ToForget.push_back(It->second);
8039         if (PHINode *PN = dyn_cast<PHINode>(I))
8040           ConstantEvolutionLoopExitValue.erase(PN);
8041       }
8042 
8043       PushDefUseChildren(I, Worklist, Visited);
8044     }
8045 
8046     LoopPropertiesCache.erase(CurrL);
8047     // Forget all contained loops too, to avoid dangling entries in the
8048     // ValuesAtScopes map.
8049     LoopWorklist.append(CurrL->begin(), CurrL->end());
8050   }
8051   forgetMemoizedResults(ToForget);
8052 }
8053 
8054 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8055   while (Loop *Parent = L->getParentLoop())
8056     L = Parent;
8057   forgetLoop(L);
8058 }
8059 
8060 void ScalarEvolution::forgetValue(Value *V) {
8061   Instruction *I = dyn_cast<Instruction>(V);
8062   if (!I) return;
8063 
8064   // Drop information about expressions based on loop-header PHIs.
8065   SmallVector<Instruction *, 16> Worklist;
8066   SmallPtrSet<Instruction *, 8> Visited;
8067   SmallVector<const SCEV *, 8> ToForget;
8068   Worklist.push_back(I);
8069   Visited.insert(I);
8070 
8071   while (!Worklist.empty()) {
8072     I = Worklist.pop_back_val();
8073     ValueExprMapType::iterator It =
8074       ValueExprMap.find_as(static_cast<Value *>(I));
8075     if (It != ValueExprMap.end()) {
8076       eraseValueFromMap(It->first);
8077       ToForget.push_back(It->second);
8078       if (PHINode *PN = dyn_cast<PHINode>(I))
8079         ConstantEvolutionLoopExitValue.erase(PN);
8080     }
8081 
8082     PushDefUseChildren(I, Worklist, Visited);
8083   }
8084   forgetMemoizedResults(ToForget);
8085 }
8086 
8087 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
8088   LoopDispositions.clear();
8089 }
8090 
8091 /// Get the exact loop backedge taken count considering all loop exits. A
8092 /// computable result can only be returned for loops with all exiting blocks
8093 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8094 /// is never skipped. This is a valid assumption as long as the loop exits via
8095 /// that test. For precise results, it is the caller's responsibility to specify
8096 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8097 const SCEV *
8098 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8099                                              SmallVector<const SCEVPredicate *, 4> *Preds) const {
8100   // If any exits were not computable, the loop is not computable.
8101   if (!isComplete() || ExitNotTaken.empty())
8102     return SE->getCouldNotCompute();
8103 
8104   const BasicBlock *Latch = L->getLoopLatch();
8105   // All exiting blocks we have collected must dominate the only backedge.
8106   if (!Latch)
8107     return SE->getCouldNotCompute();
8108 
8109   // All exiting blocks we have gathered dominate loop's latch, so exact trip
8110   // count is simply a minimum out of all these calculated exit counts.
8111   SmallVector<const SCEV *, 2> Ops;
8112   for (auto &ENT : ExitNotTaken) {
8113     const SCEV *BECount = ENT.ExactNotTaken;
8114     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8115     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8116            "We should only have known counts for exiting blocks that dominate "
8117            "latch!");
8118 
8119     Ops.push_back(BECount);
8120 
8121     if (Preds)
8122       for (auto *P : ENT.Predicates)
8123         Preds->push_back(P);
8124 
8125     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8126            "Predicate should be always true!");
8127   }
8128 
8129   return SE->getUMinFromMismatchedTypes(Ops);
8130 }
8131 
8132 /// Get the exact not taken count for this loop exit.
8133 const SCEV *
8134 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8135                                              ScalarEvolution *SE) const {
8136   for (auto &ENT : ExitNotTaken)
8137     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8138       return ENT.ExactNotTaken;
8139 
8140   return SE->getCouldNotCompute();
8141 }
8142 
8143 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8144     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8145   for (auto &ENT : ExitNotTaken)
8146     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8147       return ENT.MaxNotTaken;
8148 
8149   return SE->getCouldNotCompute();
8150 }
8151 
8152 /// getConstantMax - Get the constant max backedge taken count for the loop.
8153 const SCEV *
8154 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8155   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8156     return !ENT.hasAlwaysTruePredicate();
8157   };
8158 
8159   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8160     return SE->getCouldNotCompute();
8161 
8162   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8163           isa<SCEVConstant>(getConstantMax())) &&
8164          "No point in having a non-constant max backedge taken count!");
8165   return getConstantMax();
8166 }
8167 
8168 const SCEV *
8169 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8170                                                    ScalarEvolution *SE) {
8171   if (!SymbolicMax)
8172     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8173   return SymbolicMax;
8174 }
8175 
8176 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8177     ScalarEvolution *SE) const {
8178   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8179     return !ENT.hasAlwaysTruePredicate();
8180   };
8181   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8182 }
8183 
8184 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8185     : ExitLimit(E, E, false, None) {
8186 }
8187 
8188 ScalarEvolution::ExitLimit::ExitLimit(
8189     const SCEV *E, const SCEV *M, bool MaxOrZero,
8190     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8191     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
8192   // If we prove the max count is zero, so is the symbolic bound.  This happens
8193   // in practice due to differences in a) how context sensitive we've chosen
8194   // to be and b) how we reason about bounds impied by UB.
8195   if (MaxNotTaken->isZero())
8196     ExactNotTaken = MaxNotTaken;
8197 
8198   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8199           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
8200          "Exact is not allowed to be less precise than Max");
8201   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
8202           isa<SCEVConstant>(MaxNotTaken)) &&
8203          "No point in having a non-constant max backedge taken count!");
8204   for (auto *PredSet : PredSetList)
8205     for (auto *P : *PredSet)
8206       addPredicate(P);
8207   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8208          "Backedge count should be int");
8209   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
8210          "Max backedge count should be int");
8211 }
8212 
8213 ScalarEvolution::ExitLimit::ExitLimit(
8214     const SCEV *E, const SCEV *M, bool MaxOrZero,
8215     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8216     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
8217 }
8218 
8219 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
8220                                       bool MaxOrZero)
8221     : ExitLimit(E, M, MaxOrZero, None) {
8222 }
8223 
8224 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8225 /// computable exit into a persistent ExitNotTakenInfo array.
8226 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8227     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8228     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8229     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8230   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8231 
8232   ExitNotTaken.reserve(ExitCounts.size());
8233   std::transform(
8234       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
8235       [&](const EdgeExitInfo &EEI) {
8236         BasicBlock *ExitBB = EEI.first;
8237         const ExitLimit &EL = EEI.second;
8238         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
8239                                 EL.Predicates);
8240       });
8241   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8242           isa<SCEVConstant>(ConstantMax)) &&
8243          "No point in having a non-constant max backedge taken count!");
8244 }
8245 
8246 /// Compute the number of times the backedge of the specified loop will execute.
8247 ScalarEvolution::BackedgeTakenInfo
8248 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8249                                            bool AllowPredicates) {
8250   SmallVector<BasicBlock *, 8> ExitingBlocks;
8251   L->getExitingBlocks(ExitingBlocks);
8252 
8253   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8254 
8255   SmallVector<EdgeExitInfo, 4> ExitCounts;
8256   bool CouldComputeBECount = true;
8257   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8258   const SCEV *MustExitMaxBECount = nullptr;
8259   const SCEV *MayExitMaxBECount = nullptr;
8260   bool MustExitMaxOrZero = false;
8261 
8262   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8263   // and compute maxBECount.
8264   // Do a union of all the predicates here.
8265   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8266     BasicBlock *ExitBB = ExitingBlocks[i];
8267 
8268     // We canonicalize untaken exits to br (constant), ignore them so that
8269     // proving an exit untaken doesn't negatively impact our ability to reason
8270     // about the loop as whole.
8271     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8272       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8273         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8274         if (ExitIfTrue == CI->isZero())
8275           continue;
8276       }
8277 
8278     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8279 
8280     assert((AllowPredicates || EL.Predicates.empty()) &&
8281            "Predicated exit limit when predicates are not allowed!");
8282 
8283     // 1. For each exit that can be computed, add an entry to ExitCounts.
8284     // CouldComputeBECount is true only if all exits can be computed.
8285     if (EL.ExactNotTaken == getCouldNotCompute())
8286       // We couldn't compute an exact value for this exit, so
8287       // we won't be able to compute an exact value for the loop.
8288       CouldComputeBECount = false;
8289     else
8290       ExitCounts.emplace_back(ExitBB, EL);
8291 
8292     // 2. Derive the loop's MaxBECount from each exit's max number of
8293     // non-exiting iterations. Partition the loop exits into two kinds:
8294     // LoopMustExits and LoopMayExits.
8295     //
8296     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8297     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8298     // MaxBECount is the minimum EL.MaxNotTaken of computable
8299     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8300     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
8301     // computable EL.MaxNotTaken.
8302     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
8303         DT.dominates(ExitBB, Latch)) {
8304       if (!MustExitMaxBECount) {
8305         MustExitMaxBECount = EL.MaxNotTaken;
8306         MustExitMaxOrZero = EL.MaxOrZero;
8307       } else {
8308         MustExitMaxBECount =
8309             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
8310       }
8311     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8312       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
8313         MayExitMaxBECount = EL.MaxNotTaken;
8314       else {
8315         MayExitMaxBECount =
8316             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
8317       }
8318     }
8319   }
8320   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8321     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8322   // The loop backedge will be taken the maximum or zero times if there's
8323   // a single exit that must be taken the maximum or zero times.
8324   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8325 
8326   // Remember which SCEVs are used in exit limits for invalidation purposes.
8327   // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken
8328   // and MaxBECount, which must be SCEVConstant.
8329   for (const auto &Pair : ExitCounts)
8330     if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8331       BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8332   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8333                            MaxBECount, MaxOrZero);
8334 }
8335 
8336 ScalarEvolution::ExitLimit
8337 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8338                                       bool AllowPredicates) {
8339   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8340   // If our exiting block does not dominate the latch, then its connection with
8341   // loop's exit limit may be far from trivial.
8342   const BasicBlock *Latch = L->getLoopLatch();
8343   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8344     return getCouldNotCompute();
8345 
8346   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8347   Instruction *Term = ExitingBlock->getTerminator();
8348   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8349     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8350     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8351     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8352            "It should have one successor in loop and one exit block!");
8353     // Proceed to the next level to examine the exit condition expression.
8354     return computeExitLimitFromCond(
8355         L, BI->getCondition(), ExitIfTrue,
8356         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8357   }
8358 
8359   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8360     // For switch, make sure that there is a single exit from the loop.
8361     BasicBlock *Exit = nullptr;
8362     for (auto *SBB : successors(ExitingBlock))
8363       if (!L->contains(SBB)) {
8364         if (Exit) // Multiple exit successors.
8365           return getCouldNotCompute();
8366         Exit = SBB;
8367       }
8368     assert(Exit && "Exiting block must have at least one exit");
8369     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8370                                                 /*ControlsExit=*/IsOnlyExit);
8371   }
8372 
8373   return getCouldNotCompute();
8374 }
8375 
8376 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8377     const Loop *L, Value *ExitCond, bool ExitIfTrue,
8378     bool ControlsExit, bool AllowPredicates) {
8379   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8380   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8381                                         ControlsExit, AllowPredicates);
8382 }
8383 
8384 Optional<ScalarEvolution::ExitLimit>
8385 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8386                                       bool ExitIfTrue, bool ControlsExit,
8387                                       bool AllowPredicates) {
8388   (void)this->L;
8389   (void)this->ExitIfTrue;
8390   (void)this->AllowPredicates;
8391 
8392   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8393          this->AllowPredicates == AllowPredicates &&
8394          "Variance in assumed invariant key components!");
8395   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8396   if (Itr == TripCountMap.end())
8397     return None;
8398   return Itr->second;
8399 }
8400 
8401 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8402                                              bool ExitIfTrue,
8403                                              bool ControlsExit,
8404                                              bool AllowPredicates,
8405                                              const ExitLimit &EL) {
8406   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8407          this->AllowPredicates == AllowPredicates &&
8408          "Variance in assumed invariant key components!");
8409 
8410   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8411   assert(InsertResult.second && "Expected successful insertion!");
8412   (void)InsertResult;
8413   (void)ExitIfTrue;
8414 }
8415 
8416 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8417     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8418     bool ControlsExit, bool AllowPredicates) {
8419 
8420   if (auto MaybeEL =
8421           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8422     return *MaybeEL;
8423 
8424   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8425                                               ControlsExit, AllowPredicates);
8426   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8427   return EL;
8428 }
8429 
8430 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8431     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8432     bool ControlsExit, bool AllowPredicates) {
8433   // Handle BinOp conditions (And, Or).
8434   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8435           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8436     return *LimitFromBinOp;
8437 
8438   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8439   // Proceed to the next level to examine the icmp.
8440   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8441     ExitLimit EL =
8442         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8443     if (EL.hasFullInfo() || !AllowPredicates)
8444       return EL;
8445 
8446     // Try again, but use SCEV predicates this time.
8447     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8448                                     /*AllowPredicates=*/true);
8449   }
8450 
8451   // Check for a constant condition. These are normally stripped out by
8452   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8453   // preserve the CFG and is temporarily leaving constant conditions
8454   // in place.
8455   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8456     if (ExitIfTrue == !CI->getZExtValue())
8457       // The backedge is always taken.
8458       return getCouldNotCompute();
8459     else
8460       // The backedge is never taken.
8461       return getZero(CI->getType());
8462   }
8463 
8464   // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8465   // with a constant step, we can form an equivalent icmp predicate and figure
8466   // out how many iterations will be taken before we exit.
8467   const WithOverflowInst *WO;
8468   const APInt *C;
8469   if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8470       match(WO->getRHS(), m_APInt(C))) {
8471     ConstantRange NWR =
8472       ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8473                                            WO->getNoWrapKind());
8474     CmpInst::Predicate Pred;
8475     APInt NewRHSC, Offset;
8476     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8477     if (!ExitIfTrue)
8478       Pred = ICmpInst::getInversePredicate(Pred);
8479     auto *LHS = getSCEV(WO->getLHS());
8480     if (Offset != 0)
8481       LHS = getAddExpr(LHS, getConstant(Offset));
8482     auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8483                                        ControlsExit, AllowPredicates);
8484     if (EL.hasAnyInfo()) return EL;
8485   }
8486 
8487   // If it's not an integer or pointer comparison then compute it the hard way.
8488   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8489 }
8490 
8491 Optional<ScalarEvolution::ExitLimit>
8492 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8493     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8494     bool ControlsExit, bool AllowPredicates) {
8495   // Check if the controlling expression for this loop is an And or Or.
8496   Value *Op0, *Op1;
8497   bool IsAnd = false;
8498   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8499     IsAnd = true;
8500   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8501     IsAnd = false;
8502   else
8503     return None;
8504 
8505   // EitherMayExit is true in these two cases:
8506   //   br (and Op0 Op1), loop, exit
8507   //   br (or  Op0 Op1), exit, loop
8508   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8509   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
8510                                                  ControlsExit && !EitherMayExit,
8511                                                  AllowPredicates);
8512   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
8513                                                  ControlsExit && !EitherMayExit,
8514                                                  AllowPredicates);
8515 
8516   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8517   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8518   if (isa<ConstantInt>(Op1))
8519     return Op1 == NeutralElement ? EL0 : EL1;
8520   if (isa<ConstantInt>(Op0))
8521     return Op0 == NeutralElement ? EL1 : EL0;
8522 
8523   const SCEV *BECount = getCouldNotCompute();
8524   const SCEV *MaxBECount = getCouldNotCompute();
8525   if (EitherMayExit) {
8526     // Both conditions must be same for the loop to continue executing.
8527     // Choose the less conservative count.
8528     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8529         EL1.ExactNotTaken != getCouldNotCompute()) {
8530       BECount = getUMinFromMismatchedTypes(
8531           EL0.ExactNotTaken, EL1.ExactNotTaken,
8532           /*Sequential=*/!isa<BinaryOperator>(ExitCond));
8533     }
8534     if (EL0.MaxNotTaken == getCouldNotCompute())
8535       MaxBECount = EL1.MaxNotTaken;
8536     else if (EL1.MaxNotTaken == getCouldNotCompute())
8537       MaxBECount = EL0.MaxNotTaken;
8538     else
8539       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
8540   } else {
8541     // Both conditions must be same at the same time for the loop to exit.
8542     // For now, be conservative.
8543     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8544       BECount = EL0.ExactNotTaken;
8545   }
8546 
8547   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8548   // to be more aggressive when computing BECount than when computing
8549   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
8550   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
8551   // to not.
8552   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
8553       !isa<SCEVCouldNotCompute>(BECount))
8554     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
8555 
8556   return ExitLimit(BECount, MaxBECount, false,
8557                    { &EL0.Predicates, &EL1.Predicates });
8558 }
8559 
8560 ScalarEvolution::ExitLimit
8561 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8562                                           ICmpInst *ExitCond,
8563                                           bool ExitIfTrue,
8564                                           bool ControlsExit,
8565                                           bool AllowPredicates) {
8566   // If the condition was exit on true, convert the condition to exit on false
8567   ICmpInst::Predicate Pred;
8568   if (!ExitIfTrue)
8569     Pred = ExitCond->getPredicate();
8570   else
8571     Pred = ExitCond->getInversePredicate();
8572   const ICmpInst::Predicate OriginalPred = Pred;
8573 
8574   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8575   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8576 
8577   ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit,
8578                                           AllowPredicates);
8579   if (EL.hasAnyInfo()) return EL;
8580 
8581   auto *ExhaustiveCount =
8582       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8583 
8584   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8585     return ExhaustiveCount;
8586 
8587   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8588                                       ExitCond->getOperand(1), L, OriginalPred);
8589 }
8590 ScalarEvolution::ExitLimit
8591 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8592                                           ICmpInst::Predicate Pred,
8593                                           const SCEV *LHS, const SCEV *RHS,
8594                                           bool ControlsExit,
8595                                           bool AllowPredicates) {
8596 
8597   // Try to evaluate any dependencies out of the loop.
8598   LHS = getSCEVAtScope(LHS, L);
8599   RHS = getSCEVAtScope(RHS, L);
8600 
8601   // At this point, we would like to compute how many iterations of the
8602   // loop the predicate will return true for these inputs.
8603   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8604     // If there is a loop-invariant, force it into the RHS.
8605     std::swap(LHS, RHS);
8606     Pred = ICmpInst::getSwappedPredicate(Pred);
8607   }
8608 
8609   bool ControllingFiniteLoop =
8610       ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L);
8611   // Simplify the operands before analyzing them.
8612   (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0,
8613                              (EnableFiniteLoopControl ? ControllingFiniteLoop
8614                                                      : false));
8615 
8616   // If we have a comparison of a chrec against a constant, try to use value
8617   // ranges to answer this query.
8618   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8619     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8620       if (AddRec->getLoop() == L) {
8621         // Form the constant range.
8622         ConstantRange CompRange =
8623             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8624 
8625         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8626         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8627       }
8628 
8629   // If this loop must exit based on this condition (or execute undefined
8630   // behaviour), and we can prove the test sequence produced must repeat
8631   // the same values on self-wrap of the IV, then we can infer that IV
8632   // doesn't self wrap because if it did, we'd have an infinite (undefined)
8633   // loop.
8634   if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
8635     // TODO: We can peel off any functions which are invertible *in L*.  Loop
8636     // invariant terms are effectively constants for our purposes here.
8637     auto *InnerLHS = LHS;
8638     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
8639       InnerLHS = ZExt->getOperand();
8640     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
8641       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
8642       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
8643           StrideC && StrideC->getAPInt().isPowerOf2()) {
8644         auto Flags = AR->getNoWrapFlags();
8645         Flags = setFlags(Flags, SCEV::FlagNW);
8646         SmallVector<const SCEV*> Operands{AR->operands()};
8647         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
8648         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
8649       }
8650     }
8651   }
8652 
8653   switch (Pred) {
8654   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8655     // Convert to: while (X-Y != 0)
8656     if (LHS->getType()->isPointerTy()) {
8657       LHS = getLosslessPtrToIntExpr(LHS);
8658       if (isa<SCEVCouldNotCompute>(LHS))
8659         return LHS;
8660     }
8661     if (RHS->getType()->isPointerTy()) {
8662       RHS = getLosslessPtrToIntExpr(RHS);
8663       if (isa<SCEVCouldNotCompute>(RHS))
8664         return RHS;
8665     }
8666     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8667                                 AllowPredicates);
8668     if (EL.hasAnyInfo()) return EL;
8669     break;
8670   }
8671   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8672     // Convert to: while (X-Y == 0)
8673     if (LHS->getType()->isPointerTy()) {
8674       LHS = getLosslessPtrToIntExpr(LHS);
8675       if (isa<SCEVCouldNotCompute>(LHS))
8676         return LHS;
8677     }
8678     if (RHS->getType()->isPointerTy()) {
8679       RHS = getLosslessPtrToIntExpr(RHS);
8680       if (isa<SCEVCouldNotCompute>(RHS))
8681         return RHS;
8682     }
8683     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8684     if (EL.hasAnyInfo()) return EL;
8685     break;
8686   }
8687   case ICmpInst::ICMP_SLT:
8688   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8689     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8690     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8691                                     AllowPredicates);
8692     if (EL.hasAnyInfo()) return EL;
8693     break;
8694   }
8695   case ICmpInst::ICMP_SGT:
8696   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8697     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8698     ExitLimit EL =
8699         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8700                             AllowPredicates);
8701     if (EL.hasAnyInfo()) return EL;
8702     break;
8703   }
8704   default:
8705     break;
8706   }
8707 
8708   return getCouldNotCompute();
8709 }
8710 
8711 ScalarEvolution::ExitLimit
8712 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8713                                                       SwitchInst *Switch,
8714                                                       BasicBlock *ExitingBlock,
8715                                                       bool ControlsExit) {
8716   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8717 
8718   // Give up if the exit is the default dest of a switch.
8719   if (Switch->getDefaultDest() == ExitingBlock)
8720     return getCouldNotCompute();
8721 
8722   assert(L->contains(Switch->getDefaultDest()) &&
8723          "Default case must not exit the loop!");
8724   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8725   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8726 
8727   // while (X != Y) --> while (X-Y != 0)
8728   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8729   if (EL.hasAnyInfo())
8730     return EL;
8731 
8732   return getCouldNotCompute();
8733 }
8734 
8735 static ConstantInt *
8736 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8737                                 ScalarEvolution &SE) {
8738   const SCEV *InVal = SE.getConstant(C);
8739   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8740   assert(isa<SCEVConstant>(Val) &&
8741          "Evaluation of SCEV at constant didn't fold correctly?");
8742   return cast<SCEVConstant>(Val)->getValue();
8743 }
8744 
8745 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8746     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8747   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8748   if (!RHS)
8749     return getCouldNotCompute();
8750 
8751   const BasicBlock *Latch = L->getLoopLatch();
8752   if (!Latch)
8753     return getCouldNotCompute();
8754 
8755   const BasicBlock *Predecessor = L->getLoopPredecessor();
8756   if (!Predecessor)
8757     return getCouldNotCompute();
8758 
8759   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8760   // Return LHS in OutLHS and shift_opt in OutOpCode.
8761   auto MatchPositiveShift =
8762       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8763 
8764     using namespace PatternMatch;
8765 
8766     ConstantInt *ShiftAmt;
8767     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8768       OutOpCode = Instruction::LShr;
8769     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8770       OutOpCode = Instruction::AShr;
8771     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8772       OutOpCode = Instruction::Shl;
8773     else
8774       return false;
8775 
8776     return ShiftAmt->getValue().isStrictlyPositive();
8777   };
8778 
8779   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8780   //
8781   // loop:
8782   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8783   //   %iv.shifted = lshr i32 %iv, <positive constant>
8784   //
8785   // Return true on a successful match.  Return the corresponding PHI node (%iv
8786   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8787   auto MatchShiftRecurrence =
8788       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8789     Optional<Instruction::BinaryOps> PostShiftOpCode;
8790 
8791     {
8792       Instruction::BinaryOps OpC;
8793       Value *V;
8794 
8795       // If we encounter a shift instruction, "peel off" the shift operation,
8796       // and remember that we did so.  Later when we inspect %iv's backedge
8797       // value, we will make sure that the backedge value uses the same
8798       // operation.
8799       //
8800       // Note: the peeled shift operation does not have to be the same
8801       // instruction as the one feeding into the PHI's backedge value.  We only
8802       // really care about it being the same *kind* of shift instruction --
8803       // that's all that is required for our later inferences to hold.
8804       if (MatchPositiveShift(LHS, V, OpC)) {
8805         PostShiftOpCode = OpC;
8806         LHS = V;
8807       }
8808     }
8809 
8810     PNOut = dyn_cast<PHINode>(LHS);
8811     if (!PNOut || PNOut->getParent() != L->getHeader())
8812       return false;
8813 
8814     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8815     Value *OpLHS;
8816 
8817     return
8818         // The backedge value for the PHI node must be a shift by a positive
8819         // amount
8820         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8821 
8822         // of the PHI node itself
8823         OpLHS == PNOut &&
8824 
8825         // and the kind of shift should be match the kind of shift we peeled
8826         // off, if any.
8827         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8828   };
8829 
8830   PHINode *PN;
8831   Instruction::BinaryOps OpCode;
8832   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8833     return getCouldNotCompute();
8834 
8835   const DataLayout &DL = getDataLayout();
8836 
8837   // The key rationale for this optimization is that for some kinds of shift
8838   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8839   // within a finite number of iterations.  If the condition guarding the
8840   // backedge (in the sense that the backedge is taken if the condition is true)
8841   // is false for the value the shift recurrence stabilizes to, then we know
8842   // that the backedge is taken only a finite number of times.
8843 
8844   ConstantInt *StableValue = nullptr;
8845   switch (OpCode) {
8846   default:
8847     llvm_unreachable("Impossible case!");
8848 
8849   case Instruction::AShr: {
8850     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8851     // bitwidth(K) iterations.
8852     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8853     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8854                                        Predecessor->getTerminator(), &DT);
8855     auto *Ty = cast<IntegerType>(RHS->getType());
8856     if (Known.isNonNegative())
8857       StableValue = ConstantInt::get(Ty, 0);
8858     else if (Known.isNegative())
8859       StableValue = ConstantInt::get(Ty, -1, true);
8860     else
8861       return getCouldNotCompute();
8862 
8863     break;
8864   }
8865   case Instruction::LShr:
8866   case Instruction::Shl:
8867     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8868     // stabilize to 0 in at most bitwidth(K) iterations.
8869     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8870     break;
8871   }
8872 
8873   auto *Result =
8874       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8875   assert(Result->getType()->isIntegerTy(1) &&
8876          "Otherwise cannot be an operand to a branch instruction");
8877 
8878   if (Result->isZeroValue()) {
8879     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8880     const SCEV *UpperBound =
8881         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8882     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8883   }
8884 
8885   return getCouldNotCompute();
8886 }
8887 
8888 /// Return true if we can constant fold an instruction of the specified type,
8889 /// assuming that all operands were constants.
8890 static bool CanConstantFold(const Instruction *I) {
8891   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8892       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8893       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8894     return true;
8895 
8896   if (const CallInst *CI = dyn_cast<CallInst>(I))
8897     if (const Function *F = CI->getCalledFunction())
8898       return canConstantFoldCallTo(CI, F);
8899   return false;
8900 }
8901 
8902 /// Determine whether this instruction can constant evolve within this loop
8903 /// assuming its operands can all constant evolve.
8904 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8905   // An instruction outside of the loop can't be derived from a loop PHI.
8906   if (!L->contains(I)) return false;
8907 
8908   if (isa<PHINode>(I)) {
8909     // We don't currently keep track of the control flow needed to evaluate
8910     // PHIs, so we cannot handle PHIs inside of loops.
8911     return L->getHeader() == I->getParent();
8912   }
8913 
8914   // If we won't be able to constant fold this expression even if the operands
8915   // are constants, bail early.
8916   return CanConstantFold(I);
8917 }
8918 
8919 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8920 /// recursing through each instruction operand until reaching a loop header phi.
8921 static PHINode *
8922 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8923                                DenseMap<Instruction *, PHINode *> &PHIMap,
8924                                unsigned Depth) {
8925   if (Depth > MaxConstantEvolvingDepth)
8926     return nullptr;
8927 
8928   // Otherwise, we can evaluate this instruction if all of its operands are
8929   // constant or derived from a PHI node themselves.
8930   PHINode *PHI = nullptr;
8931   for (Value *Op : UseInst->operands()) {
8932     if (isa<Constant>(Op)) continue;
8933 
8934     Instruction *OpInst = dyn_cast<Instruction>(Op);
8935     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8936 
8937     PHINode *P = dyn_cast<PHINode>(OpInst);
8938     if (!P)
8939       // If this operand is already visited, reuse the prior result.
8940       // We may have P != PHI if this is the deepest point at which the
8941       // inconsistent paths meet.
8942       P = PHIMap.lookup(OpInst);
8943     if (!P) {
8944       // Recurse and memoize the results, whether a phi is found or not.
8945       // This recursive call invalidates pointers into PHIMap.
8946       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8947       PHIMap[OpInst] = P;
8948     }
8949     if (!P)
8950       return nullptr;  // Not evolving from PHI
8951     if (PHI && PHI != P)
8952       return nullptr;  // Evolving from multiple different PHIs.
8953     PHI = P;
8954   }
8955   // This is a expression evolving from a constant PHI!
8956   return PHI;
8957 }
8958 
8959 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8960 /// in the loop that V is derived from.  We allow arbitrary operations along the
8961 /// way, but the operands of an operation must either be constants or a value
8962 /// derived from a constant PHI.  If this expression does not fit with these
8963 /// constraints, return null.
8964 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8965   Instruction *I = dyn_cast<Instruction>(V);
8966   if (!I || !canConstantEvolve(I, L)) return nullptr;
8967 
8968   if (PHINode *PN = dyn_cast<PHINode>(I))
8969     return PN;
8970 
8971   // Record non-constant instructions contained by the loop.
8972   DenseMap<Instruction *, PHINode *> PHIMap;
8973   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8974 }
8975 
8976 /// EvaluateExpression - Given an expression that passes the
8977 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8978 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8979 /// reason, return null.
8980 static Constant *EvaluateExpression(Value *V, const Loop *L,
8981                                     DenseMap<Instruction *, Constant *> &Vals,
8982                                     const DataLayout &DL,
8983                                     const TargetLibraryInfo *TLI) {
8984   // Convenient constant check, but redundant for recursive calls.
8985   if (Constant *C = dyn_cast<Constant>(V)) return C;
8986   Instruction *I = dyn_cast<Instruction>(V);
8987   if (!I) return nullptr;
8988 
8989   if (Constant *C = Vals.lookup(I)) return C;
8990 
8991   // An instruction inside the loop depends on a value outside the loop that we
8992   // weren't given a mapping for, or a value such as a call inside the loop.
8993   if (!canConstantEvolve(I, L)) return nullptr;
8994 
8995   // An unmapped PHI can be due to a branch or another loop inside this loop,
8996   // or due to this not being the initial iteration through a loop where we
8997   // couldn't compute the evolution of this particular PHI last time.
8998   if (isa<PHINode>(I)) return nullptr;
8999 
9000   std::vector<Constant*> Operands(I->getNumOperands());
9001 
9002   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9003     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9004     if (!Operand) {
9005       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9006       if (!Operands[i]) return nullptr;
9007       continue;
9008     }
9009     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9010     Vals[Operand] = C;
9011     if (!C) return nullptr;
9012     Operands[i] = C;
9013   }
9014 
9015   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9016     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9017                                            Operands[1], DL, TLI);
9018   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9019     if (!LI->isVolatile())
9020       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
9021   }
9022   return ConstantFoldInstOperands(I, Operands, DL, TLI);
9023 }
9024 
9025 
9026 // If every incoming value to PN except the one for BB is a specific Constant,
9027 // return that, else return nullptr.
9028 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9029   Constant *IncomingVal = nullptr;
9030 
9031   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9032     if (PN->getIncomingBlock(i) == BB)
9033       continue;
9034 
9035     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9036     if (!CurrentVal)
9037       return nullptr;
9038 
9039     if (IncomingVal != CurrentVal) {
9040       if (IncomingVal)
9041         return nullptr;
9042       IncomingVal = CurrentVal;
9043     }
9044   }
9045 
9046   return IncomingVal;
9047 }
9048 
9049 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9050 /// in the header of its containing loop, we know the loop executes a
9051 /// constant number of times, and the PHI node is just a recurrence
9052 /// involving constants, fold it.
9053 Constant *
9054 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9055                                                    const APInt &BEs,
9056                                                    const Loop *L) {
9057   auto I = ConstantEvolutionLoopExitValue.find(PN);
9058   if (I != ConstantEvolutionLoopExitValue.end())
9059     return I->second;
9060 
9061   if (BEs.ugt(MaxBruteForceIterations))
9062     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
9063 
9064   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9065 
9066   DenseMap<Instruction *, Constant *> CurrentIterVals;
9067   BasicBlock *Header = L->getHeader();
9068   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9069 
9070   BasicBlock *Latch = L->getLoopLatch();
9071   if (!Latch)
9072     return nullptr;
9073 
9074   for (PHINode &PHI : Header->phis()) {
9075     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9076       CurrentIterVals[&PHI] = StartCST;
9077   }
9078   if (!CurrentIterVals.count(PN))
9079     return RetVal = nullptr;
9080 
9081   Value *BEValue = PN->getIncomingValueForBlock(Latch);
9082 
9083   // Execute the loop symbolically to determine the exit value.
9084   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9085          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9086 
9087   unsigned NumIterations = BEs.getZExtValue(); // must be in range
9088   unsigned IterationNum = 0;
9089   const DataLayout &DL = getDataLayout();
9090   for (; ; ++IterationNum) {
9091     if (IterationNum == NumIterations)
9092       return RetVal = CurrentIterVals[PN];  // Got exit value!
9093 
9094     // Compute the value of the PHIs for the next iteration.
9095     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9096     DenseMap<Instruction *, Constant *> NextIterVals;
9097     Constant *NextPHI =
9098         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9099     if (!NextPHI)
9100       return nullptr;        // Couldn't evaluate!
9101     NextIterVals[PN] = NextPHI;
9102 
9103     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9104 
9105     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
9106     // cease to be able to evaluate one of them or if they stop evolving,
9107     // because that doesn't necessarily prevent us from computing PN.
9108     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9109     for (const auto &I : CurrentIterVals) {
9110       PHINode *PHI = dyn_cast<PHINode>(I.first);
9111       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9112       PHIsToCompute.emplace_back(PHI, I.second);
9113     }
9114     // We use two distinct loops because EvaluateExpression may invalidate any
9115     // iterators into CurrentIterVals.
9116     for (const auto &I : PHIsToCompute) {
9117       PHINode *PHI = I.first;
9118       Constant *&NextPHI = NextIterVals[PHI];
9119       if (!NextPHI) {   // Not already computed.
9120         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9121         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9122       }
9123       if (NextPHI != I.second)
9124         StoppedEvolving = false;
9125     }
9126 
9127     // If all entries in CurrentIterVals == NextIterVals then we can stop
9128     // iterating, the loop can't continue to change.
9129     if (StoppedEvolving)
9130       return RetVal = CurrentIterVals[PN];
9131 
9132     CurrentIterVals.swap(NextIterVals);
9133   }
9134 }
9135 
9136 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9137                                                           Value *Cond,
9138                                                           bool ExitWhen) {
9139   PHINode *PN = getConstantEvolvingPHI(Cond, L);
9140   if (!PN) return getCouldNotCompute();
9141 
9142   // If the loop is canonicalized, the PHI will have exactly two entries.
9143   // That's the only form we support here.
9144   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9145 
9146   DenseMap<Instruction *, Constant *> CurrentIterVals;
9147   BasicBlock *Header = L->getHeader();
9148   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9149 
9150   BasicBlock *Latch = L->getLoopLatch();
9151   assert(Latch && "Should follow from NumIncomingValues == 2!");
9152 
9153   for (PHINode &PHI : Header->phis()) {
9154     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9155       CurrentIterVals[&PHI] = StartCST;
9156   }
9157   if (!CurrentIterVals.count(PN))
9158     return getCouldNotCompute();
9159 
9160   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
9161   // the loop symbolically to determine when the condition gets a value of
9162   // "ExitWhen".
9163   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
9164   const DataLayout &DL = getDataLayout();
9165   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9166     auto *CondVal = dyn_cast_or_null<ConstantInt>(
9167         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9168 
9169     // Couldn't symbolically evaluate.
9170     if (!CondVal) return getCouldNotCompute();
9171 
9172     if (CondVal->getValue() == uint64_t(ExitWhen)) {
9173       ++NumBruteForceTripCountsComputed;
9174       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9175     }
9176 
9177     // Update all the PHI nodes for the next iteration.
9178     DenseMap<Instruction *, Constant *> NextIterVals;
9179 
9180     // Create a list of which PHIs we need to compute. We want to do this before
9181     // calling EvaluateExpression on them because that may invalidate iterators
9182     // into CurrentIterVals.
9183     SmallVector<PHINode *, 8> PHIsToCompute;
9184     for (const auto &I : CurrentIterVals) {
9185       PHINode *PHI = dyn_cast<PHINode>(I.first);
9186       if (!PHI || PHI->getParent() != Header) continue;
9187       PHIsToCompute.push_back(PHI);
9188     }
9189     for (PHINode *PHI : PHIsToCompute) {
9190       Constant *&NextPHI = NextIterVals[PHI];
9191       if (NextPHI) continue;    // Already computed!
9192 
9193       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9194       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9195     }
9196     CurrentIterVals.swap(NextIterVals);
9197   }
9198 
9199   // Too many iterations were needed to evaluate.
9200   return getCouldNotCompute();
9201 }
9202 
9203 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9204   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9205       ValuesAtScopes[V];
9206   // Check to see if we've folded this expression at this loop before.
9207   for (auto &LS : Values)
9208     if (LS.first == L)
9209       return LS.second ? LS.second : V;
9210 
9211   Values.emplace_back(L, nullptr);
9212 
9213   // Otherwise compute it.
9214   const SCEV *C = computeSCEVAtScope(V, L);
9215   for (auto &LS : reverse(ValuesAtScopes[V]))
9216     if (LS.first == L) {
9217       LS.second = C;
9218       if (!isa<SCEVConstant>(C))
9219         ValuesAtScopesUsers[C].push_back({L, V});
9220       break;
9221     }
9222   return C;
9223 }
9224 
9225 /// This builds up a Constant using the ConstantExpr interface.  That way, we
9226 /// will return Constants for objects which aren't represented by a
9227 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9228 /// Returns NULL if the SCEV isn't representable as a Constant.
9229 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9230   switch (V->getSCEVType()) {
9231   case scCouldNotCompute:
9232   case scAddRecExpr:
9233     return nullptr;
9234   case scConstant:
9235     return cast<SCEVConstant>(V)->getValue();
9236   case scUnknown:
9237     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9238   case scSignExtend: {
9239     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
9240     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
9241       return ConstantExpr::getSExt(CastOp, SS->getType());
9242     return nullptr;
9243   }
9244   case scZeroExtend: {
9245     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
9246     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
9247       return ConstantExpr::getZExt(CastOp, SZ->getType());
9248     return nullptr;
9249   }
9250   case scPtrToInt: {
9251     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9252     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9253       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9254 
9255     return nullptr;
9256   }
9257   case scTruncate: {
9258     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9259     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9260       return ConstantExpr::getTrunc(CastOp, ST->getType());
9261     return nullptr;
9262   }
9263   case scAddExpr: {
9264     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9265     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
9266       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
9267         unsigned AS = PTy->getAddressSpace();
9268         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9269         C = ConstantExpr::getBitCast(C, DestPtrTy);
9270       }
9271       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
9272         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
9273         if (!C2)
9274           return nullptr;
9275 
9276         // First pointer!
9277         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
9278           unsigned AS = C2->getType()->getPointerAddressSpace();
9279           std::swap(C, C2);
9280           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9281           // The offsets have been converted to bytes.  We can add bytes to an
9282           // i8* by GEP with the byte count in the first index.
9283           C = ConstantExpr::getBitCast(C, DestPtrTy);
9284         }
9285 
9286         // Don't bother trying to sum two pointers. We probably can't
9287         // statically compute a load that results from it anyway.
9288         if (C2->getType()->isPointerTy())
9289           return nullptr;
9290 
9291         if (C->getType()->isPointerTy()) {
9292           C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9293                                              C, C2);
9294         } else {
9295           C = ConstantExpr::getAdd(C, C2);
9296         }
9297       }
9298       return C;
9299     }
9300     return nullptr;
9301   }
9302   case scMulExpr: {
9303     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9304     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
9305       // Don't bother with pointers at all.
9306       if (C->getType()->isPointerTy())
9307         return nullptr;
9308       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
9309         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
9310         if (!C2 || C2->getType()->isPointerTy())
9311           return nullptr;
9312         C = ConstantExpr::getMul(C, C2);
9313       }
9314       return C;
9315     }
9316     return nullptr;
9317   }
9318   case scUDivExpr: {
9319     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
9320     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
9321       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
9322         if (LHS->getType() == RHS->getType())
9323           return ConstantExpr::getUDiv(LHS, RHS);
9324     return nullptr;
9325   }
9326   case scSMaxExpr:
9327   case scUMaxExpr:
9328   case scSMinExpr:
9329   case scUMinExpr:
9330   case scSequentialUMinExpr:
9331     return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
9332   }
9333   llvm_unreachable("Unknown SCEV kind!");
9334 }
9335 
9336 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9337   if (isa<SCEVConstant>(V)) return V;
9338 
9339   // If this instruction is evolved from a constant-evolving PHI, compute the
9340   // exit value from the loop without using SCEVs.
9341   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
9342     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
9343       if (PHINode *PN = dyn_cast<PHINode>(I)) {
9344         const Loop *CurrLoop = this->LI[I->getParent()];
9345         // Looking for loop exit value.
9346         if (CurrLoop && CurrLoop->getParentLoop() == L &&
9347             PN->getParent() == CurrLoop->getHeader()) {
9348           // Okay, there is no closed form solution for the PHI node.  Check
9349           // to see if the loop that contains it has a known backedge-taken
9350           // count.  If so, we may be able to force computation of the exit
9351           // value.
9352           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9353           // This trivial case can show up in some degenerate cases where
9354           // the incoming IR has not yet been fully simplified.
9355           if (BackedgeTakenCount->isZero()) {
9356             Value *InitValue = nullptr;
9357             bool MultipleInitValues = false;
9358             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9359               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9360                 if (!InitValue)
9361                   InitValue = PN->getIncomingValue(i);
9362                 else if (InitValue != PN->getIncomingValue(i)) {
9363                   MultipleInitValues = true;
9364                   break;
9365                 }
9366               }
9367             }
9368             if (!MultipleInitValues && InitValue)
9369               return getSCEV(InitValue);
9370           }
9371           // Do we have a loop invariant value flowing around the backedge
9372           // for a loop which must execute the backedge?
9373           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9374               isKnownPositive(BackedgeTakenCount) &&
9375               PN->getNumIncomingValues() == 2) {
9376 
9377             unsigned InLoopPred =
9378                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9379             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9380             if (CurrLoop->isLoopInvariant(BackedgeVal))
9381               return getSCEV(BackedgeVal);
9382           }
9383           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9384             // Okay, we know how many times the containing loop executes.  If
9385             // this is a constant evolving PHI node, get the final value at
9386             // the specified iteration number.
9387             Constant *RV = getConstantEvolutionLoopExitValue(
9388                 PN, BTCC->getAPInt(), CurrLoop);
9389             if (RV) return getSCEV(RV);
9390           }
9391         }
9392 
9393         // If there is a single-input Phi, evaluate it at our scope. If we can
9394         // prove that this replacement does not break LCSSA form, use new value.
9395         if (PN->getNumOperands() == 1) {
9396           const SCEV *Input = getSCEV(PN->getOperand(0));
9397           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
9398           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
9399           // for the simplest case just support constants.
9400           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
9401         }
9402       }
9403 
9404       // Okay, this is an expression that we cannot symbolically evaluate
9405       // into a SCEV.  Check to see if it's possible to symbolically evaluate
9406       // the arguments into constants, and if so, try to constant propagate the
9407       // result.  This is particularly useful for computing loop exit values.
9408       if (CanConstantFold(I)) {
9409         SmallVector<Constant *, 4> Operands;
9410         bool MadeImprovement = false;
9411         for (Value *Op : I->operands()) {
9412           if (Constant *C = dyn_cast<Constant>(Op)) {
9413             Operands.push_back(C);
9414             continue;
9415           }
9416 
9417           // If any of the operands is non-constant and if they are
9418           // non-integer and non-pointer, don't even try to analyze them
9419           // with scev techniques.
9420           if (!isSCEVable(Op->getType()))
9421             return V;
9422 
9423           const SCEV *OrigV = getSCEV(Op);
9424           const SCEV *OpV = getSCEVAtScope(OrigV, L);
9425           MadeImprovement |= OrigV != OpV;
9426 
9427           Constant *C = BuildConstantFromSCEV(OpV);
9428           if (!C) return V;
9429           if (C->getType() != Op->getType())
9430             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
9431                                                               Op->getType(),
9432                                                               false),
9433                                       C, Op->getType());
9434           Operands.push_back(C);
9435         }
9436 
9437         // Check to see if getSCEVAtScope actually made an improvement.
9438         if (MadeImprovement) {
9439           Constant *C = nullptr;
9440           const DataLayout &DL = getDataLayout();
9441           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
9442             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9443                                                 Operands[1], DL, &TLI);
9444           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
9445             if (!Load->isVolatile())
9446               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
9447                                                DL);
9448           } else
9449             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9450           if (!C) return V;
9451           return getSCEV(C);
9452         }
9453       }
9454     }
9455 
9456     // This is some other type of SCEVUnknown, just return it.
9457     return V;
9458   }
9459 
9460   if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) {
9461     const auto *Comm = cast<SCEVNAryExpr>(V);
9462     // Avoid performing the look-up in the common case where the specified
9463     // expression has no loop-variant portions.
9464     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
9465       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9466       if (OpAtScope != Comm->getOperand(i)) {
9467         // Okay, at least one of these operands is loop variant but might be
9468         // foldable.  Build a new instance of the folded commutative expression.
9469         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
9470                                             Comm->op_begin()+i);
9471         NewOps.push_back(OpAtScope);
9472 
9473         for (++i; i != e; ++i) {
9474           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9475           NewOps.push_back(OpAtScope);
9476         }
9477         if (isa<SCEVAddExpr>(Comm))
9478           return getAddExpr(NewOps, Comm->getNoWrapFlags());
9479         if (isa<SCEVMulExpr>(Comm))
9480           return getMulExpr(NewOps, Comm->getNoWrapFlags());
9481         if (isa<SCEVMinMaxExpr>(Comm))
9482           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
9483         if (isa<SCEVSequentialMinMaxExpr>(Comm))
9484           return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps);
9485         llvm_unreachable("Unknown commutative / sequential min/max SCEV type!");
9486       }
9487     }
9488     // If we got here, all operands are loop invariant.
9489     return Comm;
9490   }
9491 
9492   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
9493     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
9494     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
9495     if (LHS == Div->getLHS() && RHS == Div->getRHS())
9496       return Div;   // must be loop invariant
9497     return getUDivExpr(LHS, RHS);
9498   }
9499 
9500   // If this is a loop recurrence for a loop that does not contain L, then we
9501   // are dealing with the final value computed by the loop.
9502   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
9503     // First, attempt to evaluate each operand.
9504     // Avoid performing the look-up in the common case where the specified
9505     // expression has no loop-variant portions.
9506     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9507       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9508       if (OpAtScope == AddRec->getOperand(i))
9509         continue;
9510 
9511       // Okay, at least one of these operands is loop variant but might be
9512       // foldable.  Build a new instance of the folded commutative expression.
9513       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9514                                           AddRec->op_begin()+i);
9515       NewOps.push_back(OpAtScope);
9516       for (++i; i != e; ++i)
9517         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9518 
9519       const SCEV *FoldedRec =
9520         getAddRecExpr(NewOps, AddRec->getLoop(),
9521                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9522       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9523       // The addrec may be folded to a nonrecurrence, for example, if the
9524       // induction variable is multiplied by zero after constant folding. Go
9525       // ahead and return the folded value.
9526       if (!AddRec)
9527         return FoldedRec;
9528       break;
9529     }
9530 
9531     // If the scope is outside the addrec's loop, evaluate it by using the
9532     // loop exit value of the addrec.
9533     if (!AddRec->getLoop()->contains(L)) {
9534       // To evaluate this recurrence, we need to know how many times the AddRec
9535       // loop iterates.  Compute this now.
9536       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9537       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9538 
9539       // Then, evaluate the AddRec.
9540       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9541     }
9542 
9543     return AddRec;
9544   }
9545 
9546   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
9547     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9548     if (Op == Cast->getOperand())
9549       return Cast;  // must be loop invariant
9550     return getCastExpr(Cast->getSCEVType(), Op, Cast->getType());
9551   }
9552 
9553   llvm_unreachable("Unknown SCEV type!");
9554 }
9555 
9556 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9557   return getSCEVAtScope(getSCEV(V), L);
9558 }
9559 
9560 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9561   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9562     return stripInjectiveFunctions(ZExt->getOperand());
9563   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9564     return stripInjectiveFunctions(SExt->getOperand());
9565   return S;
9566 }
9567 
9568 /// Finds the minimum unsigned root of the following equation:
9569 ///
9570 ///     A * X = B (mod N)
9571 ///
9572 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9573 /// A and B isn't important.
9574 ///
9575 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9576 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9577                                                ScalarEvolution &SE) {
9578   uint32_t BW = A.getBitWidth();
9579   assert(BW == SE.getTypeSizeInBits(B->getType()));
9580   assert(A != 0 && "A must be non-zero.");
9581 
9582   // 1. D = gcd(A, N)
9583   //
9584   // The gcd of A and N may have only one prime factor: 2. The number of
9585   // trailing zeros in A is its multiplicity
9586   uint32_t Mult2 = A.countTrailingZeros();
9587   // D = 2^Mult2
9588 
9589   // 2. Check if B is divisible by D.
9590   //
9591   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9592   // is not less than multiplicity of this prime factor for D.
9593   if (SE.GetMinTrailingZeros(B) < Mult2)
9594     return SE.getCouldNotCompute();
9595 
9596   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9597   // modulo (N / D).
9598   //
9599   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9600   // (N / D) in general. The inverse itself always fits into BW bits, though,
9601   // so we immediately truncate it.
9602   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9603   APInt Mod(BW + 1, 0);
9604   Mod.setBit(BW - Mult2);  // Mod = N / D
9605   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9606 
9607   // 4. Compute the minimum unsigned root of the equation:
9608   // I * (B / D) mod (N / D)
9609   // To simplify the computation, we factor out the divide by D:
9610   // (I * B mod N) / D
9611   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9612   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9613 }
9614 
9615 /// For a given quadratic addrec, generate coefficients of the corresponding
9616 /// quadratic equation, multiplied by a common value to ensure that they are
9617 /// integers.
9618 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9619 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9620 /// were multiplied by, and BitWidth is the bit width of the original addrec
9621 /// coefficients.
9622 /// This function returns None if the addrec coefficients are not compile-
9623 /// time constants.
9624 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9625 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9626   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9627   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9628   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9629   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9630   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9631                     << *AddRec << '\n');
9632 
9633   // We currently can only solve this if the coefficients are constants.
9634   if (!LC || !MC || !NC) {
9635     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9636     return None;
9637   }
9638 
9639   APInt L = LC->getAPInt();
9640   APInt M = MC->getAPInt();
9641   APInt N = NC->getAPInt();
9642   assert(!N.isZero() && "This is not a quadratic addrec");
9643 
9644   unsigned BitWidth = LC->getAPInt().getBitWidth();
9645   unsigned NewWidth = BitWidth + 1;
9646   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9647                     << BitWidth << '\n');
9648   // The sign-extension (as opposed to a zero-extension) here matches the
9649   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9650   N = N.sext(NewWidth);
9651   M = M.sext(NewWidth);
9652   L = L.sext(NewWidth);
9653 
9654   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9655   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9656   //   L+M, L+2M+N, L+3M+3N, ...
9657   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9658   //
9659   // The equation Acc = 0 is then
9660   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9661   // In a quadratic form it becomes:
9662   //   N n^2 + (2M-N) n + 2L = 0.
9663 
9664   APInt A = N;
9665   APInt B = 2 * M - A;
9666   APInt C = 2 * L;
9667   APInt T = APInt(NewWidth, 2);
9668   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9669                     << "x + " << C << ", coeff bw: " << NewWidth
9670                     << ", multiplied by " << T << '\n');
9671   return std::make_tuple(A, B, C, T, BitWidth);
9672 }
9673 
9674 /// Helper function to compare optional APInts:
9675 /// (a) if X and Y both exist, return min(X, Y),
9676 /// (b) if neither X nor Y exist, return None,
9677 /// (c) if exactly one of X and Y exists, return that value.
9678 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9679   if (X.hasValue() && Y.hasValue()) {
9680     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9681     APInt XW = X->sextOrSelf(W);
9682     APInt YW = Y->sextOrSelf(W);
9683     return XW.slt(YW) ? *X : *Y;
9684   }
9685   if (!X.hasValue() && !Y.hasValue())
9686     return None;
9687   return X.hasValue() ? *X : *Y;
9688 }
9689 
9690 /// Helper function to truncate an optional APInt to a given BitWidth.
9691 /// When solving addrec-related equations, it is preferable to return a value
9692 /// that has the same bit width as the original addrec's coefficients. If the
9693 /// solution fits in the original bit width, truncate it (except for i1).
9694 /// Returning a value of a different bit width may inhibit some optimizations.
9695 ///
9696 /// In general, a solution to a quadratic equation generated from an addrec
9697 /// may require BW+1 bits, where BW is the bit width of the addrec's
9698 /// coefficients. The reason is that the coefficients of the quadratic
9699 /// equation are BW+1 bits wide (to avoid truncation when converting from
9700 /// the addrec to the equation).
9701 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9702   if (!X.hasValue())
9703     return None;
9704   unsigned W = X->getBitWidth();
9705   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9706     return X->trunc(BitWidth);
9707   return X;
9708 }
9709 
9710 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9711 /// iterations. The values L, M, N are assumed to be signed, and they
9712 /// should all have the same bit widths.
9713 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9714 /// where BW is the bit width of the addrec's coefficients.
9715 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9716 /// returned as such, otherwise the bit width of the returned value may
9717 /// be greater than BW.
9718 ///
9719 /// This function returns None if
9720 /// (a) the addrec coefficients are not constant, or
9721 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9722 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9723 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9724 static Optional<APInt>
9725 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9726   APInt A, B, C, M;
9727   unsigned BitWidth;
9728   auto T = GetQuadraticEquation(AddRec);
9729   if (!T.hasValue())
9730     return None;
9731 
9732   std::tie(A, B, C, M, BitWidth) = *T;
9733   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9734   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9735   if (!X.hasValue())
9736     return None;
9737 
9738   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9739   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9740   if (!V->isZero())
9741     return None;
9742 
9743   return TruncIfPossible(X, BitWidth);
9744 }
9745 
9746 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9747 /// iterations. The values M, N are assumed to be signed, and they
9748 /// should all have the same bit widths.
9749 /// Find the least n such that c(n) does not belong to the given range,
9750 /// while c(n-1) does.
9751 ///
9752 /// This function returns None if
9753 /// (a) the addrec coefficients are not constant, or
9754 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9755 ///     bounds of the range.
9756 static Optional<APInt>
9757 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9758                           const ConstantRange &Range, ScalarEvolution &SE) {
9759   assert(AddRec->getOperand(0)->isZero() &&
9760          "Starting value of addrec should be 0");
9761   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9762                     << Range << ", addrec " << *AddRec << '\n');
9763   // This case is handled in getNumIterationsInRange. Here we can assume that
9764   // we start in the range.
9765   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9766          "Addrec's initial value should be in range");
9767 
9768   APInt A, B, C, M;
9769   unsigned BitWidth;
9770   auto T = GetQuadraticEquation(AddRec);
9771   if (!T.hasValue())
9772     return None;
9773 
9774   // Be careful about the return value: there can be two reasons for not
9775   // returning an actual number. First, if no solutions to the equations
9776   // were found, and second, if the solutions don't leave the given range.
9777   // The first case means that the actual solution is "unknown", the second
9778   // means that it's known, but not valid. If the solution is unknown, we
9779   // cannot make any conclusions.
9780   // Return a pair: the optional solution and a flag indicating if the
9781   // solution was found.
9782   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9783     // Solve for signed overflow and unsigned overflow, pick the lower
9784     // solution.
9785     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9786                       << Bound << " (before multiplying by " << M << ")\n");
9787     Bound *= M; // The quadratic equation multiplier.
9788 
9789     Optional<APInt> SO = None;
9790     if (BitWidth > 1) {
9791       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9792                            "signed overflow\n");
9793       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9794     }
9795     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9796                          "unsigned overflow\n");
9797     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9798                                                               BitWidth+1);
9799 
9800     auto LeavesRange = [&] (const APInt &X) {
9801       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9802       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9803       if (Range.contains(V0->getValue()))
9804         return false;
9805       // X should be at least 1, so X-1 is non-negative.
9806       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9807       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9808       if (Range.contains(V1->getValue()))
9809         return true;
9810       return false;
9811     };
9812 
9813     // If SolveQuadraticEquationWrap returns None, it means that there can
9814     // be a solution, but the function failed to find it. We cannot treat it
9815     // as "no solution".
9816     if (!SO.hasValue() || !UO.hasValue())
9817       return { None, false };
9818 
9819     // Check the smaller value first to see if it leaves the range.
9820     // At this point, both SO and UO must have values.
9821     Optional<APInt> Min = MinOptional(SO, UO);
9822     if (LeavesRange(*Min))
9823       return { Min, true };
9824     Optional<APInt> Max = Min == SO ? UO : SO;
9825     if (LeavesRange(*Max))
9826       return { Max, true };
9827 
9828     // Solutions were found, but were eliminated, hence the "true".
9829     return { None, true };
9830   };
9831 
9832   std::tie(A, B, C, M, BitWidth) = *T;
9833   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9834   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9835   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9836   auto SL = SolveForBoundary(Lower);
9837   auto SU = SolveForBoundary(Upper);
9838   // If any of the solutions was unknown, no meaninigful conclusions can
9839   // be made.
9840   if (!SL.second || !SU.second)
9841     return None;
9842 
9843   // Claim: The correct solution is not some value between Min and Max.
9844   //
9845   // Justification: Assuming that Min and Max are different values, one of
9846   // them is when the first signed overflow happens, the other is when the
9847   // first unsigned overflow happens. Crossing the range boundary is only
9848   // possible via an overflow (treating 0 as a special case of it, modeling
9849   // an overflow as crossing k*2^W for some k).
9850   //
9851   // The interesting case here is when Min was eliminated as an invalid
9852   // solution, but Max was not. The argument is that if there was another
9853   // overflow between Min and Max, it would also have been eliminated if
9854   // it was considered.
9855   //
9856   // For a given boundary, it is possible to have two overflows of the same
9857   // type (signed/unsigned) without having the other type in between: this
9858   // can happen when the vertex of the parabola is between the iterations
9859   // corresponding to the overflows. This is only possible when the two
9860   // overflows cross k*2^W for the same k. In such case, if the second one
9861   // left the range (and was the first one to do so), the first overflow
9862   // would have to enter the range, which would mean that either we had left
9863   // the range before or that we started outside of it. Both of these cases
9864   // are contradictions.
9865   //
9866   // Claim: In the case where SolveForBoundary returns None, the correct
9867   // solution is not some value between the Max for this boundary and the
9868   // Min of the other boundary.
9869   //
9870   // Justification: Assume that we had such Max_A and Min_B corresponding
9871   // to range boundaries A and B and such that Max_A < Min_B. If there was
9872   // a solution between Max_A and Min_B, it would have to be caused by an
9873   // overflow corresponding to either A or B. It cannot correspond to B,
9874   // since Min_B is the first occurrence of such an overflow. If it
9875   // corresponded to A, it would have to be either a signed or an unsigned
9876   // overflow that is larger than both eliminated overflows for A. But
9877   // between the eliminated overflows and this overflow, the values would
9878   // cover the entire value space, thus crossing the other boundary, which
9879   // is a contradiction.
9880 
9881   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9882 }
9883 
9884 ScalarEvolution::ExitLimit
9885 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9886                               bool AllowPredicates) {
9887 
9888   // This is only used for loops with a "x != y" exit test. The exit condition
9889   // is now expressed as a single expression, V = x-y. So the exit test is
9890   // effectively V != 0.  We know and take advantage of the fact that this
9891   // expression only being used in a comparison by zero context.
9892 
9893   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9894   // If the value is a constant
9895   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9896     // If the value is already zero, the branch will execute zero times.
9897     if (C->getValue()->isZero()) return C;
9898     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9899   }
9900 
9901   const SCEVAddRecExpr *AddRec =
9902       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9903 
9904   if (!AddRec && AllowPredicates)
9905     // Try to make this an AddRec using runtime tests, in the first X
9906     // iterations of this loop, where X is the SCEV expression found by the
9907     // algorithm below.
9908     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9909 
9910   if (!AddRec || AddRec->getLoop() != L)
9911     return getCouldNotCompute();
9912 
9913   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9914   // the quadratic equation to solve it.
9915   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9916     // We can only use this value if the chrec ends up with an exact zero
9917     // value at this index.  When solving for "X*X != 5", for example, we
9918     // should not accept a root of 2.
9919     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9920       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9921       return ExitLimit(R, R, false, Predicates);
9922     }
9923     return getCouldNotCompute();
9924   }
9925 
9926   // Otherwise we can only handle this if it is affine.
9927   if (!AddRec->isAffine())
9928     return getCouldNotCompute();
9929 
9930   // If this is an affine expression, the execution count of this branch is
9931   // the minimum unsigned root of the following equation:
9932   //
9933   //     Start + Step*N = 0 (mod 2^BW)
9934   //
9935   // equivalent to:
9936   //
9937   //             Step*N = -Start (mod 2^BW)
9938   //
9939   // where BW is the common bit width of Start and Step.
9940 
9941   // Get the initial value for the loop.
9942   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9943   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9944 
9945   // For now we handle only constant steps.
9946   //
9947   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9948   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9949   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9950   // We have not yet seen any such cases.
9951   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9952   if (!StepC || StepC->getValue()->isZero())
9953     return getCouldNotCompute();
9954 
9955   // For positive steps (counting up until unsigned overflow):
9956   //   N = -Start/Step (as unsigned)
9957   // For negative steps (counting down to zero):
9958   //   N = Start/-Step
9959   // First compute the unsigned distance from zero in the direction of Step.
9960   bool CountDown = StepC->getAPInt().isNegative();
9961   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9962 
9963   // Handle unitary steps, which cannot wraparound.
9964   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9965   //   N = Distance (as unsigned)
9966   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9967     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9968     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
9969 
9970     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9971     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9972     // case, and see if we can improve the bound.
9973     //
9974     // Explicitly handling this here is necessary because getUnsignedRange
9975     // isn't context-sensitive; it doesn't know that we only care about the
9976     // range inside the loop.
9977     const SCEV *Zero = getZero(Distance->getType());
9978     const SCEV *One = getOne(Distance->getType());
9979     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9980     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9981       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9982       // as "unsigned_max(Distance + 1) - 1".
9983       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9984       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9985     }
9986     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9987   }
9988 
9989   // If the condition controls loop exit (the loop exits only if the expression
9990   // is true) and the addition is no-wrap we can use unsigned divide to
9991   // compute the backedge count.  In this case, the step may not divide the
9992   // distance, but we don't care because if the condition is "missed" the loop
9993   // will have undefined behavior due to wrapping.
9994   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9995       loopHasNoAbnormalExits(AddRec->getLoop())) {
9996     const SCEV *Exact =
9997         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9998     const SCEV *Max = getCouldNotCompute();
9999     if (Exact != getCouldNotCompute()) {
10000       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10001       Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10002     }
10003     return ExitLimit(Exact, Max, false, Predicates);
10004   }
10005 
10006   // Solve the general equation.
10007   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10008                                                getNegativeSCEV(Start), *this);
10009 
10010   const SCEV *M = E;
10011   if (E != getCouldNotCompute()) {
10012     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10013     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10014   }
10015   return ExitLimit(E, M, false, Predicates);
10016 }
10017 
10018 ScalarEvolution::ExitLimit
10019 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10020   // Loops that look like: while (X == 0) are very strange indeed.  We don't
10021   // handle them yet except for the trivial case.  This could be expanded in the
10022   // future as needed.
10023 
10024   // If the value is a constant, check to see if it is known to be non-zero
10025   // already.  If so, the backedge will execute zero times.
10026   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10027     if (!C->getValue()->isZero())
10028       return getZero(C->getType());
10029     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10030   }
10031 
10032   // We could implement others, but I really doubt anyone writes loops like
10033   // this, and if they did, they would already be constant folded.
10034   return getCouldNotCompute();
10035 }
10036 
10037 std::pair<const BasicBlock *, const BasicBlock *>
10038 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10039     const {
10040   // If the block has a unique predecessor, then there is no path from the
10041   // predecessor to the block that does not go through the direct edge
10042   // from the predecessor to the block.
10043   if (const BasicBlock *Pred = BB->getSinglePredecessor())
10044     return {Pred, BB};
10045 
10046   // A loop's header is defined to be a block that dominates the loop.
10047   // If the header has a unique predecessor outside the loop, it must be
10048   // a block that has exactly one successor that can reach the loop.
10049   if (const Loop *L = LI.getLoopFor(BB))
10050     return {L->getLoopPredecessor(), L->getHeader()};
10051 
10052   return {nullptr, nullptr};
10053 }
10054 
10055 /// SCEV structural equivalence is usually sufficient for testing whether two
10056 /// expressions are equal, however for the purposes of looking for a condition
10057 /// guarding a loop, it can be useful to be a little more general, since a
10058 /// front-end may have replicated the controlling expression.
10059 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10060   // Quick check to see if they are the same SCEV.
10061   if (A == B) return true;
10062 
10063   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10064     // Not all instructions that are "identical" compute the same value.  For
10065     // instance, two distinct alloca instructions allocating the same type are
10066     // identical and do not read memory; but compute distinct values.
10067     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10068   };
10069 
10070   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10071   // two different instructions with the same value. Check for this case.
10072   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10073     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10074       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10075         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10076           if (ComputesEqualValues(AI, BI))
10077             return true;
10078 
10079   // Otherwise assume they may have a different value.
10080   return false;
10081 }
10082 
10083 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10084                                            const SCEV *&LHS, const SCEV *&RHS,
10085                                            unsigned Depth,
10086                                            bool ControllingFiniteLoop) {
10087   bool Changed = false;
10088   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10089   // '0 != 0'.
10090   auto TrivialCase = [&](bool TriviallyTrue) {
10091     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10092     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10093     return true;
10094   };
10095   // If we hit the max recursion limit bail out.
10096   if (Depth >= 3)
10097     return false;
10098 
10099   // Canonicalize a constant to the right side.
10100   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10101     // Check for both operands constant.
10102     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10103       if (ConstantExpr::getICmp(Pred,
10104                                 LHSC->getValue(),
10105                                 RHSC->getValue())->isNullValue())
10106         return TrivialCase(false);
10107       else
10108         return TrivialCase(true);
10109     }
10110     // Otherwise swap the operands to put the constant on the right.
10111     std::swap(LHS, RHS);
10112     Pred = ICmpInst::getSwappedPredicate(Pred);
10113     Changed = true;
10114   }
10115 
10116   // If we're comparing an addrec with a value which is loop-invariant in the
10117   // addrec's loop, put the addrec on the left. Also make a dominance check,
10118   // as both operands could be addrecs loop-invariant in each other's loop.
10119   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10120     const Loop *L = AR->getLoop();
10121     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10122       std::swap(LHS, RHS);
10123       Pred = ICmpInst::getSwappedPredicate(Pred);
10124       Changed = true;
10125     }
10126   }
10127 
10128   // If there's a constant operand, canonicalize comparisons with boundary
10129   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10130   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10131     const APInt &RA = RC->getAPInt();
10132 
10133     bool SimplifiedByConstantRange = false;
10134 
10135     if (!ICmpInst::isEquality(Pred)) {
10136       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10137       if (ExactCR.isFullSet())
10138         return TrivialCase(true);
10139       else if (ExactCR.isEmptySet())
10140         return TrivialCase(false);
10141 
10142       APInt NewRHS;
10143       CmpInst::Predicate NewPred;
10144       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10145           ICmpInst::isEquality(NewPred)) {
10146         // We were able to convert an inequality to an equality.
10147         Pred = NewPred;
10148         RHS = getConstant(NewRHS);
10149         Changed = SimplifiedByConstantRange = true;
10150       }
10151     }
10152 
10153     if (!SimplifiedByConstantRange) {
10154       switch (Pred) {
10155       default:
10156         break;
10157       case ICmpInst::ICMP_EQ:
10158       case ICmpInst::ICMP_NE:
10159         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10160         if (!RA)
10161           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10162             if (const SCEVMulExpr *ME =
10163                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10164               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10165                   ME->getOperand(0)->isAllOnesValue()) {
10166                 RHS = AE->getOperand(1);
10167                 LHS = ME->getOperand(1);
10168                 Changed = true;
10169               }
10170         break;
10171 
10172 
10173         // The "Should have been caught earlier!" messages refer to the fact
10174         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10175         // should have fired on the corresponding cases, and canonicalized the
10176         // check to trivial case.
10177 
10178       case ICmpInst::ICMP_UGE:
10179         assert(!RA.isMinValue() && "Should have been caught earlier!");
10180         Pred = ICmpInst::ICMP_UGT;
10181         RHS = getConstant(RA - 1);
10182         Changed = true;
10183         break;
10184       case ICmpInst::ICMP_ULE:
10185         assert(!RA.isMaxValue() && "Should have been caught earlier!");
10186         Pred = ICmpInst::ICMP_ULT;
10187         RHS = getConstant(RA + 1);
10188         Changed = true;
10189         break;
10190       case ICmpInst::ICMP_SGE:
10191         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10192         Pred = ICmpInst::ICMP_SGT;
10193         RHS = getConstant(RA - 1);
10194         Changed = true;
10195         break;
10196       case ICmpInst::ICMP_SLE:
10197         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10198         Pred = ICmpInst::ICMP_SLT;
10199         RHS = getConstant(RA + 1);
10200         Changed = true;
10201         break;
10202       }
10203     }
10204   }
10205 
10206   // Check for obvious equality.
10207   if (HasSameValue(LHS, RHS)) {
10208     if (ICmpInst::isTrueWhenEqual(Pred))
10209       return TrivialCase(true);
10210     if (ICmpInst::isFalseWhenEqual(Pred))
10211       return TrivialCase(false);
10212   }
10213 
10214   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10215   // adding or subtracting 1 from one of the operands. This can be done for
10216   // one of two reasons:
10217   // 1) The range of the RHS does not include the (signed/unsigned) boundaries
10218   // 2) The loop is finite, with this comparison controlling the exit. Since the
10219   // loop is finite, the bound cannot include the corresponding boundary
10220   // (otherwise it would loop forever).
10221   switch (Pred) {
10222   case ICmpInst::ICMP_SLE:
10223     if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) {
10224       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10225                        SCEV::FlagNSW);
10226       Pred = ICmpInst::ICMP_SLT;
10227       Changed = true;
10228     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10229       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10230                        SCEV::FlagNSW);
10231       Pred = ICmpInst::ICMP_SLT;
10232       Changed = true;
10233     }
10234     break;
10235   case ICmpInst::ICMP_SGE:
10236     if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) {
10237       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10238                        SCEV::FlagNSW);
10239       Pred = ICmpInst::ICMP_SGT;
10240       Changed = true;
10241     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10242       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10243                        SCEV::FlagNSW);
10244       Pred = ICmpInst::ICMP_SGT;
10245       Changed = true;
10246     }
10247     break;
10248   case ICmpInst::ICMP_ULE:
10249     if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) {
10250       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10251                        SCEV::FlagNUW);
10252       Pred = ICmpInst::ICMP_ULT;
10253       Changed = true;
10254     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10255       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10256       Pred = ICmpInst::ICMP_ULT;
10257       Changed = true;
10258     }
10259     break;
10260   case ICmpInst::ICMP_UGE:
10261     if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) {
10262       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10263       Pred = ICmpInst::ICMP_UGT;
10264       Changed = true;
10265     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10266       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10267                        SCEV::FlagNUW);
10268       Pred = ICmpInst::ICMP_UGT;
10269       Changed = true;
10270     }
10271     break;
10272   default:
10273     break;
10274   }
10275 
10276   // TODO: More simplifications are possible here.
10277 
10278   // Recursively simplify until we either hit a recursion limit or nothing
10279   // changes.
10280   if (Changed)
10281     return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1,
10282                                 ControllingFiniteLoop);
10283 
10284   return Changed;
10285 }
10286 
10287 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10288   return getSignedRangeMax(S).isNegative();
10289 }
10290 
10291 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10292   return getSignedRangeMin(S).isStrictlyPositive();
10293 }
10294 
10295 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10296   return !getSignedRangeMin(S).isNegative();
10297 }
10298 
10299 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10300   return !getSignedRangeMax(S).isStrictlyPositive();
10301 }
10302 
10303 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10304   return getUnsignedRangeMin(S) != 0;
10305 }
10306 
10307 std::pair<const SCEV *, const SCEV *>
10308 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10309   // Compute SCEV on entry of loop L.
10310   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10311   if (Start == getCouldNotCompute())
10312     return { Start, Start };
10313   // Compute post increment SCEV for loop L.
10314   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10315   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10316   return { Start, PostInc };
10317 }
10318 
10319 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10320                                           const SCEV *LHS, const SCEV *RHS) {
10321   // First collect all loops.
10322   SmallPtrSet<const Loop *, 8> LoopsUsed;
10323   getUsedLoops(LHS, LoopsUsed);
10324   getUsedLoops(RHS, LoopsUsed);
10325 
10326   if (LoopsUsed.empty())
10327     return false;
10328 
10329   // Domination relationship must be a linear order on collected loops.
10330 #ifndef NDEBUG
10331   for (auto *L1 : LoopsUsed)
10332     for (auto *L2 : LoopsUsed)
10333       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10334               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10335              "Domination relationship is not a linear order");
10336 #endif
10337 
10338   const Loop *MDL =
10339       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10340                         [&](const Loop *L1, const Loop *L2) {
10341          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10342        });
10343 
10344   // Get init and post increment value for LHS.
10345   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10346   // if LHS contains unknown non-invariant SCEV then bail out.
10347   if (SplitLHS.first == getCouldNotCompute())
10348     return false;
10349   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10350   // Get init and post increment value for RHS.
10351   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10352   // if RHS contains unknown non-invariant SCEV then bail out.
10353   if (SplitRHS.first == getCouldNotCompute())
10354     return false;
10355   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10356   // It is possible that init SCEV contains an invariant load but it does
10357   // not dominate MDL and is not available at MDL loop entry, so we should
10358   // check it here.
10359   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10360       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10361     return false;
10362 
10363   // It seems backedge guard check is faster than entry one so in some cases
10364   // it can speed up whole estimation by short circuit
10365   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10366                                      SplitRHS.second) &&
10367          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10368 }
10369 
10370 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10371                                        const SCEV *LHS, const SCEV *RHS) {
10372   // Canonicalize the inputs first.
10373   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10374 
10375   if (isKnownViaInduction(Pred, LHS, RHS))
10376     return true;
10377 
10378   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10379     return true;
10380 
10381   // Otherwise see what can be done with some simple reasoning.
10382   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10383 }
10384 
10385 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10386                                                   const SCEV *LHS,
10387                                                   const SCEV *RHS) {
10388   if (isKnownPredicate(Pred, LHS, RHS))
10389     return true;
10390   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10391     return false;
10392   return None;
10393 }
10394 
10395 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10396                                          const SCEV *LHS, const SCEV *RHS,
10397                                          const Instruction *CtxI) {
10398   // TODO: Analyze guards and assumes from Context's block.
10399   return isKnownPredicate(Pred, LHS, RHS) ||
10400          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10401 }
10402 
10403 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred,
10404                                                     const SCEV *LHS,
10405                                                     const SCEV *RHS,
10406                                                     const Instruction *CtxI) {
10407   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10408   if (KnownWithoutContext)
10409     return KnownWithoutContext;
10410 
10411   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10412     return true;
10413   else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10414                                           ICmpInst::getInversePredicate(Pred),
10415                                           LHS, RHS))
10416     return false;
10417   return None;
10418 }
10419 
10420 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10421                                               const SCEVAddRecExpr *LHS,
10422                                               const SCEV *RHS) {
10423   const Loop *L = LHS->getLoop();
10424   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10425          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10426 }
10427 
10428 Optional<ScalarEvolution::MonotonicPredicateType>
10429 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10430                                            ICmpInst::Predicate Pred) {
10431   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10432 
10433 #ifndef NDEBUG
10434   // Verify an invariant: inverting the predicate should turn a monotonically
10435   // increasing change to a monotonically decreasing one, and vice versa.
10436   if (Result) {
10437     auto ResultSwapped =
10438         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10439 
10440     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
10441     assert(ResultSwapped.getValue() != Result.getValue() &&
10442            "monotonicity should flip as we flip the predicate");
10443   }
10444 #endif
10445 
10446   return Result;
10447 }
10448 
10449 Optional<ScalarEvolution::MonotonicPredicateType>
10450 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10451                                                ICmpInst::Predicate Pred) {
10452   // A zero step value for LHS means the induction variable is essentially a
10453   // loop invariant value. We don't really depend on the predicate actually
10454   // flipping from false to true (for increasing predicates, and the other way
10455   // around for decreasing predicates), all we care about is that *if* the
10456   // predicate changes then it only changes from false to true.
10457   //
10458   // A zero step value in itself is not very useful, but there may be places
10459   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10460   // as general as possible.
10461 
10462   // Only handle LE/LT/GE/GT predicates.
10463   if (!ICmpInst::isRelational(Pred))
10464     return None;
10465 
10466   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10467   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10468          "Should be greater or less!");
10469 
10470   // Check that AR does not wrap.
10471   if (ICmpInst::isUnsigned(Pred)) {
10472     if (!LHS->hasNoUnsignedWrap())
10473       return None;
10474     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10475   } else {
10476     assert(ICmpInst::isSigned(Pred) &&
10477            "Relational predicate is either signed or unsigned!");
10478     if (!LHS->hasNoSignedWrap())
10479       return None;
10480 
10481     const SCEV *Step = LHS->getStepRecurrence(*this);
10482 
10483     if (isKnownNonNegative(Step))
10484       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10485 
10486     if (isKnownNonPositive(Step))
10487       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10488 
10489     return None;
10490   }
10491 }
10492 
10493 Optional<ScalarEvolution::LoopInvariantPredicate>
10494 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10495                                            const SCEV *LHS, const SCEV *RHS,
10496                                            const Loop *L) {
10497 
10498   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10499   if (!isLoopInvariant(RHS, L)) {
10500     if (!isLoopInvariant(LHS, L))
10501       return None;
10502 
10503     std::swap(LHS, RHS);
10504     Pred = ICmpInst::getSwappedPredicate(Pred);
10505   }
10506 
10507   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10508   if (!ArLHS || ArLHS->getLoop() != L)
10509     return None;
10510 
10511   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10512   if (!MonotonicType)
10513     return None;
10514   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10515   // true as the loop iterates, and the backedge is control dependent on
10516   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10517   //
10518   //   * if the predicate was false in the first iteration then the predicate
10519   //     is never evaluated again, since the loop exits without taking the
10520   //     backedge.
10521   //   * if the predicate was true in the first iteration then it will
10522   //     continue to be true for all future iterations since it is
10523   //     monotonically increasing.
10524   //
10525   // For both the above possibilities, we can replace the loop varying
10526   // predicate with its value on the first iteration of the loop (which is
10527   // loop invariant).
10528   //
10529   // A similar reasoning applies for a monotonically decreasing predicate, by
10530   // replacing true with false and false with true in the above two bullets.
10531   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10532   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10533 
10534   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10535     return None;
10536 
10537   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10538 }
10539 
10540 Optional<ScalarEvolution::LoopInvariantPredicate>
10541 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10542     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10543     const Instruction *CtxI, const SCEV *MaxIter) {
10544   // Try to prove the following set of facts:
10545   // - The predicate is monotonic in the iteration space.
10546   // - If the check does not fail on the 1st iteration:
10547   //   - No overflow will happen during first MaxIter iterations;
10548   //   - It will not fail on the MaxIter'th iteration.
10549   // If the check does fail on the 1st iteration, we leave the loop and no
10550   // other checks matter.
10551 
10552   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10553   if (!isLoopInvariant(RHS, L)) {
10554     if (!isLoopInvariant(LHS, L))
10555       return None;
10556 
10557     std::swap(LHS, RHS);
10558     Pred = ICmpInst::getSwappedPredicate(Pred);
10559   }
10560 
10561   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10562   if (!AR || AR->getLoop() != L)
10563     return None;
10564 
10565   // The predicate must be relational (i.e. <, <=, >=, >).
10566   if (!ICmpInst::isRelational(Pred))
10567     return None;
10568 
10569   // TODO: Support steps other than +/- 1.
10570   const SCEV *Step = AR->getStepRecurrence(*this);
10571   auto *One = getOne(Step->getType());
10572   auto *MinusOne = getNegativeSCEV(One);
10573   if (Step != One && Step != MinusOne)
10574     return None;
10575 
10576   // Type mismatch here means that MaxIter is potentially larger than max
10577   // unsigned value in start type, which mean we cannot prove no wrap for the
10578   // indvar.
10579   if (AR->getType() != MaxIter->getType())
10580     return None;
10581 
10582   // Value of IV on suggested last iteration.
10583   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10584   // Does it still meet the requirement?
10585   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10586     return None;
10587   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10588   // not exceed max unsigned value of this type), this effectively proves
10589   // that there is no wrap during the iteration. To prove that there is no
10590   // signed/unsigned wrap, we need to check that
10591   // Start <= Last for step = 1 or Start >= Last for step = -1.
10592   ICmpInst::Predicate NoOverflowPred =
10593       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10594   if (Step == MinusOne)
10595     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10596   const SCEV *Start = AR->getStart();
10597   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
10598     return None;
10599 
10600   // Everything is fine.
10601   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10602 }
10603 
10604 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10605     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10606   if (HasSameValue(LHS, RHS))
10607     return ICmpInst::isTrueWhenEqual(Pred);
10608 
10609   // This code is split out from isKnownPredicate because it is called from
10610   // within isLoopEntryGuardedByCond.
10611 
10612   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10613                          const ConstantRange &RangeRHS) {
10614     return RangeLHS.icmp(Pred, RangeRHS);
10615   };
10616 
10617   // The check at the top of the function catches the case where the values are
10618   // known to be equal.
10619   if (Pred == CmpInst::ICMP_EQ)
10620     return false;
10621 
10622   if (Pred == CmpInst::ICMP_NE) {
10623     if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10624         CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)))
10625       return true;
10626     auto *Diff = getMinusSCEV(LHS, RHS);
10627     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10628   }
10629 
10630   if (CmpInst::isSigned(Pred))
10631     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10632 
10633   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10634 }
10635 
10636 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10637                                                     const SCEV *LHS,
10638                                                     const SCEV *RHS) {
10639   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10640   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10641   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10642   // OutC1 and OutC2.
10643   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10644                                       APInt &OutC1, APInt &OutC2,
10645                                       SCEV::NoWrapFlags ExpectedFlags) {
10646     const SCEV *XNonConstOp, *XConstOp;
10647     const SCEV *YNonConstOp, *YConstOp;
10648     SCEV::NoWrapFlags XFlagsPresent;
10649     SCEV::NoWrapFlags YFlagsPresent;
10650 
10651     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10652       XConstOp = getZero(X->getType());
10653       XNonConstOp = X;
10654       XFlagsPresent = ExpectedFlags;
10655     }
10656     if (!isa<SCEVConstant>(XConstOp) ||
10657         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10658       return false;
10659 
10660     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10661       YConstOp = getZero(Y->getType());
10662       YNonConstOp = Y;
10663       YFlagsPresent = ExpectedFlags;
10664     }
10665 
10666     if (!isa<SCEVConstant>(YConstOp) ||
10667         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10668       return false;
10669 
10670     if (YNonConstOp != XNonConstOp)
10671       return false;
10672 
10673     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10674     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10675 
10676     return true;
10677   };
10678 
10679   APInt C1;
10680   APInt C2;
10681 
10682   switch (Pred) {
10683   default:
10684     break;
10685 
10686   case ICmpInst::ICMP_SGE:
10687     std::swap(LHS, RHS);
10688     LLVM_FALLTHROUGH;
10689   case ICmpInst::ICMP_SLE:
10690     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10691     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10692       return true;
10693 
10694     break;
10695 
10696   case ICmpInst::ICMP_SGT:
10697     std::swap(LHS, RHS);
10698     LLVM_FALLTHROUGH;
10699   case ICmpInst::ICMP_SLT:
10700     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10701     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10702       return true;
10703 
10704     break;
10705 
10706   case ICmpInst::ICMP_UGE:
10707     std::swap(LHS, RHS);
10708     LLVM_FALLTHROUGH;
10709   case ICmpInst::ICMP_ULE:
10710     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10711     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10712       return true;
10713 
10714     break;
10715 
10716   case ICmpInst::ICMP_UGT:
10717     std::swap(LHS, RHS);
10718     LLVM_FALLTHROUGH;
10719   case ICmpInst::ICMP_ULT:
10720     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10721     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10722       return true;
10723     break;
10724   }
10725 
10726   return false;
10727 }
10728 
10729 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10730                                                    const SCEV *LHS,
10731                                                    const SCEV *RHS) {
10732   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10733     return false;
10734 
10735   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10736   // the stack can result in exponential time complexity.
10737   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10738 
10739   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10740   //
10741   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10742   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10743   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10744   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10745   // use isKnownPredicate later if needed.
10746   return isKnownNonNegative(RHS) &&
10747          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10748          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10749 }
10750 
10751 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10752                                         ICmpInst::Predicate Pred,
10753                                         const SCEV *LHS, const SCEV *RHS) {
10754   // No need to even try if we know the module has no guards.
10755   if (!HasGuards)
10756     return false;
10757 
10758   return any_of(*BB, [&](const Instruction &I) {
10759     using namespace llvm::PatternMatch;
10760 
10761     Value *Condition;
10762     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10763                          m_Value(Condition))) &&
10764            isImpliedCond(Pred, LHS, RHS, Condition, false);
10765   });
10766 }
10767 
10768 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10769 /// protected by a conditional between LHS and RHS.  This is used to
10770 /// to eliminate casts.
10771 bool
10772 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10773                                              ICmpInst::Predicate Pred,
10774                                              const SCEV *LHS, const SCEV *RHS) {
10775   // Interpret a null as meaning no loop, where there is obviously no guard
10776   // (interprocedural conditions notwithstanding).
10777   if (!L) return true;
10778 
10779   if (VerifyIR)
10780     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10781            "This cannot be done on broken IR!");
10782 
10783 
10784   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10785     return true;
10786 
10787   BasicBlock *Latch = L->getLoopLatch();
10788   if (!Latch)
10789     return false;
10790 
10791   BranchInst *LoopContinuePredicate =
10792     dyn_cast<BranchInst>(Latch->getTerminator());
10793   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10794       isImpliedCond(Pred, LHS, RHS,
10795                     LoopContinuePredicate->getCondition(),
10796                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10797     return true;
10798 
10799   // We don't want more than one activation of the following loops on the stack
10800   // -- that can lead to O(n!) time complexity.
10801   if (WalkingBEDominatingConds)
10802     return false;
10803 
10804   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10805 
10806   // See if we can exploit a trip count to prove the predicate.
10807   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10808   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10809   if (LatchBECount != getCouldNotCompute()) {
10810     // We know that Latch branches back to the loop header exactly
10811     // LatchBECount times.  This means the backdege condition at Latch is
10812     // equivalent to  "{0,+,1} u< LatchBECount".
10813     Type *Ty = LatchBECount->getType();
10814     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10815     const SCEV *LoopCounter =
10816       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10817     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10818                       LatchBECount))
10819       return true;
10820   }
10821 
10822   // Check conditions due to any @llvm.assume intrinsics.
10823   for (auto &AssumeVH : AC.assumptions()) {
10824     if (!AssumeVH)
10825       continue;
10826     auto *CI = cast<CallInst>(AssumeVH);
10827     if (!DT.dominates(CI, Latch->getTerminator()))
10828       continue;
10829 
10830     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10831       return true;
10832   }
10833 
10834   // If the loop is not reachable from the entry block, we risk running into an
10835   // infinite loop as we walk up into the dom tree.  These loops do not matter
10836   // anyway, so we just return a conservative answer when we see them.
10837   if (!DT.isReachableFromEntry(L->getHeader()))
10838     return false;
10839 
10840   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10841     return true;
10842 
10843   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10844        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10845     assert(DTN && "should reach the loop header before reaching the root!");
10846 
10847     BasicBlock *BB = DTN->getBlock();
10848     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10849       return true;
10850 
10851     BasicBlock *PBB = BB->getSinglePredecessor();
10852     if (!PBB)
10853       continue;
10854 
10855     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10856     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10857       continue;
10858 
10859     Value *Condition = ContinuePredicate->getCondition();
10860 
10861     // If we have an edge `E` within the loop body that dominates the only
10862     // latch, the condition guarding `E` also guards the backedge.  This
10863     // reasoning works only for loops with a single latch.
10864 
10865     BasicBlockEdge DominatingEdge(PBB, BB);
10866     if (DominatingEdge.isSingleEdge()) {
10867       // We're constructively (and conservatively) enumerating edges within the
10868       // loop body that dominate the latch.  The dominator tree better agree
10869       // with us on this:
10870       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10871 
10872       if (isImpliedCond(Pred, LHS, RHS, Condition,
10873                         BB != ContinuePredicate->getSuccessor(0)))
10874         return true;
10875     }
10876   }
10877 
10878   return false;
10879 }
10880 
10881 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10882                                                      ICmpInst::Predicate Pred,
10883                                                      const SCEV *LHS,
10884                                                      const SCEV *RHS) {
10885   if (VerifyIR)
10886     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10887            "This cannot be done on broken IR!");
10888 
10889   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10890   // the facts (a >= b && a != b) separately. A typical situation is when the
10891   // non-strict comparison is known from ranges and non-equality is known from
10892   // dominating predicates. If we are proving strict comparison, we always try
10893   // to prove non-equality and non-strict comparison separately.
10894   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10895   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10896   bool ProvedNonStrictComparison = false;
10897   bool ProvedNonEquality = false;
10898 
10899   auto SplitAndProve =
10900     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10901     if (!ProvedNonStrictComparison)
10902       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10903     if (!ProvedNonEquality)
10904       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10905     if (ProvedNonStrictComparison && ProvedNonEquality)
10906       return true;
10907     return false;
10908   };
10909 
10910   if (ProvingStrictComparison) {
10911     auto ProofFn = [&](ICmpInst::Predicate P) {
10912       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10913     };
10914     if (SplitAndProve(ProofFn))
10915       return true;
10916   }
10917 
10918   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10919   auto ProveViaGuard = [&](const BasicBlock *Block) {
10920     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10921       return true;
10922     if (ProvingStrictComparison) {
10923       auto ProofFn = [&](ICmpInst::Predicate P) {
10924         return isImpliedViaGuard(Block, P, LHS, RHS);
10925       };
10926       if (SplitAndProve(ProofFn))
10927         return true;
10928     }
10929     return false;
10930   };
10931 
10932   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10933   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10934     const Instruction *CtxI = &BB->front();
10935     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
10936       return true;
10937     if (ProvingStrictComparison) {
10938       auto ProofFn = [&](ICmpInst::Predicate P) {
10939         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
10940       };
10941       if (SplitAndProve(ProofFn))
10942         return true;
10943     }
10944     return false;
10945   };
10946 
10947   // Starting at the block's predecessor, climb up the predecessor chain, as long
10948   // as there are predecessors that can be found that have unique successors
10949   // leading to the original block.
10950   const Loop *ContainingLoop = LI.getLoopFor(BB);
10951   const BasicBlock *PredBB;
10952   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10953     PredBB = ContainingLoop->getLoopPredecessor();
10954   else
10955     PredBB = BB->getSinglePredecessor();
10956   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10957        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10958     if (ProveViaGuard(Pair.first))
10959       return true;
10960 
10961     const BranchInst *LoopEntryPredicate =
10962         dyn_cast<BranchInst>(Pair.first->getTerminator());
10963     if (!LoopEntryPredicate ||
10964         LoopEntryPredicate->isUnconditional())
10965       continue;
10966 
10967     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10968                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10969       return true;
10970   }
10971 
10972   // Check conditions due to any @llvm.assume intrinsics.
10973   for (auto &AssumeVH : AC.assumptions()) {
10974     if (!AssumeVH)
10975       continue;
10976     auto *CI = cast<CallInst>(AssumeVH);
10977     if (!DT.dominates(CI, BB))
10978       continue;
10979 
10980     if (ProveViaCond(CI->getArgOperand(0), false))
10981       return true;
10982   }
10983 
10984   return false;
10985 }
10986 
10987 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10988                                                ICmpInst::Predicate Pred,
10989                                                const SCEV *LHS,
10990                                                const SCEV *RHS) {
10991   // Interpret a null as meaning no loop, where there is obviously no guard
10992   // (interprocedural conditions notwithstanding).
10993   if (!L)
10994     return false;
10995 
10996   // Both LHS and RHS must be available at loop entry.
10997   assert(isAvailableAtLoopEntry(LHS, L) &&
10998          "LHS is not available at Loop Entry");
10999   assert(isAvailableAtLoopEntry(RHS, L) &&
11000          "RHS is not available at Loop Entry");
11001 
11002   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11003     return true;
11004 
11005   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11006 }
11007 
11008 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11009                                     const SCEV *RHS,
11010                                     const Value *FoundCondValue, bool Inverse,
11011                                     const Instruction *CtxI) {
11012   // False conditions implies anything. Do not bother analyzing it further.
11013   if (FoundCondValue ==
11014       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11015     return true;
11016 
11017   if (!PendingLoopPredicates.insert(FoundCondValue).second)
11018     return false;
11019 
11020   auto ClearOnExit =
11021       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11022 
11023   // Recursively handle And and Or conditions.
11024   const Value *Op0, *Op1;
11025   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11026     if (!Inverse)
11027       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11028              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11029   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11030     if (Inverse)
11031       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11032              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11033   }
11034 
11035   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11036   if (!ICI) return false;
11037 
11038   // Now that we found a conditional branch that dominates the loop or controls
11039   // the loop latch. Check to see if it is the comparison we are looking for.
11040   ICmpInst::Predicate FoundPred;
11041   if (Inverse)
11042     FoundPred = ICI->getInversePredicate();
11043   else
11044     FoundPred = ICI->getPredicate();
11045 
11046   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11047   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11048 
11049   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11050 }
11051 
11052 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11053                                     const SCEV *RHS,
11054                                     ICmpInst::Predicate FoundPred,
11055                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
11056                                     const Instruction *CtxI) {
11057   // Balance the types.
11058   if (getTypeSizeInBits(LHS->getType()) <
11059       getTypeSizeInBits(FoundLHS->getType())) {
11060     // For unsigned and equality predicates, try to prove that both found
11061     // operands fit into narrow unsigned range. If so, try to prove facts in
11062     // narrow types.
11063     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11064         !FoundRHS->getType()->isPointerTy()) {
11065       auto *NarrowType = LHS->getType();
11066       auto *WideType = FoundLHS->getType();
11067       auto BitWidth = getTypeSizeInBits(NarrowType);
11068       const SCEV *MaxValue = getZeroExtendExpr(
11069           getConstant(APInt::getMaxValue(BitWidth)), WideType);
11070       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11071                                           MaxValue) &&
11072           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11073                                           MaxValue)) {
11074         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11075         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11076         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11077                                        TruncFoundRHS, CtxI))
11078           return true;
11079       }
11080     }
11081 
11082     if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11083       return false;
11084     if (CmpInst::isSigned(Pred)) {
11085       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11086       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11087     } else {
11088       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11089       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11090     }
11091   } else if (getTypeSizeInBits(LHS->getType()) >
11092       getTypeSizeInBits(FoundLHS->getType())) {
11093     if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11094       return false;
11095     if (CmpInst::isSigned(FoundPred)) {
11096       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11097       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11098     } else {
11099       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11100       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11101     }
11102   }
11103   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11104                                     FoundRHS, CtxI);
11105 }
11106 
11107 bool ScalarEvolution::isImpliedCondBalancedTypes(
11108     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11109     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11110     const Instruction *CtxI) {
11111   assert(getTypeSizeInBits(LHS->getType()) ==
11112              getTypeSizeInBits(FoundLHS->getType()) &&
11113          "Types should be balanced!");
11114   // Canonicalize the query to match the way instcombine will have
11115   // canonicalized the comparison.
11116   if (SimplifyICmpOperands(Pred, LHS, RHS))
11117     if (LHS == RHS)
11118       return CmpInst::isTrueWhenEqual(Pred);
11119   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11120     if (FoundLHS == FoundRHS)
11121       return CmpInst::isFalseWhenEqual(FoundPred);
11122 
11123   // Check to see if we can make the LHS or RHS match.
11124   if (LHS == FoundRHS || RHS == FoundLHS) {
11125     if (isa<SCEVConstant>(RHS)) {
11126       std::swap(FoundLHS, FoundRHS);
11127       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11128     } else {
11129       std::swap(LHS, RHS);
11130       Pred = ICmpInst::getSwappedPredicate(Pred);
11131     }
11132   }
11133 
11134   // Check whether the found predicate is the same as the desired predicate.
11135   if (FoundPred == Pred)
11136     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11137 
11138   // Check whether swapping the found predicate makes it the same as the
11139   // desired predicate.
11140   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11141     // We can write the implication
11142     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
11143     // using one of the following ways:
11144     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
11145     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
11146     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
11147     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
11148     // Forms 1. and 2. require swapping the operands of one condition. Don't
11149     // do this if it would break canonical constant/addrec ordering.
11150     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11151       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11152                                    CtxI);
11153     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11154       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11155 
11156     // There's no clear preference between forms 3. and 4., try both.  Avoid
11157     // forming getNotSCEV of pointer values as the resulting subtract is
11158     // not legal.
11159     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11160         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11161                               FoundLHS, FoundRHS, CtxI))
11162       return true;
11163 
11164     if (!FoundLHS->getType()->isPointerTy() &&
11165         !FoundRHS->getType()->isPointerTy() &&
11166         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11167                               getNotSCEV(FoundRHS), CtxI))
11168       return true;
11169 
11170     return false;
11171   }
11172 
11173   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11174                                    CmpInst::Predicate P2) {
11175     assert(P1 != P2 && "Handled earlier!");
11176     return CmpInst::isRelational(P2) &&
11177            P1 == CmpInst::getFlippedSignednessPredicate(P2);
11178   };
11179   if (IsSignFlippedPredicate(Pred, FoundPred)) {
11180     // Unsigned comparison is the same as signed comparison when both the
11181     // operands are non-negative or negative.
11182     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11183         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11184       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11185     // Create local copies that we can freely swap and canonicalize our
11186     // conditions to "le/lt".
11187     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11188     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11189                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11190     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11191       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11192       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11193       std::swap(CanonicalLHS, CanonicalRHS);
11194       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11195     }
11196     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11197            "Must be!");
11198     assert((ICmpInst::isLT(CanonicalFoundPred) ||
11199             ICmpInst::isLE(CanonicalFoundPred)) &&
11200            "Must be!");
11201     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11202       // Use implication:
11203       // x <u y && y >=s 0 --> x <s y.
11204       // If we can prove the left part, the right part is also proven.
11205       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11206                                    CanonicalRHS, CanonicalFoundLHS,
11207                                    CanonicalFoundRHS);
11208     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11209       // Use implication:
11210       // x <s y && y <s 0 --> x <u y.
11211       // If we can prove the left part, the right part is also proven.
11212       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11213                                    CanonicalRHS, CanonicalFoundLHS,
11214                                    CanonicalFoundRHS);
11215   }
11216 
11217   // Check if we can make progress by sharpening ranges.
11218   if (FoundPred == ICmpInst::ICMP_NE &&
11219       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11220 
11221     const SCEVConstant *C = nullptr;
11222     const SCEV *V = nullptr;
11223 
11224     if (isa<SCEVConstant>(FoundLHS)) {
11225       C = cast<SCEVConstant>(FoundLHS);
11226       V = FoundRHS;
11227     } else {
11228       C = cast<SCEVConstant>(FoundRHS);
11229       V = FoundLHS;
11230     }
11231 
11232     // The guarding predicate tells us that C != V. If the known range
11233     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
11234     // range we consider has to correspond to same signedness as the
11235     // predicate we're interested in folding.
11236 
11237     APInt Min = ICmpInst::isSigned(Pred) ?
11238         getSignedRangeMin(V) : getUnsignedRangeMin(V);
11239 
11240     if (Min == C->getAPInt()) {
11241       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11242       // This is true even if (Min + 1) wraps around -- in case of
11243       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11244 
11245       APInt SharperMin = Min + 1;
11246 
11247       switch (Pred) {
11248         case ICmpInst::ICMP_SGE:
11249         case ICmpInst::ICMP_UGE:
11250           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
11251           // RHS, we're done.
11252           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11253                                     CtxI))
11254             return true;
11255           LLVM_FALLTHROUGH;
11256 
11257         case ICmpInst::ICMP_SGT:
11258         case ICmpInst::ICMP_UGT:
11259           // We know from the range information that (V `Pred` Min ||
11260           // V == Min).  We know from the guarding condition that !(V
11261           // == Min).  This gives us
11262           //
11263           //       V `Pred` Min || V == Min && !(V == Min)
11264           //   =>  V `Pred` Min
11265           //
11266           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11267 
11268           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11269             return true;
11270           break;
11271 
11272         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11273         case ICmpInst::ICMP_SLE:
11274         case ICmpInst::ICMP_ULE:
11275           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11276                                     LHS, V, getConstant(SharperMin), CtxI))
11277             return true;
11278           LLVM_FALLTHROUGH;
11279 
11280         case ICmpInst::ICMP_SLT:
11281         case ICmpInst::ICMP_ULT:
11282           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11283                                     LHS, V, getConstant(Min), CtxI))
11284             return true;
11285           break;
11286 
11287         default:
11288           // No change
11289           break;
11290       }
11291     }
11292   }
11293 
11294   // Check whether the actual condition is beyond sufficient.
11295   if (FoundPred == ICmpInst::ICMP_EQ)
11296     if (ICmpInst::isTrueWhenEqual(Pred))
11297       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11298         return true;
11299   if (Pred == ICmpInst::ICMP_NE)
11300     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11301       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11302         return true;
11303 
11304   // Otherwise assume the worst.
11305   return false;
11306 }
11307 
11308 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11309                                      const SCEV *&L, const SCEV *&R,
11310                                      SCEV::NoWrapFlags &Flags) {
11311   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11312   if (!AE || AE->getNumOperands() != 2)
11313     return false;
11314 
11315   L = AE->getOperand(0);
11316   R = AE->getOperand(1);
11317   Flags = AE->getNoWrapFlags();
11318   return true;
11319 }
11320 
11321 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
11322                                                            const SCEV *Less) {
11323   // We avoid subtracting expressions here because this function is usually
11324   // fairly deep in the call stack (i.e. is called many times).
11325 
11326   // X - X = 0.
11327   if (More == Less)
11328     return APInt(getTypeSizeInBits(More->getType()), 0);
11329 
11330   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11331     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11332     const auto *MAR = cast<SCEVAddRecExpr>(More);
11333 
11334     if (LAR->getLoop() != MAR->getLoop())
11335       return None;
11336 
11337     // We look at affine expressions only; not for correctness but to keep
11338     // getStepRecurrence cheap.
11339     if (!LAR->isAffine() || !MAR->isAffine())
11340       return None;
11341 
11342     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11343       return None;
11344 
11345     Less = LAR->getStart();
11346     More = MAR->getStart();
11347 
11348     // fall through
11349   }
11350 
11351   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11352     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11353     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11354     return M - L;
11355   }
11356 
11357   SCEV::NoWrapFlags Flags;
11358   const SCEV *LLess = nullptr, *RLess = nullptr;
11359   const SCEV *LMore = nullptr, *RMore = nullptr;
11360   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11361   // Compare (X + C1) vs X.
11362   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11363     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11364       if (RLess == More)
11365         return -(C1->getAPInt());
11366 
11367   // Compare X vs (X + C2).
11368   if (splitBinaryAdd(More, LMore, RMore, Flags))
11369     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11370       if (RMore == Less)
11371         return C2->getAPInt();
11372 
11373   // Compare (X + C1) vs (X + C2).
11374   if (C1 && C2 && RLess == RMore)
11375     return C2->getAPInt() - C1->getAPInt();
11376 
11377   return None;
11378 }
11379 
11380 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11381     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11382     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11383   // Try to recognize the following pattern:
11384   //
11385   //   FoundRHS = ...
11386   // ...
11387   // loop:
11388   //   FoundLHS = {Start,+,W}
11389   // context_bb: // Basic block from the same loop
11390   //   known(Pred, FoundLHS, FoundRHS)
11391   //
11392   // If some predicate is known in the context of a loop, it is also known on
11393   // each iteration of this loop, including the first iteration. Therefore, in
11394   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11395   // prove the original pred using this fact.
11396   if (!CtxI)
11397     return false;
11398   const BasicBlock *ContextBB = CtxI->getParent();
11399   // Make sure AR varies in the context block.
11400   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11401     const Loop *L = AR->getLoop();
11402     // Make sure that context belongs to the loop and executes on 1st iteration
11403     // (if it ever executes at all).
11404     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11405       return false;
11406     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11407       return false;
11408     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11409   }
11410 
11411   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11412     const Loop *L = AR->getLoop();
11413     // Make sure that context belongs to the loop and executes on 1st iteration
11414     // (if it ever executes at all).
11415     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11416       return false;
11417     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11418       return false;
11419     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11420   }
11421 
11422   return false;
11423 }
11424 
11425 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11426     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11427     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11428   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11429     return false;
11430 
11431   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11432   if (!AddRecLHS)
11433     return false;
11434 
11435   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11436   if (!AddRecFoundLHS)
11437     return false;
11438 
11439   // We'd like to let SCEV reason about control dependencies, so we constrain
11440   // both the inequalities to be about add recurrences on the same loop.  This
11441   // way we can use isLoopEntryGuardedByCond later.
11442 
11443   const Loop *L = AddRecFoundLHS->getLoop();
11444   if (L != AddRecLHS->getLoop())
11445     return false;
11446 
11447   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11448   //
11449   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11450   //                                                                  ... (2)
11451   //
11452   // Informal proof for (2), assuming (1) [*]:
11453   //
11454   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11455   //
11456   // Then
11457   //
11458   //       FoundLHS s< FoundRHS s< INT_MIN - C
11459   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11460   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11461   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11462   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11463   // <=>  FoundLHS + C s< FoundRHS + C
11464   //
11465   // [*]: (1) can be proved by ruling out overflow.
11466   //
11467   // [**]: This can be proved by analyzing all the four possibilities:
11468   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11469   //    (A s>= 0, B s>= 0).
11470   //
11471   // Note:
11472   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11473   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11474   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11475   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11476   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11477   // C)".
11478 
11479   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11480   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11481   if (!LDiff || !RDiff || *LDiff != *RDiff)
11482     return false;
11483 
11484   if (LDiff->isMinValue())
11485     return true;
11486 
11487   APInt FoundRHSLimit;
11488 
11489   if (Pred == CmpInst::ICMP_ULT) {
11490     FoundRHSLimit = -(*RDiff);
11491   } else {
11492     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11493     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11494   }
11495 
11496   // Try to prove (1) or (2), as needed.
11497   return isAvailableAtLoopEntry(FoundRHS, L) &&
11498          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11499                                   getConstant(FoundRHSLimit));
11500 }
11501 
11502 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11503                                         const SCEV *LHS, const SCEV *RHS,
11504                                         const SCEV *FoundLHS,
11505                                         const SCEV *FoundRHS, unsigned Depth) {
11506   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11507 
11508   auto ClearOnExit = make_scope_exit([&]() {
11509     if (LPhi) {
11510       bool Erased = PendingMerges.erase(LPhi);
11511       assert(Erased && "Failed to erase LPhi!");
11512       (void)Erased;
11513     }
11514     if (RPhi) {
11515       bool Erased = PendingMerges.erase(RPhi);
11516       assert(Erased && "Failed to erase RPhi!");
11517       (void)Erased;
11518     }
11519   });
11520 
11521   // Find respective Phis and check that they are not being pending.
11522   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11523     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11524       if (!PendingMerges.insert(Phi).second)
11525         return false;
11526       LPhi = Phi;
11527     }
11528   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11529     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11530       // If we detect a loop of Phi nodes being processed by this method, for
11531       // example:
11532       //
11533       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11534       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11535       //
11536       // we don't want to deal with a case that complex, so return conservative
11537       // answer false.
11538       if (!PendingMerges.insert(Phi).second)
11539         return false;
11540       RPhi = Phi;
11541     }
11542 
11543   // If none of LHS, RHS is a Phi, nothing to do here.
11544   if (!LPhi && !RPhi)
11545     return false;
11546 
11547   // If there is a SCEVUnknown Phi we are interested in, make it left.
11548   if (!LPhi) {
11549     std::swap(LHS, RHS);
11550     std::swap(FoundLHS, FoundRHS);
11551     std::swap(LPhi, RPhi);
11552     Pred = ICmpInst::getSwappedPredicate(Pred);
11553   }
11554 
11555   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11556   const BasicBlock *LBB = LPhi->getParent();
11557   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11558 
11559   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11560     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11561            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11562            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11563   };
11564 
11565   if (RPhi && RPhi->getParent() == LBB) {
11566     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11567     // If we compare two Phis from the same block, and for each entry block
11568     // the predicate is true for incoming values from this block, then the
11569     // predicate is also true for the Phis.
11570     for (const BasicBlock *IncBB : predecessors(LBB)) {
11571       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11572       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11573       if (!ProvedEasily(L, R))
11574         return false;
11575     }
11576   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11577     // Case two: RHS is also a Phi from the same basic block, and it is an
11578     // AddRec. It means that there is a loop which has both AddRec and Unknown
11579     // PHIs, for it we can compare incoming values of AddRec from above the loop
11580     // and latch with their respective incoming values of LPhi.
11581     // TODO: Generalize to handle loops with many inputs in a header.
11582     if (LPhi->getNumIncomingValues() != 2) return false;
11583 
11584     auto *RLoop = RAR->getLoop();
11585     auto *Predecessor = RLoop->getLoopPredecessor();
11586     assert(Predecessor && "Loop with AddRec with no predecessor?");
11587     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11588     if (!ProvedEasily(L1, RAR->getStart()))
11589       return false;
11590     auto *Latch = RLoop->getLoopLatch();
11591     assert(Latch && "Loop with AddRec with no latch?");
11592     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11593     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11594       return false;
11595   } else {
11596     // In all other cases go over inputs of LHS and compare each of them to RHS,
11597     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11598     // At this point RHS is either a non-Phi, or it is a Phi from some block
11599     // different from LBB.
11600     for (const BasicBlock *IncBB : predecessors(LBB)) {
11601       // Check that RHS is available in this block.
11602       if (!dominates(RHS, IncBB))
11603         return false;
11604       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11605       // Make sure L does not refer to a value from a potentially previous
11606       // iteration of a loop.
11607       if (!properlyDominates(L, IncBB))
11608         return false;
11609       if (!ProvedEasily(L, RHS))
11610         return false;
11611     }
11612   }
11613   return true;
11614 }
11615 
11616 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
11617                                                     const SCEV *LHS,
11618                                                     const SCEV *RHS,
11619                                                     const SCEV *FoundLHS,
11620                                                     const SCEV *FoundRHS) {
11621   // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue).  First, make
11622   // sure that we are dealing with same LHS.
11623   if (RHS == FoundRHS) {
11624     std::swap(LHS, RHS);
11625     std::swap(FoundLHS, FoundRHS);
11626     Pred = ICmpInst::getSwappedPredicate(Pred);
11627   }
11628   if (LHS != FoundLHS)
11629     return false;
11630 
11631   auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
11632   if (!SUFoundRHS)
11633     return false;
11634 
11635   Value *Shiftee, *ShiftValue;
11636 
11637   using namespace PatternMatch;
11638   if (match(SUFoundRHS->getValue(),
11639             m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
11640     auto *ShifteeS = getSCEV(Shiftee);
11641     // Prove one of the following:
11642     // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
11643     // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
11644     // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11645     //   ---> LHS <s RHS
11646     // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11647     //   ---> LHS <=s RHS
11648     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
11649       return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
11650     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
11651       if (isKnownNonNegative(ShifteeS))
11652         return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
11653   }
11654 
11655   return false;
11656 }
11657 
11658 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11659                                             const SCEV *LHS, const SCEV *RHS,
11660                                             const SCEV *FoundLHS,
11661                                             const SCEV *FoundRHS,
11662                                             const Instruction *CtxI) {
11663   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11664     return true;
11665 
11666   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11667     return true;
11668 
11669   if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
11670     return true;
11671 
11672   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11673                                           CtxI))
11674     return true;
11675 
11676   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11677                                      FoundLHS, FoundRHS);
11678 }
11679 
11680 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11681 template <typename MinMaxExprType>
11682 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11683                                  const SCEV *Candidate) {
11684   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11685   if (!MinMaxExpr)
11686     return false;
11687 
11688   return is_contained(MinMaxExpr->operands(), Candidate);
11689 }
11690 
11691 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11692                                            ICmpInst::Predicate Pred,
11693                                            const SCEV *LHS, const SCEV *RHS) {
11694   // If both sides are affine addrecs for the same loop, with equal
11695   // steps, and we know the recurrences don't wrap, then we only
11696   // need to check the predicate on the starting values.
11697 
11698   if (!ICmpInst::isRelational(Pred))
11699     return false;
11700 
11701   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11702   if (!LAR)
11703     return false;
11704   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11705   if (!RAR)
11706     return false;
11707   if (LAR->getLoop() != RAR->getLoop())
11708     return false;
11709   if (!LAR->isAffine() || !RAR->isAffine())
11710     return false;
11711 
11712   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11713     return false;
11714 
11715   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11716                          SCEV::FlagNSW : SCEV::FlagNUW;
11717   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11718     return false;
11719 
11720   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11721 }
11722 
11723 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11724 /// expression?
11725 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11726                                         ICmpInst::Predicate Pred,
11727                                         const SCEV *LHS, const SCEV *RHS) {
11728   switch (Pred) {
11729   default:
11730     return false;
11731 
11732   case ICmpInst::ICMP_SGE:
11733     std::swap(LHS, RHS);
11734     LLVM_FALLTHROUGH;
11735   case ICmpInst::ICMP_SLE:
11736     return
11737         // min(A, ...) <= A
11738         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11739         // A <= max(A, ...)
11740         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11741 
11742   case ICmpInst::ICMP_UGE:
11743     std::swap(LHS, RHS);
11744     LLVM_FALLTHROUGH;
11745   case ICmpInst::ICMP_ULE:
11746     return
11747         // min(A, ...) <= A
11748         // FIXME: what about umin_seq?
11749         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11750         // A <= max(A, ...)
11751         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11752   }
11753 
11754   llvm_unreachable("covered switch fell through?!");
11755 }
11756 
11757 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11758                                              const SCEV *LHS, const SCEV *RHS,
11759                                              const SCEV *FoundLHS,
11760                                              const SCEV *FoundRHS,
11761                                              unsigned Depth) {
11762   assert(getTypeSizeInBits(LHS->getType()) ==
11763              getTypeSizeInBits(RHS->getType()) &&
11764          "LHS and RHS have different sizes?");
11765   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11766              getTypeSizeInBits(FoundRHS->getType()) &&
11767          "FoundLHS and FoundRHS have different sizes?");
11768   // We want to avoid hurting the compile time with analysis of too big trees.
11769   if (Depth > MaxSCEVOperationsImplicationDepth)
11770     return false;
11771 
11772   // We only want to work with GT comparison so far.
11773   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11774     Pred = CmpInst::getSwappedPredicate(Pred);
11775     std::swap(LHS, RHS);
11776     std::swap(FoundLHS, FoundRHS);
11777   }
11778 
11779   // For unsigned, try to reduce it to corresponding signed comparison.
11780   if (Pred == ICmpInst::ICMP_UGT)
11781     // We can replace unsigned predicate with its signed counterpart if all
11782     // involved values are non-negative.
11783     // TODO: We could have better support for unsigned.
11784     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11785       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11786       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11787       // use this fact to prove that LHS and RHS are non-negative.
11788       const SCEV *MinusOne = getMinusOne(LHS->getType());
11789       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11790                                 FoundRHS) &&
11791           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11792                                 FoundRHS))
11793         Pred = ICmpInst::ICMP_SGT;
11794     }
11795 
11796   if (Pred != ICmpInst::ICMP_SGT)
11797     return false;
11798 
11799   auto GetOpFromSExt = [&](const SCEV *S) {
11800     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11801       return Ext->getOperand();
11802     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11803     // the constant in some cases.
11804     return S;
11805   };
11806 
11807   // Acquire values from extensions.
11808   auto *OrigLHS = LHS;
11809   auto *OrigFoundLHS = FoundLHS;
11810   LHS = GetOpFromSExt(LHS);
11811   FoundLHS = GetOpFromSExt(FoundLHS);
11812 
11813   // Is the SGT predicate can be proved trivially or using the found context.
11814   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11815     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11816            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11817                                   FoundRHS, Depth + 1);
11818   };
11819 
11820   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11821     // We want to avoid creation of any new non-constant SCEV. Since we are
11822     // going to compare the operands to RHS, we should be certain that we don't
11823     // need any size extensions for this. So let's decline all cases when the
11824     // sizes of types of LHS and RHS do not match.
11825     // TODO: Maybe try to get RHS from sext to catch more cases?
11826     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11827       return false;
11828 
11829     // Should not overflow.
11830     if (!LHSAddExpr->hasNoSignedWrap())
11831       return false;
11832 
11833     auto *LL = LHSAddExpr->getOperand(0);
11834     auto *LR = LHSAddExpr->getOperand(1);
11835     auto *MinusOne = getMinusOne(RHS->getType());
11836 
11837     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11838     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11839       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11840     };
11841     // Try to prove the following rule:
11842     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11843     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11844     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11845       return true;
11846   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11847     Value *LL, *LR;
11848     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11849 
11850     using namespace llvm::PatternMatch;
11851 
11852     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11853       // Rules for division.
11854       // We are going to perform some comparisons with Denominator and its
11855       // derivative expressions. In general case, creating a SCEV for it may
11856       // lead to a complex analysis of the entire graph, and in particular it
11857       // can request trip count recalculation for the same loop. This would
11858       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11859       // this, we only want to create SCEVs that are constants in this section.
11860       // So we bail if Denominator is not a constant.
11861       if (!isa<ConstantInt>(LR))
11862         return false;
11863 
11864       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11865 
11866       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11867       // then a SCEV for the numerator already exists and matches with FoundLHS.
11868       auto *Numerator = getExistingSCEV(LL);
11869       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11870         return false;
11871 
11872       // Make sure that the numerator matches with FoundLHS and the denominator
11873       // is positive.
11874       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11875         return false;
11876 
11877       auto *DTy = Denominator->getType();
11878       auto *FRHSTy = FoundRHS->getType();
11879       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11880         // One of types is a pointer and another one is not. We cannot extend
11881         // them properly to a wider type, so let us just reject this case.
11882         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11883         // to avoid this check.
11884         return false;
11885 
11886       // Given that:
11887       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11888       auto *WTy = getWiderType(DTy, FRHSTy);
11889       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11890       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11891 
11892       // Try to prove the following rule:
11893       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11894       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11895       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11896       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11897       if (isKnownNonPositive(RHS) &&
11898           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11899         return true;
11900 
11901       // Try to prove the following rule:
11902       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11903       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11904       // If we divide it by Denominator > 2, then:
11905       // 1. If FoundLHS is negative, then the result is 0.
11906       // 2. If FoundLHS is non-negative, then the result is non-negative.
11907       // Anyways, the result is non-negative.
11908       auto *MinusOne = getMinusOne(WTy);
11909       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11910       if (isKnownNegative(RHS) &&
11911           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11912         return true;
11913     }
11914   }
11915 
11916   // If our expression contained SCEVUnknown Phis, and we split it down and now
11917   // need to prove something for them, try to prove the predicate for every
11918   // possible incoming values of those Phis.
11919   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11920     return true;
11921 
11922   return false;
11923 }
11924 
11925 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11926                                         const SCEV *LHS, const SCEV *RHS) {
11927   // zext x u<= sext x, sext x s<= zext x
11928   switch (Pred) {
11929   case ICmpInst::ICMP_SGE:
11930     std::swap(LHS, RHS);
11931     LLVM_FALLTHROUGH;
11932   case ICmpInst::ICMP_SLE: {
11933     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11934     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11935     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11936     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11937       return true;
11938     break;
11939   }
11940   case ICmpInst::ICMP_UGE:
11941     std::swap(LHS, RHS);
11942     LLVM_FALLTHROUGH;
11943   case ICmpInst::ICMP_ULE: {
11944     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11945     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11946     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11947     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11948       return true;
11949     break;
11950   }
11951   default:
11952     break;
11953   };
11954   return false;
11955 }
11956 
11957 bool
11958 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11959                                            const SCEV *LHS, const SCEV *RHS) {
11960   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11961          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11962          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11963          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11964          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11965 }
11966 
11967 bool
11968 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11969                                              const SCEV *LHS, const SCEV *RHS,
11970                                              const SCEV *FoundLHS,
11971                                              const SCEV *FoundRHS) {
11972   switch (Pred) {
11973   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11974   case ICmpInst::ICMP_EQ:
11975   case ICmpInst::ICMP_NE:
11976     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11977       return true;
11978     break;
11979   case ICmpInst::ICMP_SLT:
11980   case ICmpInst::ICMP_SLE:
11981     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11982         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11983       return true;
11984     break;
11985   case ICmpInst::ICMP_SGT:
11986   case ICmpInst::ICMP_SGE:
11987     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11988         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11989       return true;
11990     break;
11991   case ICmpInst::ICMP_ULT:
11992   case ICmpInst::ICMP_ULE:
11993     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11994         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11995       return true;
11996     break;
11997   case ICmpInst::ICMP_UGT:
11998   case ICmpInst::ICMP_UGE:
11999     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12000         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12001       return true;
12002     break;
12003   }
12004 
12005   // Maybe it can be proved via operations?
12006   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12007     return true;
12008 
12009   return false;
12010 }
12011 
12012 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12013                                                      const SCEV *LHS,
12014                                                      const SCEV *RHS,
12015                                                      const SCEV *FoundLHS,
12016                                                      const SCEV *FoundRHS) {
12017   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12018     // The restriction on `FoundRHS` be lifted easily -- it exists only to
12019     // reduce the compile time impact of this optimization.
12020     return false;
12021 
12022   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12023   if (!Addend)
12024     return false;
12025 
12026   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12027 
12028   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12029   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
12030   ConstantRange FoundLHSRange =
12031       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
12032 
12033   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12034   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12035 
12036   // We can also compute the range of values for `LHS` that satisfy the
12037   // consequent, "`LHS` `Pred` `RHS`":
12038   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12039   // The antecedent implies the consequent if every value of `LHS` that
12040   // satisfies the antecedent also satisfies the consequent.
12041   return LHSRange.icmp(Pred, ConstRHS);
12042 }
12043 
12044 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12045                                         bool IsSigned) {
12046   assert(isKnownPositive(Stride) && "Positive stride expected!");
12047 
12048   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12049   const SCEV *One = getOne(Stride->getType());
12050 
12051   if (IsSigned) {
12052     APInt MaxRHS = getSignedRangeMax(RHS);
12053     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12054     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12055 
12056     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12057     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12058   }
12059 
12060   APInt MaxRHS = getUnsignedRangeMax(RHS);
12061   APInt MaxValue = APInt::getMaxValue(BitWidth);
12062   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12063 
12064   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12065   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12066 }
12067 
12068 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12069                                         bool IsSigned) {
12070 
12071   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12072   const SCEV *One = getOne(Stride->getType());
12073 
12074   if (IsSigned) {
12075     APInt MinRHS = getSignedRangeMin(RHS);
12076     APInt MinValue = APInt::getSignedMinValue(BitWidth);
12077     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12078 
12079     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12080     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12081   }
12082 
12083   APInt MinRHS = getUnsignedRangeMin(RHS);
12084   APInt MinValue = APInt::getMinValue(BitWidth);
12085   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12086 
12087   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12088   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12089 }
12090 
12091 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12092   // umin(N, 1) + floor((N - umin(N, 1)) / D)
12093   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12094   // expression fixes the case of N=0.
12095   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12096   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12097   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12098 }
12099 
12100 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12101                                                     const SCEV *Stride,
12102                                                     const SCEV *End,
12103                                                     unsigned BitWidth,
12104                                                     bool IsSigned) {
12105   // The logic in this function assumes we can represent a positive stride.
12106   // If we can't, the backedge-taken count must be zero.
12107   if (IsSigned && BitWidth == 1)
12108     return getZero(Stride->getType());
12109 
12110   // This code has only been closely audited for negative strides in the
12111   // unsigned comparison case, it may be correct for signed comparison, but
12112   // that needs to be established.
12113   assert((!IsSigned || !isKnownNonPositive(Stride)) &&
12114          "Stride is expected strictly positive for signed case!");
12115 
12116   // Calculate the maximum backedge count based on the range of values
12117   // permitted by Start, End, and Stride.
12118   APInt MinStart =
12119       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12120 
12121   APInt MinStride =
12122       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12123 
12124   // We assume either the stride is positive, or the backedge-taken count
12125   // is zero. So force StrideForMaxBECount to be at least one.
12126   APInt One(BitWidth, 1);
12127   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12128                                        : APIntOps::umax(One, MinStride);
12129 
12130   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12131                             : APInt::getMaxValue(BitWidth);
12132   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12133 
12134   // Although End can be a MAX expression we estimate MaxEnd considering only
12135   // the case End = RHS of the loop termination condition. This is safe because
12136   // in the other case (End - Start) is zero, leading to a zero maximum backedge
12137   // taken count.
12138   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12139                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12140 
12141   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12142   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12143                     : APIntOps::umax(MaxEnd, MinStart);
12144 
12145   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12146                          getConstant(StrideForMaxBECount) /* Step */);
12147 }
12148 
12149 ScalarEvolution::ExitLimit
12150 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12151                                   const Loop *L, bool IsSigned,
12152                                   bool ControlsExit, bool AllowPredicates) {
12153   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12154 
12155   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12156   bool PredicatedIV = false;
12157 
12158   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12159     // Can we prove this loop *must* be UB if overflow of IV occurs?
12160     // Reasoning goes as follows:
12161     // * Suppose the IV did self wrap.
12162     // * If Stride evenly divides the iteration space, then once wrap
12163     //   occurs, the loop must revisit the same values.
12164     // * We know that RHS is invariant, and that none of those values
12165     //   caused this exit to be taken previously.  Thus, this exit is
12166     //   dynamically dead.
12167     // * If this is the sole exit, then a dead exit implies the loop
12168     //   must be infinite if there are no abnormal exits.
12169     // * If the loop were infinite, then it must either not be mustprogress
12170     //   or have side effects. Otherwise, it must be UB.
12171     // * It can't (by assumption), be UB so we have contradicted our
12172     //   premise and can conclude the IV did not in fact self-wrap.
12173     if (!isLoopInvariant(RHS, L))
12174       return false;
12175 
12176     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12177     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12178       return false;
12179 
12180     if (!ControlsExit || !loopHasNoAbnormalExits(L))
12181       return false;
12182 
12183     return loopIsFiniteByAssumption(L);
12184   };
12185 
12186   if (!IV) {
12187     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12188       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12189       if (AR && AR->getLoop() == L && AR->isAffine()) {
12190         auto canProveNUW = [&]() {
12191           if (!isLoopInvariant(RHS, L))
12192             return false;
12193 
12194           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12195             // We need the sequence defined by AR to strictly increase in the
12196             // unsigned integer domain for the logic below to hold.
12197             return false;
12198 
12199           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12200           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12201           // If RHS <=u Limit, then there must exist a value V in the sequence
12202           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12203           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
12204           // overflow occurs.  This limit also implies that a signed comparison
12205           // (in the wide bitwidth) is equivalent to an unsigned comparison as
12206           // the high bits on both sides must be zero.
12207           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12208           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12209           Limit = Limit.zext(OuterBitWidth);
12210           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12211         };
12212         auto Flags = AR->getNoWrapFlags();
12213         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12214           Flags = setFlags(Flags, SCEV::FlagNUW);
12215 
12216         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12217         if (AR->hasNoUnsignedWrap()) {
12218           // Emulate what getZeroExtendExpr would have done during construction
12219           // if we'd been able to infer the fact just above at that time.
12220           const SCEV *Step = AR->getStepRecurrence(*this);
12221           Type *Ty = ZExt->getType();
12222           auto *S = getAddRecExpr(
12223             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12224             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12225           IV = dyn_cast<SCEVAddRecExpr>(S);
12226         }
12227       }
12228     }
12229   }
12230 
12231 
12232   if (!IV && AllowPredicates) {
12233     // Try to make this an AddRec using runtime tests, in the first X
12234     // iterations of this loop, where X is the SCEV expression found by the
12235     // algorithm below.
12236     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12237     PredicatedIV = true;
12238   }
12239 
12240   // Avoid weird loops
12241   if (!IV || IV->getLoop() != L || !IV->isAffine())
12242     return getCouldNotCompute();
12243 
12244   // A precondition of this method is that the condition being analyzed
12245   // reaches an exiting branch which dominates the latch.  Given that, we can
12246   // assume that an increment which violates the nowrap specification and
12247   // produces poison must cause undefined behavior when the resulting poison
12248   // value is branched upon and thus we can conclude that the backedge is
12249   // taken no more often than would be required to produce that poison value.
12250   // Note that a well defined loop can exit on the iteration which violates
12251   // the nowrap specification if there is another exit (either explicit or
12252   // implicit/exceptional) which causes the loop to execute before the
12253   // exiting instruction we're analyzing would trigger UB.
12254   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12255   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12256   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12257 
12258   const SCEV *Stride = IV->getStepRecurrence(*this);
12259 
12260   bool PositiveStride = isKnownPositive(Stride);
12261 
12262   // Avoid negative or zero stride values.
12263   if (!PositiveStride) {
12264     // We can compute the correct backedge taken count for loops with unknown
12265     // strides if we can prove that the loop is not an infinite loop with side
12266     // effects. Here's the loop structure we are trying to handle -
12267     //
12268     // i = start
12269     // do {
12270     //   A[i] = i;
12271     //   i += s;
12272     // } while (i < end);
12273     //
12274     // The backedge taken count for such loops is evaluated as -
12275     // (max(end, start + stride) - start - 1) /u stride
12276     //
12277     // The additional preconditions that we need to check to prove correctness
12278     // of the above formula is as follows -
12279     //
12280     // a) IV is either nuw or nsw depending upon signedness (indicated by the
12281     //    NoWrap flag).
12282     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12283     //    no side effects within the loop)
12284     // c) loop has a single static exit (with no abnormal exits)
12285     //
12286     // Precondition a) implies that if the stride is negative, this is a single
12287     // trip loop. The backedge taken count formula reduces to zero in this case.
12288     //
12289     // Precondition b) and c) combine to imply that if rhs is invariant in L,
12290     // then a zero stride means the backedge can't be taken without executing
12291     // undefined behavior.
12292     //
12293     // The positive stride case is the same as isKnownPositive(Stride) returning
12294     // true (original behavior of the function).
12295     //
12296     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12297         !loopHasNoAbnormalExits(L))
12298       return getCouldNotCompute();
12299 
12300     // This bailout is protecting the logic in computeMaxBECountForLT which
12301     // has not yet been sufficiently auditted or tested with negative strides.
12302     // We used to filter out all known-non-positive cases here, we're in the
12303     // process of being less restrictive bit by bit.
12304     if (IsSigned && isKnownNonPositive(Stride))
12305       return getCouldNotCompute();
12306 
12307     if (!isKnownNonZero(Stride)) {
12308       // If we have a step of zero, and RHS isn't invariant in L, we don't know
12309       // if it might eventually be greater than start and if so, on which
12310       // iteration.  We can't even produce a useful upper bound.
12311       if (!isLoopInvariant(RHS, L))
12312         return getCouldNotCompute();
12313 
12314       // We allow a potentially zero stride, but we need to divide by stride
12315       // below.  Since the loop can't be infinite and this check must control
12316       // the sole exit, we can infer the exit must be taken on the first
12317       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
12318       // we know the numerator in the divides below must be zero, so we can
12319       // pick an arbitrary non-zero value for the denominator (e.g. stride)
12320       // and produce the right result.
12321       // FIXME: Handle the case where Stride is poison?
12322       auto wouldZeroStrideBeUB = [&]() {
12323         // Proof by contradiction.  Suppose the stride were zero.  If we can
12324         // prove that the backedge *is* taken on the first iteration, then since
12325         // we know this condition controls the sole exit, we must have an
12326         // infinite loop.  We can't have a (well defined) infinite loop per
12327         // check just above.
12328         // Note: The (Start - Stride) term is used to get the start' term from
12329         // (start' + stride,+,stride). Remember that we only care about the
12330         // result of this expression when stride == 0 at runtime.
12331         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12332         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12333       };
12334       if (!wouldZeroStrideBeUB()) {
12335         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12336       }
12337     }
12338   } else if (!Stride->isOne() && !NoWrap) {
12339     auto isUBOnWrap = [&]() {
12340       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12341       // follows trivially from the fact that every (un)signed-wrapped, but
12342       // not self-wrapped value must be LT than the last value before
12343       // (un)signed wrap.  Since we know that last value didn't exit, nor
12344       // will any smaller one.
12345       return canAssumeNoSelfWrap(IV);
12346     };
12347 
12348     // Avoid proven overflow cases: this will ensure that the backedge taken
12349     // count will not generate any unsigned overflow. Relaxed no-overflow
12350     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12351     // undefined behaviors like the case of C language.
12352     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12353       return getCouldNotCompute();
12354   }
12355 
12356   // On all paths just preceeding, we established the following invariant:
12357   //   IV can be assumed not to overflow up to and including the exiting
12358   //   iteration.  We proved this in one of two ways:
12359   //   1) We can show overflow doesn't occur before the exiting iteration
12360   //      1a) canIVOverflowOnLT, and b) step of one
12361   //   2) We can show that if overflow occurs, the loop must execute UB
12362   //      before any possible exit.
12363   // Note that we have not yet proved RHS invariant (in general).
12364 
12365   const SCEV *Start = IV->getStart();
12366 
12367   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12368   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12369   // Use integer-typed versions for actual computation; we can't subtract
12370   // pointers in general.
12371   const SCEV *OrigStart = Start;
12372   const SCEV *OrigRHS = RHS;
12373   if (Start->getType()->isPointerTy()) {
12374     Start = getLosslessPtrToIntExpr(Start);
12375     if (isa<SCEVCouldNotCompute>(Start))
12376       return Start;
12377   }
12378   if (RHS->getType()->isPointerTy()) {
12379     RHS = getLosslessPtrToIntExpr(RHS);
12380     if (isa<SCEVCouldNotCompute>(RHS))
12381       return RHS;
12382   }
12383 
12384   // When the RHS is not invariant, we do not know the end bound of the loop and
12385   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12386   // calculate the MaxBECount, given the start, stride and max value for the end
12387   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12388   // checked above).
12389   if (!isLoopInvariant(RHS, L)) {
12390     const SCEV *MaxBECount = computeMaxBECountForLT(
12391         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12392     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12393                      false /*MaxOrZero*/, Predicates);
12394   }
12395 
12396   // We use the expression (max(End,Start)-Start)/Stride to describe the
12397   // backedge count, as if the backedge is taken at least once max(End,Start)
12398   // is End and so the result is as above, and if not max(End,Start) is Start
12399   // so we get a backedge count of zero.
12400   const SCEV *BECount = nullptr;
12401   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12402   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12403   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12404   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12405   // Can we prove (max(RHS,Start) > Start - Stride?
12406   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12407       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12408     // In this case, we can use a refined formula for computing backedge taken
12409     // count.  The general formula remains:
12410     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12411     // We want to use the alternate formula:
12412     //   "((End - 1) - (Start - Stride)) /u Stride"
12413     // Let's do a quick case analysis to show these are equivalent under
12414     // our precondition that max(RHS,Start) > Start - Stride.
12415     // * For RHS <= Start, the backedge-taken count must be zero.
12416     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12417     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12418     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12419     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12420     //     this to the stride of 1 case.
12421     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12422     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12423     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12424     //   "((RHS - (Start - Stride) - 1) /u Stride".
12425     //   Our preconditions trivially imply no overflow in that form.
12426     const SCEV *MinusOne = getMinusOne(Stride->getType());
12427     const SCEV *Numerator =
12428         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12429     BECount = getUDivExpr(Numerator, Stride);
12430   }
12431 
12432   const SCEV *BECountIfBackedgeTaken = nullptr;
12433   if (!BECount) {
12434     auto canProveRHSGreaterThanEqualStart = [&]() {
12435       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12436       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12437         return true;
12438 
12439       // (RHS > Start - 1) implies RHS >= Start.
12440       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12441       //   "Start - 1" doesn't overflow.
12442       // * For signed comparison, if Start - 1 does overflow, it's equal
12443       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12444       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12445       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12446       //
12447       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12448       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12449       auto *StartMinusOne = getAddExpr(OrigStart,
12450                                        getMinusOne(OrigStart->getType()));
12451       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12452     };
12453 
12454     // If we know that RHS >= Start in the context of loop, then we know that
12455     // max(RHS, Start) = RHS at this point.
12456     const SCEV *End;
12457     if (canProveRHSGreaterThanEqualStart()) {
12458       End = RHS;
12459     } else {
12460       // If RHS < Start, the backedge will be taken zero times.  So in
12461       // general, we can write the backedge-taken count as:
12462       //
12463       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12464       //
12465       // We convert it to the following to make it more convenient for SCEV:
12466       //
12467       //     ceil(max(RHS, Start) - Start) / Stride
12468       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12469 
12470       // See what would happen if we assume the backedge is taken. This is
12471       // used to compute MaxBECount.
12472       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12473     }
12474 
12475     // At this point, we know:
12476     //
12477     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12478     // 2. The index variable doesn't overflow.
12479     //
12480     // Therefore, we know N exists such that
12481     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12482     // doesn't overflow.
12483     //
12484     // Using this information, try to prove whether the addition in
12485     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12486     const SCEV *One = getOne(Stride->getType());
12487     bool MayAddOverflow = [&] {
12488       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12489         if (StrideC->getAPInt().isPowerOf2()) {
12490           // Suppose Stride is a power of two, and Start/End are unsigned
12491           // integers.  Let UMAX be the largest representable unsigned
12492           // integer.
12493           //
12494           // By the preconditions of this function, we know
12495           // "(Start + Stride * N) >= End", and this doesn't overflow.
12496           // As a formula:
12497           //
12498           //   End <= (Start + Stride * N) <= UMAX
12499           //
12500           // Subtracting Start from all the terms:
12501           //
12502           //   End - Start <= Stride * N <= UMAX - Start
12503           //
12504           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12505           //
12506           //   End - Start <= Stride * N <= UMAX
12507           //
12508           // Stride * N is a multiple of Stride. Therefore,
12509           //
12510           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12511           //
12512           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12513           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12514           //
12515           //   End - Start <= Stride * N <= UMAX - Stride - 1
12516           //
12517           // Dropping the middle term:
12518           //
12519           //   End - Start <= UMAX - Stride - 1
12520           //
12521           // Adding Stride - 1 to both sides:
12522           //
12523           //   (End - Start) + (Stride - 1) <= UMAX
12524           //
12525           // In other words, the addition doesn't have unsigned overflow.
12526           //
12527           // A similar proof works if we treat Start/End as signed values.
12528           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12529           // use signed max instead of unsigned max. Note that we're trying
12530           // to prove a lack of unsigned overflow in either case.
12531           return false;
12532         }
12533       }
12534       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12535         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12536         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12537         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12538         //
12539         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12540         return false;
12541       }
12542       return true;
12543     }();
12544 
12545     const SCEV *Delta = getMinusSCEV(End, Start);
12546     if (!MayAddOverflow) {
12547       // floor((D + (S - 1)) / S)
12548       // We prefer this formulation if it's legal because it's fewer operations.
12549       BECount =
12550           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
12551     } else {
12552       BECount = getUDivCeilSCEV(Delta, Stride);
12553     }
12554   }
12555 
12556   const SCEV *MaxBECount;
12557   bool MaxOrZero = false;
12558   if (isa<SCEVConstant>(BECount)) {
12559     MaxBECount = BECount;
12560   } else if (BECountIfBackedgeTaken &&
12561              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
12562     // If we know exactly how many times the backedge will be taken if it's
12563     // taken at least once, then the backedge count will either be that or
12564     // zero.
12565     MaxBECount = BECountIfBackedgeTaken;
12566     MaxOrZero = true;
12567   } else {
12568     MaxBECount = computeMaxBECountForLT(
12569         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12570   }
12571 
12572   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
12573       !isa<SCEVCouldNotCompute>(BECount))
12574     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
12575 
12576   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
12577 }
12578 
12579 ScalarEvolution::ExitLimit
12580 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
12581                                      const Loop *L, bool IsSigned,
12582                                      bool ControlsExit, bool AllowPredicates) {
12583   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12584   // We handle only IV > Invariant
12585   if (!isLoopInvariant(RHS, L))
12586     return getCouldNotCompute();
12587 
12588   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12589   if (!IV && AllowPredicates)
12590     // Try to make this an AddRec using runtime tests, in the first X
12591     // iterations of this loop, where X is the SCEV expression found by the
12592     // algorithm below.
12593     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12594 
12595   // Avoid weird loops
12596   if (!IV || IV->getLoop() != L || !IV->isAffine())
12597     return getCouldNotCompute();
12598 
12599   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12600   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12601   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12602 
12603   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
12604 
12605   // Avoid negative or zero stride values
12606   if (!isKnownPositive(Stride))
12607     return getCouldNotCompute();
12608 
12609   // Avoid proven overflow cases: this will ensure that the backedge taken count
12610   // will not generate any unsigned overflow. Relaxed no-overflow conditions
12611   // exploit NoWrapFlags, allowing to optimize in presence of undefined
12612   // behaviors like the case of C language.
12613   if (!Stride->isOne() && !NoWrap)
12614     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
12615       return getCouldNotCompute();
12616 
12617   const SCEV *Start = IV->getStart();
12618   const SCEV *End = RHS;
12619   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
12620     // If we know that Start >= RHS in the context of loop, then we know that
12621     // min(RHS, Start) = RHS at this point.
12622     if (isLoopEntryGuardedByCond(
12623             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
12624       End = RHS;
12625     else
12626       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
12627   }
12628 
12629   if (Start->getType()->isPointerTy()) {
12630     Start = getLosslessPtrToIntExpr(Start);
12631     if (isa<SCEVCouldNotCompute>(Start))
12632       return Start;
12633   }
12634   if (End->getType()->isPointerTy()) {
12635     End = getLosslessPtrToIntExpr(End);
12636     if (isa<SCEVCouldNotCompute>(End))
12637       return End;
12638   }
12639 
12640   // Compute ((Start - End) + (Stride - 1)) / Stride.
12641   // FIXME: This can overflow. Holding off on fixing this for now;
12642   // howManyGreaterThans will hopefully be gone soon.
12643   const SCEV *One = getOne(Stride->getType());
12644   const SCEV *BECount = getUDivExpr(
12645       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
12646 
12647   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
12648                             : getUnsignedRangeMax(Start);
12649 
12650   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
12651                              : getUnsignedRangeMin(Stride);
12652 
12653   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
12654   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
12655                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
12656 
12657   // Although End can be a MIN expression we estimate MinEnd considering only
12658   // the case End = RHS. This is safe because in the other case (Start - End)
12659   // is zero, leading to a zero maximum backedge taken count.
12660   APInt MinEnd =
12661     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
12662              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
12663 
12664   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
12665                                ? BECount
12666                                : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
12667                                                  getConstant(MinStride));
12668 
12669   if (isa<SCEVCouldNotCompute>(MaxBECount))
12670     MaxBECount = BECount;
12671 
12672   return ExitLimit(BECount, MaxBECount, false, Predicates);
12673 }
12674 
12675 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
12676                                                     ScalarEvolution &SE) const {
12677   if (Range.isFullSet())  // Infinite loop.
12678     return SE.getCouldNotCompute();
12679 
12680   // If the start is a non-zero constant, shift the range to simplify things.
12681   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
12682     if (!SC->getValue()->isZero()) {
12683       SmallVector<const SCEV *, 4> Operands(operands());
12684       Operands[0] = SE.getZero(SC->getType());
12685       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
12686                                              getNoWrapFlags(FlagNW));
12687       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
12688         return ShiftedAddRec->getNumIterationsInRange(
12689             Range.subtract(SC->getAPInt()), SE);
12690       // This is strange and shouldn't happen.
12691       return SE.getCouldNotCompute();
12692     }
12693 
12694   // The only time we can solve this is when we have all constant indices.
12695   // Otherwise, we cannot determine the overflow conditions.
12696   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
12697     return SE.getCouldNotCompute();
12698 
12699   // Okay at this point we know that all elements of the chrec are constants and
12700   // that the start element is zero.
12701 
12702   // First check to see if the range contains zero.  If not, the first
12703   // iteration exits.
12704   unsigned BitWidth = SE.getTypeSizeInBits(getType());
12705   if (!Range.contains(APInt(BitWidth, 0)))
12706     return SE.getZero(getType());
12707 
12708   if (isAffine()) {
12709     // If this is an affine expression then we have this situation:
12710     //   Solve {0,+,A} in Range  ===  Ax in Range
12711 
12712     // We know that zero is in the range.  If A is positive then we know that
12713     // the upper value of the range must be the first possible exit value.
12714     // If A is negative then the lower of the range is the last possible loop
12715     // value.  Also note that we already checked for a full range.
12716     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
12717     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
12718 
12719     // The exit value should be (End+A)/A.
12720     APInt ExitVal = (End + A).udiv(A);
12721     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
12722 
12723     // Evaluate at the exit value.  If we really did fall out of the valid
12724     // range, then we computed our trip count, otherwise wrap around or other
12725     // things must have happened.
12726     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
12727     if (Range.contains(Val->getValue()))
12728       return SE.getCouldNotCompute();  // Something strange happened
12729 
12730     // Ensure that the previous value is in the range.
12731     assert(Range.contains(
12732            EvaluateConstantChrecAtConstant(this,
12733            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
12734            "Linear scev computation is off in a bad way!");
12735     return SE.getConstant(ExitValue);
12736   }
12737 
12738   if (isQuadratic()) {
12739     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
12740       return SE.getConstant(S.getValue());
12741   }
12742 
12743   return SE.getCouldNotCompute();
12744 }
12745 
12746 const SCEVAddRecExpr *
12747 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
12748   assert(getNumOperands() > 1 && "AddRec with zero step?");
12749   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
12750   // but in this case we cannot guarantee that the value returned will be an
12751   // AddRec because SCEV does not have a fixed point where it stops
12752   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
12753   // may happen if we reach arithmetic depth limit while simplifying. So we
12754   // construct the returned value explicitly.
12755   SmallVector<const SCEV *, 3> Ops;
12756   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
12757   // (this + Step) is {A+B,+,B+C,+...,+,N}.
12758   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
12759     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
12760   // We know that the last operand is not a constant zero (otherwise it would
12761   // have been popped out earlier). This guarantees us that if the result has
12762   // the same last operand, then it will also not be popped out, meaning that
12763   // the returned value will be an AddRec.
12764   const SCEV *Last = getOperand(getNumOperands() - 1);
12765   assert(!Last->isZero() && "Recurrency with zero step?");
12766   Ops.push_back(Last);
12767   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
12768                                                SCEV::FlagAnyWrap));
12769 }
12770 
12771 // Return true when S contains at least an undef value.
12772 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
12773   return SCEVExprContains(S, [](const SCEV *S) {
12774     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12775       return isa<UndefValue>(SU->getValue());
12776     return false;
12777   });
12778 }
12779 
12780 // Return true when S contains a value that is a nullptr.
12781 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
12782   return SCEVExprContains(S, [](const SCEV *S) {
12783     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12784       return SU->getValue() == nullptr;
12785     return false;
12786   });
12787 }
12788 
12789 /// Return the size of an element read or written by Inst.
12790 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12791   Type *Ty;
12792   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12793     Ty = Store->getValueOperand()->getType();
12794   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12795     Ty = Load->getType();
12796   else
12797     return nullptr;
12798 
12799   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12800   return getSizeOfExpr(ETy, Ty);
12801 }
12802 
12803 //===----------------------------------------------------------------------===//
12804 //                   SCEVCallbackVH Class Implementation
12805 //===----------------------------------------------------------------------===//
12806 
12807 void ScalarEvolution::SCEVCallbackVH::deleted() {
12808   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12809   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12810     SE->ConstantEvolutionLoopExitValue.erase(PN);
12811   SE->eraseValueFromMap(getValPtr());
12812   // this now dangles!
12813 }
12814 
12815 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12816   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12817 
12818   // Forget all the expressions associated with users of the old value,
12819   // so that future queries will recompute the expressions using the new
12820   // value.
12821   Value *Old = getValPtr();
12822   SmallVector<User *, 16> Worklist(Old->users());
12823   SmallPtrSet<User *, 8> Visited;
12824   while (!Worklist.empty()) {
12825     User *U = Worklist.pop_back_val();
12826     // Deleting the Old value will cause this to dangle. Postpone
12827     // that until everything else is done.
12828     if (U == Old)
12829       continue;
12830     if (!Visited.insert(U).second)
12831       continue;
12832     if (PHINode *PN = dyn_cast<PHINode>(U))
12833       SE->ConstantEvolutionLoopExitValue.erase(PN);
12834     SE->eraseValueFromMap(U);
12835     llvm::append_range(Worklist, U->users());
12836   }
12837   // Delete the Old value.
12838   if (PHINode *PN = dyn_cast<PHINode>(Old))
12839     SE->ConstantEvolutionLoopExitValue.erase(PN);
12840   SE->eraseValueFromMap(Old);
12841   // this now dangles!
12842 }
12843 
12844 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12845   : CallbackVH(V), SE(se) {}
12846 
12847 //===----------------------------------------------------------------------===//
12848 //                   ScalarEvolution Class Implementation
12849 //===----------------------------------------------------------------------===//
12850 
12851 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12852                                  AssumptionCache &AC, DominatorTree &DT,
12853                                  LoopInfo &LI)
12854     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12855       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12856       LoopDispositions(64), BlockDispositions(64) {
12857   // To use guards for proving predicates, we need to scan every instruction in
12858   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12859   // time if the IR does not actually contain any calls to
12860   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12861   //
12862   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12863   // to _add_ guards to the module when there weren't any before, and wants
12864   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12865   // efficient in lieu of being smart in that rather obscure case.
12866 
12867   auto *GuardDecl = F.getParent()->getFunction(
12868       Intrinsic::getName(Intrinsic::experimental_guard));
12869   HasGuards = GuardDecl && !GuardDecl->use_empty();
12870 }
12871 
12872 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12873     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12874       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12875       ValueExprMap(std::move(Arg.ValueExprMap)),
12876       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12877       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12878       PendingMerges(std::move(Arg.PendingMerges)),
12879       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12880       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12881       PredicatedBackedgeTakenCounts(
12882           std::move(Arg.PredicatedBackedgeTakenCounts)),
12883       BECountUsers(std::move(Arg.BECountUsers)),
12884       ConstantEvolutionLoopExitValue(
12885           std::move(Arg.ConstantEvolutionLoopExitValue)),
12886       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12887       ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
12888       LoopDispositions(std::move(Arg.LoopDispositions)),
12889       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12890       BlockDispositions(std::move(Arg.BlockDispositions)),
12891       SCEVUsers(std::move(Arg.SCEVUsers)),
12892       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12893       SignedRanges(std::move(Arg.SignedRanges)),
12894       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12895       UniquePreds(std::move(Arg.UniquePreds)),
12896       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12897       LoopUsers(std::move(Arg.LoopUsers)),
12898       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12899       FirstUnknown(Arg.FirstUnknown) {
12900   Arg.FirstUnknown = nullptr;
12901 }
12902 
12903 ScalarEvolution::~ScalarEvolution() {
12904   // Iterate through all the SCEVUnknown instances and call their
12905   // destructors, so that they release their references to their values.
12906   for (SCEVUnknown *U = FirstUnknown; U;) {
12907     SCEVUnknown *Tmp = U;
12908     U = U->Next;
12909     Tmp->~SCEVUnknown();
12910   }
12911   FirstUnknown = nullptr;
12912 
12913   ExprValueMap.clear();
12914   ValueExprMap.clear();
12915   HasRecMap.clear();
12916   BackedgeTakenCounts.clear();
12917   PredicatedBackedgeTakenCounts.clear();
12918 
12919   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12920   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12921   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12922   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12923   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12924 }
12925 
12926 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12927   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12928 }
12929 
12930 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12931                           const Loop *L) {
12932   // Print all inner loops first
12933   for (Loop *I : *L)
12934     PrintLoopInfo(OS, SE, I);
12935 
12936   OS << "Loop ";
12937   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12938   OS << ": ";
12939 
12940   SmallVector<BasicBlock *, 8> ExitingBlocks;
12941   L->getExitingBlocks(ExitingBlocks);
12942   if (ExitingBlocks.size() != 1)
12943     OS << "<multiple exits> ";
12944 
12945   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12946     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12947   else
12948     OS << "Unpredictable backedge-taken count.\n";
12949 
12950   if (ExitingBlocks.size() > 1)
12951     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12952       OS << "  exit count for " << ExitingBlock->getName() << ": "
12953          << *SE->getExitCount(L, ExitingBlock) << "\n";
12954     }
12955 
12956   OS << "Loop ";
12957   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12958   OS << ": ";
12959 
12960   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12961     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12962     if (SE->isBackedgeTakenCountMaxOrZero(L))
12963       OS << ", actual taken count either this or zero.";
12964   } else {
12965     OS << "Unpredictable max backedge-taken count. ";
12966   }
12967 
12968   OS << "\n"
12969         "Loop ";
12970   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12971   OS << ": ";
12972 
12973   SmallVector<const SCEVPredicate *, 4> Preds;
12974   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
12975   if (!isa<SCEVCouldNotCompute>(PBT)) {
12976     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12977     OS << " Predicates:\n";
12978     for (auto *P : Preds)
12979       P->print(OS, 4);
12980   } else {
12981     OS << "Unpredictable predicated backedge-taken count. ";
12982   }
12983   OS << "\n";
12984 
12985   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12986     OS << "Loop ";
12987     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12988     OS << ": ";
12989     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12990   }
12991 }
12992 
12993 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12994   switch (LD) {
12995   case ScalarEvolution::LoopVariant:
12996     return "Variant";
12997   case ScalarEvolution::LoopInvariant:
12998     return "Invariant";
12999   case ScalarEvolution::LoopComputable:
13000     return "Computable";
13001   }
13002   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
13003 }
13004 
13005 void ScalarEvolution::print(raw_ostream &OS) const {
13006   // ScalarEvolution's implementation of the print method is to print
13007   // out SCEV values of all instructions that are interesting. Doing
13008   // this potentially causes it to create new SCEV objects though,
13009   // which technically conflicts with the const qualifier. This isn't
13010   // observable from outside the class though, so casting away the
13011   // const isn't dangerous.
13012   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13013 
13014   if (ClassifyExpressions) {
13015     OS << "Classifying expressions for: ";
13016     F.printAsOperand(OS, /*PrintType=*/false);
13017     OS << "\n";
13018     for (Instruction &I : instructions(F))
13019       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13020         OS << I << '\n';
13021         OS << "  -->  ";
13022         const SCEV *SV = SE.getSCEV(&I);
13023         SV->print(OS);
13024         if (!isa<SCEVCouldNotCompute>(SV)) {
13025           OS << " U: ";
13026           SE.getUnsignedRange(SV).print(OS);
13027           OS << " S: ";
13028           SE.getSignedRange(SV).print(OS);
13029         }
13030 
13031         const Loop *L = LI.getLoopFor(I.getParent());
13032 
13033         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13034         if (AtUse != SV) {
13035           OS << "  -->  ";
13036           AtUse->print(OS);
13037           if (!isa<SCEVCouldNotCompute>(AtUse)) {
13038             OS << " U: ";
13039             SE.getUnsignedRange(AtUse).print(OS);
13040             OS << " S: ";
13041             SE.getSignedRange(AtUse).print(OS);
13042           }
13043         }
13044 
13045         if (L) {
13046           OS << "\t\t" "Exits: ";
13047           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13048           if (!SE.isLoopInvariant(ExitValue, L)) {
13049             OS << "<<Unknown>>";
13050           } else {
13051             OS << *ExitValue;
13052           }
13053 
13054           bool First = true;
13055           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13056             if (First) {
13057               OS << "\t\t" "LoopDispositions: { ";
13058               First = false;
13059             } else {
13060               OS << ", ";
13061             }
13062 
13063             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13064             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
13065           }
13066 
13067           for (auto *InnerL : depth_first(L)) {
13068             if (InnerL == L)
13069               continue;
13070             if (First) {
13071               OS << "\t\t" "LoopDispositions: { ";
13072               First = false;
13073             } else {
13074               OS << ", ";
13075             }
13076 
13077             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13078             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
13079           }
13080 
13081           OS << " }";
13082         }
13083 
13084         OS << "\n";
13085       }
13086   }
13087 
13088   OS << "Determining loop execution counts for: ";
13089   F.printAsOperand(OS, /*PrintType=*/false);
13090   OS << "\n";
13091   for (Loop *I : LI)
13092     PrintLoopInfo(OS, &SE, I);
13093 }
13094 
13095 ScalarEvolution::LoopDisposition
13096 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13097   auto &Values = LoopDispositions[S];
13098   for (auto &V : Values) {
13099     if (V.getPointer() == L)
13100       return V.getInt();
13101   }
13102   Values.emplace_back(L, LoopVariant);
13103   LoopDisposition D = computeLoopDisposition(S, L);
13104   auto &Values2 = LoopDispositions[S];
13105   for (auto &V : llvm::reverse(Values2)) {
13106     if (V.getPointer() == L) {
13107       V.setInt(D);
13108       break;
13109     }
13110   }
13111   return D;
13112 }
13113 
13114 ScalarEvolution::LoopDisposition
13115 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13116   switch (S->getSCEVType()) {
13117   case scConstant:
13118     return LoopInvariant;
13119   case scPtrToInt:
13120   case scTruncate:
13121   case scZeroExtend:
13122   case scSignExtend:
13123     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
13124   case scAddRecExpr: {
13125     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13126 
13127     // If L is the addrec's loop, it's computable.
13128     if (AR->getLoop() == L)
13129       return LoopComputable;
13130 
13131     // Add recurrences are never invariant in the function-body (null loop).
13132     if (!L)
13133       return LoopVariant;
13134 
13135     // Everything that is not defined at loop entry is variant.
13136     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13137       return LoopVariant;
13138     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13139            " dominate the contained loop's header?");
13140 
13141     // This recurrence is invariant w.r.t. L if AR's loop contains L.
13142     if (AR->getLoop()->contains(L))
13143       return LoopInvariant;
13144 
13145     // This recurrence is variant w.r.t. L if any of its operands
13146     // are variant.
13147     for (auto *Op : AR->operands())
13148       if (!isLoopInvariant(Op, L))
13149         return LoopVariant;
13150 
13151     // Otherwise it's loop-invariant.
13152     return LoopInvariant;
13153   }
13154   case scAddExpr:
13155   case scMulExpr:
13156   case scUMaxExpr:
13157   case scSMaxExpr:
13158   case scUMinExpr:
13159   case scSMinExpr:
13160   case scSequentialUMinExpr: {
13161     bool HasVarying = false;
13162     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
13163       LoopDisposition D = getLoopDisposition(Op, L);
13164       if (D == LoopVariant)
13165         return LoopVariant;
13166       if (D == LoopComputable)
13167         HasVarying = true;
13168     }
13169     return HasVarying ? LoopComputable : LoopInvariant;
13170   }
13171   case scUDivExpr: {
13172     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13173     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
13174     if (LD == LoopVariant)
13175       return LoopVariant;
13176     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
13177     if (RD == LoopVariant)
13178       return LoopVariant;
13179     return (LD == LoopInvariant && RD == LoopInvariant) ?
13180            LoopInvariant : LoopComputable;
13181   }
13182   case scUnknown:
13183     // All non-instruction values are loop invariant.  All instructions are loop
13184     // invariant if they are not contained in the specified loop.
13185     // Instructions are never considered invariant in the function body
13186     // (null loop) because they are defined within the "loop".
13187     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13188       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13189     return LoopInvariant;
13190   case scCouldNotCompute:
13191     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13192   }
13193   llvm_unreachable("Unknown SCEV kind!");
13194 }
13195 
13196 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13197   return getLoopDisposition(S, L) == LoopInvariant;
13198 }
13199 
13200 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13201   return getLoopDisposition(S, L) == LoopComputable;
13202 }
13203 
13204 ScalarEvolution::BlockDisposition
13205 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13206   auto &Values = BlockDispositions[S];
13207   for (auto &V : Values) {
13208     if (V.getPointer() == BB)
13209       return V.getInt();
13210   }
13211   Values.emplace_back(BB, DoesNotDominateBlock);
13212   BlockDisposition D = computeBlockDisposition(S, BB);
13213   auto &Values2 = BlockDispositions[S];
13214   for (auto &V : llvm::reverse(Values2)) {
13215     if (V.getPointer() == BB) {
13216       V.setInt(D);
13217       break;
13218     }
13219   }
13220   return D;
13221 }
13222 
13223 ScalarEvolution::BlockDisposition
13224 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13225   switch (S->getSCEVType()) {
13226   case scConstant:
13227     return ProperlyDominatesBlock;
13228   case scPtrToInt:
13229   case scTruncate:
13230   case scZeroExtend:
13231   case scSignExtend:
13232     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
13233   case scAddRecExpr: {
13234     // This uses a "dominates" query instead of "properly dominates" query
13235     // to test for proper dominance too, because the instruction which
13236     // produces the addrec's value is a PHI, and a PHI effectively properly
13237     // dominates its entire containing block.
13238     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13239     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13240       return DoesNotDominateBlock;
13241 
13242     // Fall through into SCEVNAryExpr handling.
13243     LLVM_FALLTHROUGH;
13244   }
13245   case scAddExpr:
13246   case scMulExpr:
13247   case scUMaxExpr:
13248   case scSMaxExpr:
13249   case scUMinExpr:
13250   case scSMinExpr:
13251   case scSequentialUMinExpr: {
13252     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
13253     bool Proper = true;
13254     for (const SCEV *NAryOp : NAry->operands()) {
13255       BlockDisposition D = getBlockDisposition(NAryOp, BB);
13256       if (D == DoesNotDominateBlock)
13257         return DoesNotDominateBlock;
13258       if (D == DominatesBlock)
13259         Proper = false;
13260     }
13261     return Proper ? ProperlyDominatesBlock : DominatesBlock;
13262   }
13263   case scUDivExpr: {
13264     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13265     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
13266     BlockDisposition LD = getBlockDisposition(LHS, BB);
13267     if (LD == DoesNotDominateBlock)
13268       return DoesNotDominateBlock;
13269     BlockDisposition RD = getBlockDisposition(RHS, BB);
13270     if (RD == DoesNotDominateBlock)
13271       return DoesNotDominateBlock;
13272     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
13273       ProperlyDominatesBlock : DominatesBlock;
13274   }
13275   case scUnknown:
13276     if (Instruction *I =
13277           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13278       if (I->getParent() == BB)
13279         return DominatesBlock;
13280       if (DT.properlyDominates(I->getParent(), BB))
13281         return ProperlyDominatesBlock;
13282       return DoesNotDominateBlock;
13283     }
13284     return ProperlyDominatesBlock;
13285   case scCouldNotCompute:
13286     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13287   }
13288   llvm_unreachable("Unknown SCEV kind!");
13289 }
13290 
13291 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13292   return getBlockDisposition(S, BB) >= DominatesBlock;
13293 }
13294 
13295 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13296   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13297 }
13298 
13299 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13300   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13301 }
13302 
13303 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13304                                                 bool Predicated) {
13305   auto &BECounts =
13306       Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13307   auto It = BECounts.find(L);
13308   if (It != BECounts.end()) {
13309     for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13310       if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13311         auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13312         assert(UserIt != BECountUsers.end());
13313         UserIt->second.erase({L, Predicated});
13314       }
13315     }
13316     BECounts.erase(It);
13317   }
13318 }
13319 
13320 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13321   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13322   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13323 
13324   while (!Worklist.empty()) {
13325     const SCEV *Curr = Worklist.pop_back_val();
13326     auto Users = SCEVUsers.find(Curr);
13327     if (Users != SCEVUsers.end())
13328       for (auto *User : Users->second)
13329         if (ToForget.insert(User).second)
13330           Worklist.push_back(User);
13331   }
13332 
13333   for (auto *S : ToForget)
13334     forgetMemoizedResultsImpl(S);
13335 
13336   for (auto I = PredicatedSCEVRewrites.begin();
13337        I != PredicatedSCEVRewrites.end();) {
13338     std::pair<const SCEV *, const Loop *> Entry = I->first;
13339     if (ToForget.count(Entry.first))
13340       PredicatedSCEVRewrites.erase(I++);
13341     else
13342       ++I;
13343   }
13344 }
13345 
13346 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13347   LoopDispositions.erase(S);
13348   BlockDispositions.erase(S);
13349   UnsignedRanges.erase(S);
13350   SignedRanges.erase(S);
13351   HasRecMap.erase(S);
13352   MinTrailingZerosCache.erase(S);
13353 
13354   auto ExprIt = ExprValueMap.find(S);
13355   if (ExprIt != ExprValueMap.end()) {
13356     for (Value *V : ExprIt->second) {
13357       auto ValueIt = ValueExprMap.find_as(V);
13358       if (ValueIt != ValueExprMap.end())
13359         ValueExprMap.erase(ValueIt);
13360     }
13361     ExprValueMap.erase(ExprIt);
13362   }
13363 
13364   auto ScopeIt = ValuesAtScopes.find(S);
13365   if (ScopeIt != ValuesAtScopes.end()) {
13366     for (const auto &Pair : ScopeIt->second)
13367       if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13368         erase_value(ValuesAtScopesUsers[Pair.second],
13369                     std::make_pair(Pair.first, S));
13370     ValuesAtScopes.erase(ScopeIt);
13371   }
13372 
13373   auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13374   if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13375     for (const auto &Pair : ScopeUserIt->second)
13376       erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13377     ValuesAtScopesUsers.erase(ScopeUserIt);
13378   }
13379 
13380   auto BEUsersIt = BECountUsers.find(S);
13381   if (BEUsersIt != BECountUsers.end()) {
13382     // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13383     auto Copy = BEUsersIt->second;
13384     for (const auto &Pair : Copy)
13385       forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13386     BECountUsers.erase(BEUsersIt);
13387   }
13388 }
13389 
13390 void
13391 ScalarEvolution::getUsedLoops(const SCEV *S,
13392                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13393   struct FindUsedLoops {
13394     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13395         : LoopsUsed(LoopsUsed) {}
13396     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13397     bool follow(const SCEV *S) {
13398       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13399         LoopsUsed.insert(AR->getLoop());
13400       return true;
13401     }
13402 
13403     bool isDone() const { return false; }
13404   };
13405 
13406   FindUsedLoops F(LoopsUsed);
13407   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13408 }
13409 
13410 void ScalarEvolution::getReachableBlocks(
13411     SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13412   SmallVector<BasicBlock *> Worklist;
13413   Worklist.push_back(&F.getEntryBlock());
13414   while (!Worklist.empty()) {
13415     BasicBlock *BB = Worklist.pop_back_val();
13416     if (!Reachable.insert(BB).second)
13417       continue;
13418 
13419     Value *Cond;
13420     BasicBlock *TrueBB, *FalseBB;
13421     if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
13422                                         m_BasicBlock(FalseBB)))) {
13423       if (auto *C = dyn_cast<ConstantInt>(Cond)) {
13424         Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
13425         continue;
13426       }
13427 
13428       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13429         const SCEV *L = getSCEV(Cmp->getOperand(0));
13430         const SCEV *R = getSCEV(Cmp->getOperand(1));
13431         if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
13432           Worklist.push_back(TrueBB);
13433           continue;
13434         }
13435         if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
13436                                               R)) {
13437           Worklist.push_back(FalseBB);
13438           continue;
13439         }
13440       }
13441     }
13442 
13443     append_range(Worklist, successors(BB));
13444   }
13445 }
13446 
13447 void ScalarEvolution::verify() const {
13448   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13449   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13450 
13451   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13452 
13453   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13454   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13455     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13456 
13457     const SCEV *visitConstant(const SCEVConstant *Constant) {
13458       return SE.getConstant(Constant->getAPInt());
13459     }
13460 
13461     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13462       return SE.getUnknown(Expr->getValue());
13463     }
13464 
13465     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13466       return SE.getCouldNotCompute();
13467     }
13468   };
13469 
13470   SCEVMapper SCM(SE2);
13471   SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13472   SE2.getReachableBlocks(ReachableBlocks, F);
13473 
13474   auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
13475     if (containsUndefs(Old) || containsUndefs(New)) {
13476       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13477       // not propagate undef aggressively).  This means we can (and do) fail
13478       // verification in cases where a transform makes a value go from "undef"
13479       // to "undef+1" (say).  The transform is fine, since in both cases the
13480       // result is "undef", but SCEV thinks the value increased by 1.
13481       return nullptr;
13482     }
13483 
13484     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13485     const SCEV *Delta = SE2.getMinusSCEV(Old, New);
13486     if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
13487       return nullptr;
13488 
13489     return Delta;
13490   };
13491 
13492   while (!LoopStack.empty()) {
13493     auto *L = LoopStack.pop_back_val();
13494     llvm::append_range(LoopStack, *L);
13495 
13496     // Only verify BECounts in reachable loops. For an unreachable loop,
13497     // any BECount is legal.
13498     if (!ReachableBlocks.contains(L->getHeader()))
13499       continue;
13500 
13501     // Only verify cached BECounts. Computing new BECounts may change the
13502     // results of subsequent SCEV uses.
13503     auto It = BackedgeTakenCounts.find(L);
13504     if (It == BackedgeTakenCounts.end())
13505       continue;
13506 
13507     auto *CurBECount =
13508         SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
13509     auto *NewBECount = SE2.getBackedgeTakenCount(L);
13510 
13511     if (CurBECount == SE2.getCouldNotCompute() ||
13512         NewBECount == SE2.getCouldNotCompute()) {
13513       // NB! This situation is legal, but is very suspicious -- whatever pass
13514       // change the loop to make a trip count go from could not compute to
13515       // computable or vice-versa *should have* invalidated SCEV.  However, we
13516       // choose not to assert here (for now) since we don't want false
13517       // positives.
13518       continue;
13519     }
13520 
13521     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13522         SE.getTypeSizeInBits(NewBECount->getType()))
13523       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13524     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13525              SE.getTypeSizeInBits(NewBECount->getType()))
13526       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13527 
13528     const SCEV *Delta = GetDelta(CurBECount, NewBECount);
13529     if (Delta && !Delta->isZero()) {
13530       dbgs() << "Trip Count for " << *L << " Changed!\n";
13531       dbgs() << "Old: " << *CurBECount << "\n";
13532       dbgs() << "New: " << *NewBECount << "\n";
13533       dbgs() << "Delta: " << *Delta << "\n";
13534       std::abort();
13535     }
13536   }
13537 
13538   // Collect all valid loops currently in LoopInfo.
13539   SmallPtrSet<Loop *, 32> ValidLoops;
13540   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13541   while (!Worklist.empty()) {
13542     Loop *L = Worklist.pop_back_val();
13543     if (ValidLoops.insert(L).second)
13544       Worklist.append(L->begin(), L->end());
13545   }
13546   for (auto &KV : ValueExprMap) {
13547 #ifndef NDEBUG
13548     // Check for SCEV expressions referencing invalid/deleted loops.
13549     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
13550       assert(ValidLoops.contains(AR->getLoop()) &&
13551              "AddRec references invalid loop");
13552     }
13553 #endif
13554 
13555     // Check that the value is also part of the reverse map.
13556     auto It = ExprValueMap.find(KV.second);
13557     if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
13558       dbgs() << "Value " << *KV.first
13559              << " is in ValueExprMap but not in ExprValueMap\n";
13560       std::abort();
13561     }
13562 
13563     if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
13564       if (!ReachableBlocks.contains(I->getParent()))
13565         continue;
13566       const SCEV *OldSCEV = SCM.visit(KV.second);
13567       const SCEV *NewSCEV = SE2.getSCEV(I);
13568       const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
13569       if (Delta && !Delta->isZero()) {
13570         dbgs() << "SCEV for value " << *I << " changed!\n"
13571                << "Old: " << *OldSCEV << "\n"
13572                << "New: " << *NewSCEV << "\n"
13573                << "Delta: " << *Delta << "\n";
13574         std::abort();
13575       }
13576     }
13577   }
13578 
13579   for (const auto &KV : ExprValueMap) {
13580     for (Value *V : KV.second) {
13581       auto It = ValueExprMap.find_as(V);
13582       if (It == ValueExprMap.end()) {
13583         dbgs() << "Value " << *V
13584                << " is in ExprValueMap but not in ValueExprMap\n";
13585         std::abort();
13586       }
13587       if (It->second != KV.first) {
13588         dbgs() << "Value " << *V << " mapped to " << *It->second
13589                << " rather than " << *KV.first << "\n";
13590         std::abort();
13591       }
13592     }
13593   }
13594 
13595   // Verify integrity of SCEV users.
13596   for (const auto &S : UniqueSCEVs) {
13597     SmallVector<const SCEV *, 4> Ops;
13598     collectUniqueOps(&S, Ops);
13599     for (const auto *Op : Ops) {
13600       // We do not store dependencies of constants.
13601       if (isa<SCEVConstant>(Op))
13602         continue;
13603       auto It = SCEVUsers.find(Op);
13604       if (It != SCEVUsers.end() && It->second.count(&S))
13605         continue;
13606       dbgs() << "Use of operand  " << *Op << " by user " << S
13607              << " is not being tracked!\n";
13608       std::abort();
13609     }
13610   }
13611 
13612   // Verify integrity of ValuesAtScopes users.
13613   for (const auto &ValueAndVec : ValuesAtScopes) {
13614     const SCEV *Value = ValueAndVec.first;
13615     for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
13616       const Loop *L = LoopAndValueAtScope.first;
13617       const SCEV *ValueAtScope = LoopAndValueAtScope.second;
13618       if (!isa<SCEVConstant>(ValueAtScope)) {
13619         auto It = ValuesAtScopesUsers.find(ValueAtScope);
13620         if (It != ValuesAtScopesUsers.end() &&
13621             is_contained(It->second, std::make_pair(L, Value)))
13622           continue;
13623         dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13624                << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
13625         std::abort();
13626       }
13627     }
13628   }
13629 
13630   for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
13631     const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
13632     for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
13633       const Loop *L = LoopAndValue.first;
13634       const SCEV *Value = LoopAndValue.second;
13635       assert(!isa<SCEVConstant>(Value));
13636       auto It = ValuesAtScopes.find(Value);
13637       if (It != ValuesAtScopes.end() &&
13638           is_contained(It->second, std::make_pair(L, ValueAtScope)))
13639         continue;
13640       dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13641              << *ValueAtScope << " missing in ValuesAtScopes\n";
13642       std::abort();
13643     }
13644   }
13645 
13646   // Verify integrity of BECountUsers.
13647   auto VerifyBECountUsers = [&](bool Predicated) {
13648     auto &BECounts =
13649         Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13650     for (const auto &LoopAndBEInfo : BECounts) {
13651       for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
13652         if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13653           auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13654           if (UserIt != BECountUsers.end() &&
13655               UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
13656             continue;
13657           dbgs() << "Value " << *ENT.ExactNotTaken << " for loop "
13658                  << *LoopAndBEInfo.first << " missing from BECountUsers\n";
13659           std::abort();
13660         }
13661       }
13662     }
13663   };
13664   VerifyBECountUsers(/* Predicated */ false);
13665   VerifyBECountUsers(/* Predicated */ true);
13666 }
13667 
13668 bool ScalarEvolution::invalidate(
13669     Function &F, const PreservedAnalyses &PA,
13670     FunctionAnalysisManager::Invalidator &Inv) {
13671   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13672   // of its dependencies is invalidated.
13673   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13674   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13675          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13676          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13677          Inv.invalidate<LoopAnalysis>(F, PA);
13678 }
13679 
13680 AnalysisKey ScalarEvolutionAnalysis::Key;
13681 
13682 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13683                                              FunctionAnalysisManager &AM) {
13684   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13685                          AM.getResult<AssumptionAnalysis>(F),
13686                          AM.getResult<DominatorTreeAnalysis>(F),
13687                          AM.getResult<LoopAnalysis>(F));
13688 }
13689 
13690 PreservedAnalyses
13691 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13692   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13693   return PreservedAnalyses::all();
13694 }
13695 
13696 PreservedAnalyses
13697 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13698   // For compatibility with opt's -analyze feature under legacy pass manager
13699   // which was not ported to NPM. This keeps tests using
13700   // update_analyze_test_checks.py working.
13701   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13702      << F.getName() << "':\n";
13703   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13704   return PreservedAnalyses::all();
13705 }
13706 
13707 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13708                       "Scalar Evolution Analysis", false, true)
13709 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13710 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13711 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13712 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13713 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13714                     "Scalar Evolution Analysis", false, true)
13715 
13716 char ScalarEvolutionWrapperPass::ID = 0;
13717 
13718 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13719   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13720 }
13721 
13722 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13723   SE.reset(new ScalarEvolution(
13724       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13725       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13726       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13727       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13728   return false;
13729 }
13730 
13731 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13732 
13733 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13734   SE->print(OS);
13735 }
13736 
13737 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13738   if (!VerifySCEV)
13739     return;
13740 
13741   SE->verify();
13742 }
13743 
13744 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13745   AU.setPreservesAll();
13746   AU.addRequiredTransitive<AssumptionCacheTracker>();
13747   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13748   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13749   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13750 }
13751 
13752 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13753                                                         const SCEV *RHS) {
13754   return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
13755 }
13756 
13757 const SCEVPredicate *
13758 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
13759                                      const SCEV *LHS, const SCEV *RHS) {
13760   FoldingSetNodeID ID;
13761   assert(LHS->getType() == RHS->getType() &&
13762          "Type mismatch between LHS and RHS");
13763   // Unique this node based on the arguments
13764   ID.AddInteger(SCEVPredicate::P_Compare);
13765   ID.AddInteger(Pred);
13766   ID.AddPointer(LHS);
13767   ID.AddPointer(RHS);
13768   void *IP = nullptr;
13769   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13770     return S;
13771   SCEVComparePredicate *Eq = new (SCEVAllocator)
13772     SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
13773   UniquePreds.InsertNode(Eq, IP);
13774   return Eq;
13775 }
13776 
13777 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13778     const SCEVAddRecExpr *AR,
13779     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13780   FoldingSetNodeID ID;
13781   // Unique this node based on the arguments
13782   ID.AddInteger(SCEVPredicate::P_Wrap);
13783   ID.AddPointer(AR);
13784   ID.AddInteger(AddedFlags);
13785   void *IP = nullptr;
13786   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13787     return S;
13788   auto *OF = new (SCEVAllocator)
13789       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13790   UniquePreds.InsertNode(OF, IP);
13791   return OF;
13792 }
13793 
13794 namespace {
13795 
13796 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13797 public:
13798 
13799   /// Rewrites \p S in the context of a loop L and the SCEV predication
13800   /// infrastructure.
13801   ///
13802   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13803   /// equivalences present in \p Pred.
13804   ///
13805   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13806   /// \p NewPreds such that the result will be an AddRecExpr.
13807   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13808                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13809                              const SCEVPredicate *Pred) {
13810     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13811     return Rewriter.visit(S);
13812   }
13813 
13814   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13815     if (Pred) {
13816       if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
13817         for (auto *Pred : U->getPredicates())
13818           if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
13819             if (IPred->getLHS() == Expr &&
13820                 IPred->getPredicate() == ICmpInst::ICMP_EQ)
13821               return IPred->getRHS();
13822       } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
13823         if (IPred->getLHS() == Expr &&
13824             IPred->getPredicate() == ICmpInst::ICMP_EQ)
13825           return IPred->getRHS();
13826       }
13827     }
13828     return convertToAddRecWithPreds(Expr);
13829   }
13830 
13831   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13832     const SCEV *Operand = visit(Expr->getOperand());
13833     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13834     if (AR && AR->getLoop() == L && AR->isAffine()) {
13835       // This couldn't be folded because the operand didn't have the nuw
13836       // flag. Add the nusw flag as an assumption that we could make.
13837       const SCEV *Step = AR->getStepRecurrence(SE);
13838       Type *Ty = Expr->getType();
13839       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13840         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13841                                 SE.getSignExtendExpr(Step, Ty), L,
13842                                 AR->getNoWrapFlags());
13843     }
13844     return SE.getZeroExtendExpr(Operand, Expr->getType());
13845   }
13846 
13847   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13848     const SCEV *Operand = visit(Expr->getOperand());
13849     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13850     if (AR && AR->getLoop() == L && AR->isAffine()) {
13851       // This couldn't be folded because the operand didn't have the nsw
13852       // flag. Add the nssw flag as an assumption that we could make.
13853       const SCEV *Step = AR->getStepRecurrence(SE);
13854       Type *Ty = Expr->getType();
13855       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13856         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13857                                 SE.getSignExtendExpr(Step, Ty), L,
13858                                 AR->getNoWrapFlags());
13859     }
13860     return SE.getSignExtendExpr(Operand, Expr->getType());
13861   }
13862 
13863 private:
13864   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13865                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13866                         const SCEVPredicate *Pred)
13867       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13868 
13869   bool addOverflowAssumption(const SCEVPredicate *P) {
13870     if (!NewPreds) {
13871       // Check if we've already made this assumption.
13872       return Pred && Pred->implies(P);
13873     }
13874     NewPreds->insert(P);
13875     return true;
13876   }
13877 
13878   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13879                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13880     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13881     return addOverflowAssumption(A);
13882   }
13883 
13884   // If \p Expr represents a PHINode, we try to see if it can be represented
13885   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13886   // to add this predicate as a runtime overflow check, we return the AddRec.
13887   // If \p Expr does not meet these conditions (is not a PHI node, or we
13888   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13889   // return \p Expr.
13890   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13891     if (!isa<PHINode>(Expr->getValue()))
13892       return Expr;
13893     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13894     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13895     if (!PredicatedRewrite)
13896       return Expr;
13897     for (auto *P : PredicatedRewrite->second){
13898       // Wrap predicates from outer loops are not supported.
13899       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13900         if (L != WP->getExpr()->getLoop())
13901           return Expr;
13902       }
13903       if (!addOverflowAssumption(P))
13904         return Expr;
13905     }
13906     return PredicatedRewrite->first;
13907   }
13908 
13909   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13910   const SCEVPredicate *Pred;
13911   const Loop *L;
13912 };
13913 
13914 } // end anonymous namespace
13915 
13916 const SCEV *
13917 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13918                                        const SCEVPredicate &Preds) {
13919   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13920 }
13921 
13922 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13923     const SCEV *S, const Loop *L,
13924     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13925   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13926   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13927   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13928 
13929   if (!AddRec)
13930     return nullptr;
13931 
13932   // Since the transformation was successful, we can now transfer the SCEV
13933   // predicates.
13934   for (auto *P : TransformPreds)
13935     Preds.insert(P);
13936 
13937   return AddRec;
13938 }
13939 
13940 /// SCEV predicates
13941 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13942                              SCEVPredicateKind Kind)
13943     : FastID(ID), Kind(Kind) {}
13944 
13945 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
13946                                    const ICmpInst::Predicate Pred,
13947                                    const SCEV *LHS, const SCEV *RHS)
13948   : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
13949   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13950   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13951 }
13952 
13953 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
13954   const auto *Op = dyn_cast<SCEVComparePredicate>(N);
13955 
13956   if (!Op)
13957     return false;
13958 
13959   if (Pred != ICmpInst::ICMP_EQ)
13960     return false;
13961 
13962   return Op->LHS == LHS && Op->RHS == RHS;
13963 }
13964 
13965 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
13966 
13967 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
13968   if (Pred == ICmpInst::ICMP_EQ)
13969     OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13970   else
13971     OS.indent(Depth) << "Compare predicate: " << *LHS
13972                      << " " << CmpInst::getPredicateName(Pred) << ") "
13973                      << *RHS << "\n";
13974 
13975 }
13976 
13977 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13978                                      const SCEVAddRecExpr *AR,
13979                                      IncrementWrapFlags Flags)
13980     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13981 
13982 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
13983 
13984 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13985   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13986 
13987   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13988 }
13989 
13990 bool SCEVWrapPredicate::isAlwaysTrue() const {
13991   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13992   IncrementWrapFlags IFlags = Flags;
13993 
13994   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13995     IFlags = clearFlags(IFlags, IncrementNSSW);
13996 
13997   return IFlags == IncrementAnyWrap;
13998 }
13999 
14000 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14001   OS.indent(Depth) << *getExpr() << " Added Flags: ";
14002   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14003     OS << "<nusw>";
14004   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14005     OS << "<nssw>";
14006   OS << "\n";
14007 }
14008 
14009 SCEVWrapPredicate::IncrementWrapFlags
14010 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14011                                    ScalarEvolution &SE) {
14012   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14013   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14014 
14015   // We can safely transfer the NSW flag as NSSW.
14016   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14017     ImpliedFlags = IncrementNSSW;
14018 
14019   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14020     // If the increment is positive, the SCEV NUW flag will also imply the
14021     // WrapPredicate NUSW flag.
14022     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14023       if (Step->getValue()->getValue().isNonNegative())
14024         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14025   }
14026 
14027   return ImpliedFlags;
14028 }
14029 
14030 /// Union predicates don't get cached so create a dummy set ID for it.
14031 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14032   : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14033   for (auto *P : Preds)
14034     add(P);
14035 }
14036 
14037 bool SCEVUnionPredicate::isAlwaysTrue() const {
14038   return all_of(Preds,
14039                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14040 }
14041 
14042 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14043   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14044     return all_of(Set->Preds,
14045                   [this](const SCEVPredicate *I) { return this->implies(I); });
14046 
14047   return any_of(Preds,
14048                 [N](const SCEVPredicate *I) { return I->implies(N); });
14049 }
14050 
14051 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14052   for (auto Pred : Preds)
14053     Pred->print(OS, Depth);
14054 }
14055 
14056 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14057   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14058     for (auto Pred : Set->Preds)
14059       add(Pred);
14060     return;
14061   }
14062 
14063   Preds.push_back(N);
14064 }
14065 
14066 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14067                                                      Loop &L)
14068     : SE(SE), L(L) {
14069   SmallVector<const SCEVPredicate*, 4> Empty;
14070   Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14071 }
14072 
14073 void ScalarEvolution::registerUser(const SCEV *User,
14074                                    ArrayRef<const SCEV *> Ops) {
14075   for (auto *Op : Ops)
14076     // We do not expect that forgetting cached data for SCEVConstants will ever
14077     // open any prospects for sharpening or introduce any correctness issues,
14078     // so we don't bother storing their dependencies.
14079     if (!isa<SCEVConstant>(Op))
14080       SCEVUsers[Op].insert(User);
14081 }
14082 
14083 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14084   const SCEV *Expr = SE.getSCEV(V);
14085   RewriteEntry &Entry = RewriteMap[Expr];
14086 
14087   // If we already have an entry and the version matches, return it.
14088   if (Entry.second && Generation == Entry.first)
14089     return Entry.second;
14090 
14091   // We found an entry but it's stale. Rewrite the stale entry
14092   // according to the current predicate.
14093   if (Entry.second)
14094     Expr = Entry.second;
14095 
14096   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14097   Entry = {Generation, NewSCEV};
14098 
14099   return NewSCEV;
14100 }
14101 
14102 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14103   if (!BackedgeCount) {
14104     SmallVector<const SCEVPredicate *, 4> Preds;
14105     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14106     for (auto *P : Preds)
14107       addPredicate(*P);
14108   }
14109   return BackedgeCount;
14110 }
14111 
14112 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14113   if (Preds->implies(&Pred))
14114     return;
14115 
14116   auto &OldPreds = Preds->getPredicates();
14117   SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14118   NewPreds.push_back(&Pred);
14119   Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14120   updateGeneration();
14121 }
14122 
14123 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14124   return *Preds;
14125 }
14126 
14127 void PredicatedScalarEvolution::updateGeneration() {
14128   // If the generation number wrapped recompute everything.
14129   if (++Generation == 0) {
14130     for (auto &II : RewriteMap) {
14131       const SCEV *Rewritten = II.second.second;
14132       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14133     }
14134   }
14135 }
14136 
14137 void PredicatedScalarEvolution::setNoOverflow(
14138     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14139   const SCEV *Expr = getSCEV(V);
14140   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14141 
14142   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14143 
14144   // Clear the statically implied flags.
14145   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14146   addPredicate(*SE.getWrapPredicate(AR, Flags));
14147 
14148   auto II = FlagsMap.insert({V, Flags});
14149   if (!II.second)
14150     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14151 }
14152 
14153 bool PredicatedScalarEvolution::hasNoOverflow(
14154     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14155   const SCEV *Expr = getSCEV(V);
14156   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14157 
14158   Flags = SCEVWrapPredicate::clearFlags(
14159       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14160 
14161   auto II = FlagsMap.find(V);
14162 
14163   if (II != FlagsMap.end())
14164     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14165 
14166   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14167 }
14168 
14169 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14170   const SCEV *Expr = this->getSCEV(V);
14171   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14172   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14173 
14174   if (!New)
14175     return nullptr;
14176 
14177   for (auto *P : NewPreds)
14178     addPredicate(*P);
14179 
14180   RewriteMap[SE.getSCEV(V)] = {Generation, New};
14181   return New;
14182 }
14183 
14184 PredicatedScalarEvolution::PredicatedScalarEvolution(
14185     const PredicatedScalarEvolution &Init)
14186   : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14187     Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14188     Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14189   for (auto I : Init.FlagsMap)
14190     FlagsMap.insert(I);
14191 }
14192 
14193 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14194   // For each block.
14195   for (auto *BB : L.getBlocks())
14196     for (auto &I : *BB) {
14197       if (!SE.isSCEVable(I.getType()))
14198         continue;
14199 
14200       auto *Expr = SE.getSCEV(&I);
14201       auto II = RewriteMap.find(Expr);
14202 
14203       if (II == RewriteMap.end())
14204         continue;
14205 
14206       // Don't print things that are not interesting.
14207       if (II->second.second == Expr)
14208         continue;
14209 
14210       OS.indent(Depth) << "[PSE]" << I << ":\n";
14211       OS.indent(Depth + 2) << *Expr << "\n";
14212       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14213     }
14214 }
14215 
14216 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14217 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14218 // for URem with constant power-of-2 second operands.
14219 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14220 // 4, A / B becomes X / 8).
14221 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14222                                 const SCEV *&RHS) {
14223   // Try to match 'zext (trunc A to iB) to iY', which is used
14224   // for URem with constant power-of-2 second operands. Make sure the size of
14225   // the operand A matches the size of the whole expressions.
14226   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14227     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14228       LHS = Trunc->getOperand();
14229       // Bail out if the type of the LHS is larger than the type of the
14230       // expression for now.
14231       if (getTypeSizeInBits(LHS->getType()) >
14232           getTypeSizeInBits(Expr->getType()))
14233         return false;
14234       if (LHS->getType() != Expr->getType())
14235         LHS = getZeroExtendExpr(LHS, Expr->getType());
14236       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14237                         << getTypeSizeInBits(Trunc->getType()));
14238       return true;
14239     }
14240   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14241   if (Add == nullptr || Add->getNumOperands() != 2)
14242     return false;
14243 
14244   const SCEV *A = Add->getOperand(1);
14245   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14246 
14247   if (Mul == nullptr)
14248     return false;
14249 
14250   const auto MatchURemWithDivisor = [&](const SCEV *B) {
14251     // (SomeExpr + (-(SomeExpr / B) * B)).
14252     if (Expr == getURemExpr(A, B)) {
14253       LHS = A;
14254       RHS = B;
14255       return true;
14256     }
14257     return false;
14258   };
14259 
14260   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14261   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14262     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14263            MatchURemWithDivisor(Mul->getOperand(2));
14264 
14265   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14266   if (Mul->getNumOperands() == 2)
14267     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14268            MatchURemWithDivisor(Mul->getOperand(0)) ||
14269            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14270            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14271   return false;
14272 }
14273 
14274 const SCEV *
14275 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14276   SmallVector<BasicBlock*, 16> ExitingBlocks;
14277   L->getExitingBlocks(ExitingBlocks);
14278 
14279   // Form an expression for the maximum exit count possible for this loop. We
14280   // merge the max and exact information to approximate a version of
14281   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14282   SmallVector<const SCEV*, 4> ExitCounts;
14283   for (BasicBlock *ExitingBB : ExitingBlocks) {
14284     const SCEV *ExitCount = getExitCount(L, ExitingBB);
14285     if (isa<SCEVCouldNotCompute>(ExitCount))
14286       ExitCount = getExitCount(L, ExitingBB,
14287                                   ScalarEvolution::ConstantMaximum);
14288     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14289       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14290              "We should only have known counts for exiting blocks that "
14291              "dominate latch!");
14292       ExitCounts.push_back(ExitCount);
14293     }
14294   }
14295   if (ExitCounts.empty())
14296     return getCouldNotCompute();
14297   return getUMinFromMismatchedTypes(ExitCounts);
14298 }
14299 
14300 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14301 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14302 /// replacement is loop invariant in the loop of the AddRec.
14303 ///
14304 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
14305 /// supported.
14306 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14307   const DenseMap<const SCEV *, const SCEV *> &Map;
14308 
14309 public:
14310   SCEVLoopGuardRewriter(ScalarEvolution &SE,
14311                         DenseMap<const SCEV *, const SCEV *> &M)
14312       : SCEVRewriteVisitor(SE), Map(M) {}
14313 
14314   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14315 
14316   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14317     auto I = Map.find(Expr);
14318     if (I == Map.end())
14319       return Expr;
14320     return I->second;
14321   }
14322 
14323   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14324     auto I = Map.find(Expr);
14325     if (I == Map.end())
14326       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14327           Expr);
14328     return I->second;
14329   }
14330 };
14331 
14332 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14333   SmallVector<const SCEV *> ExprsToRewrite;
14334   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14335                               const SCEV *RHS,
14336                               DenseMap<const SCEV *, const SCEV *>
14337                                   &RewriteMap) {
14338     // WARNING: It is generally unsound to apply any wrap flags to the proposed
14339     // replacement SCEV which isn't directly implied by the structure of that
14340     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
14341     // legal.  See the scoping rules for flags in the header to understand why.
14342 
14343     // If LHS is a constant, apply information to the other expression.
14344     if (isa<SCEVConstant>(LHS)) {
14345       std::swap(LHS, RHS);
14346       Predicate = CmpInst::getSwappedPredicate(Predicate);
14347     }
14348 
14349     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
14350     // create this form when combining two checks of the form (X u< C2 + C1) and
14351     // (X >=u C1).
14352     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14353                                  &ExprsToRewrite]() {
14354       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14355       if (!AddExpr || AddExpr->getNumOperands() != 2)
14356         return false;
14357 
14358       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14359       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14360       auto *C2 = dyn_cast<SCEVConstant>(RHS);
14361       if (!C1 || !C2 || !LHSUnknown)
14362         return false;
14363 
14364       auto ExactRegion =
14365           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14366               .sub(C1->getAPInt());
14367 
14368       // Bail out, unless we have a non-wrapping, monotonic range.
14369       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14370         return false;
14371       auto I = RewriteMap.find(LHSUnknown);
14372       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14373       RewriteMap[LHSUnknown] = getUMaxExpr(
14374           getConstant(ExactRegion.getUnsignedMin()),
14375           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14376       ExprsToRewrite.push_back(LHSUnknown);
14377       return true;
14378     };
14379     if (MatchRangeCheckIdiom())
14380       return;
14381 
14382     // If we have LHS == 0, check if LHS is computing a property of some unknown
14383     // SCEV %v which we can rewrite %v to express explicitly.
14384     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
14385     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
14386         RHSC->getValue()->isNullValue()) {
14387       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
14388       // explicitly express that.
14389       const SCEV *URemLHS = nullptr;
14390       const SCEV *URemRHS = nullptr;
14391       if (matchURem(LHS, URemLHS, URemRHS)) {
14392         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
14393           auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
14394           RewriteMap[LHSUnknown] = Multiple;
14395           ExprsToRewrite.push_back(LHSUnknown);
14396           return;
14397         }
14398       }
14399     }
14400 
14401     // Do not apply information for constants or if RHS contains an AddRec.
14402     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
14403       return;
14404 
14405     // If RHS is SCEVUnknown, make sure the information is applied to it.
14406     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
14407       std::swap(LHS, RHS);
14408       Predicate = CmpInst::getSwappedPredicate(Predicate);
14409     }
14410 
14411     // Limit to expressions that can be rewritten.
14412     if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
14413       return;
14414 
14415     // Check whether LHS has already been rewritten. In that case we want to
14416     // chain further rewrites onto the already rewritten value.
14417     auto I = RewriteMap.find(LHS);
14418     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
14419 
14420     const SCEV *RewrittenRHS = nullptr;
14421     switch (Predicate) {
14422     case CmpInst::ICMP_ULT:
14423       RewrittenRHS =
14424           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14425       break;
14426     case CmpInst::ICMP_SLT:
14427       RewrittenRHS =
14428           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14429       break;
14430     case CmpInst::ICMP_ULE:
14431       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
14432       break;
14433     case CmpInst::ICMP_SLE:
14434       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
14435       break;
14436     case CmpInst::ICMP_UGT:
14437       RewrittenRHS =
14438           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14439       break;
14440     case CmpInst::ICMP_SGT:
14441       RewrittenRHS =
14442           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14443       break;
14444     case CmpInst::ICMP_UGE:
14445       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
14446       break;
14447     case CmpInst::ICMP_SGE:
14448       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
14449       break;
14450     case CmpInst::ICMP_EQ:
14451       if (isa<SCEVConstant>(RHS))
14452         RewrittenRHS = RHS;
14453       break;
14454     case CmpInst::ICMP_NE:
14455       if (isa<SCEVConstant>(RHS) &&
14456           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
14457         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
14458       break;
14459     default:
14460       break;
14461     }
14462 
14463     if (RewrittenRHS) {
14464       RewriteMap[LHS] = RewrittenRHS;
14465       if (LHS == RewrittenLHS)
14466         ExprsToRewrite.push_back(LHS);
14467     }
14468   };
14469   // First, collect conditions from dominating branches. Starting at the loop
14470   // predecessor, climb up the predecessor chain, as long as there are
14471   // predecessors that can be found that have unique successors leading to the
14472   // original header.
14473   // TODO: share this logic with isLoopEntryGuardedByCond.
14474   SmallVector<std::pair<Value *, bool>> Terms;
14475   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
14476            L->getLoopPredecessor(), L->getHeader());
14477        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
14478 
14479     const BranchInst *LoopEntryPredicate =
14480         dyn_cast<BranchInst>(Pair.first->getTerminator());
14481     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
14482       continue;
14483 
14484     Terms.emplace_back(LoopEntryPredicate->getCondition(),
14485                        LoopEntryPredicate->getSuccessor(0) == Pair.second);
14486   }
14487 
14488   // Now apply the information from the collected conditions to RewriteMap.
14489   // Conditions are processed in reverse order, so the earliest conditions is
14490   // processed first. This ensures the SCEVs with the shortest dependency chains
14491   // are constructed first.
14492   DenseMap<const SCEV *, const SCEV *> RewriteMap;
14493   for (auto &E : reverse(Terms)) {
14494     bool EnterIfTrue = E.second;
14495     SmallVector<Value *, 8> Worklist;
14496     SmallPtrSet<Value *, 8> Visited;
14497     Worklist.push_back(E.first);
14498     while (!Worklist.empty()) {
14499       Value *Cond = Worklist.pop_back_val();
14500       if (!Visited.insert(Cond).second)
14501         continue;
14502 
14503       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14504         auto Predicate =
14505             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
14506         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
14507                          getSCEV(Cmp->getOperand(1)), RewriteMap);
14508         continue;
14509       }
14510 
14511       Value *L, *R;
14512       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
14513                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
14514         Worklist.push_back(L);
14515         Worklist.push_back(R);
14516       }
14517     }
14518   }
14519 
14520   // Also collect information from assumptions dominating the loop.
14521   for (auto &AssumeVH : AC.assumptions()) {
14522     if (!AssumeVH)
14523       continue;
14524     auto *AssumeI = cast<CallInst>(AssumeVH);
14525     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
14526     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
14527       continue;
14528     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
14529                      getSCEV(Cmp->getOperand(1)), RewriteMap);
14530   }
14531 
14532   if (RewriteMap.empty())
14533     return Expr;
14534 
14535   // Now that all rewrite information is collect, rewrite the collected
14536   // expressions with the information in the map. This applies information to
14537   // sub-expressions.
14538   if (ExprsToRewrite.size() > 1) {
14539     for (const SCEV *Expr : ExprsToRewrite) {
14540       const SCEV *RewriteTo = RewriteMap[Expr];
14541       RewriteMap.erase(Expr);
14542       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14543       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
14544     }
14545   }
14546 
14547   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14548   return Rewriter.visit(Expr);
14549 }
14550