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 const SCEV *
4019 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4020                                          SmallVectorImpl<const SCEV *> &Ops) {
4021   assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4022          "Not a SCEVSequentialMinMaxExpr!");
4023   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4024   if (Ops.size() == 1)
4025     return Ops[0];
4026   if (Ops.size() == 2 &&
4027       any_of(Ops, [](const SCEV *Op) { return isa<SCEVConstant>(Op); }))
4028     return getMinMaxExpr(
4029         SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4030         Ops);
4031 #ifndef NDEBUG
4032   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4033   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4034     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4035            "Operand types don't match!");
4036     assert(Ops[0]->getType()->isPointerTy() ==
4037                Ops[i]->getType()->isPointerTy() &&
4038            "min/max should be consistently pointerish");
4039   }
4040 #endif
4041 
4042   // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4043   // so we can *NOT* do any kind of sorting of the expressions!
4044 
4045   // Check if we have created the same expression before.
4046   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4047     return S;
4048 
4049   // FIXME: there are *some* simplifications that we can do here.
4050 
4051   // Keep only the first instance of an operand.
4052   {
4053     SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4054     bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4055     if (Changed)
4056       return getSequentialMinMaxExpr(Kind, Ops);
4057   }
4058 
4059   // Check to see if one of the operands is of the same kind. If so, expand its
4060   // operands onto our operand list, and recurse to simplify.
4061   {
4062     unsigned Idx = 0;
4063     bool DeletedAny = false;
4064     while (Idx < Ops.size()) {
4065       if (Ops[Idx]->getSCEVType() != Kind) {
4066         ++Idx;
4067         continue;
4068       }
4069       const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4070       Ops.erase(Ops.begin() + Idx);
4071       Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end());
4072       DeletedAny = true;
4073     }
4074 
4075     if (DeletedAny)
4076       return getSequentialMinMaxExpr(Kind, Ops);
4077   }
4078 
4079   // Okay, it looks like we really DO need an expr.  Check to see if we
4080   // already have one, otherwise create a new one.
4081   FoldingSetNodeID ID;
4082   ID.AddInteger(Kind);
4083   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4084     ID.AddPointer(Ops[i]);
4085   void *IP = nullptr;
4086   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4087   if (ExistingSCEV)
4088     return ExistingSCEV;
4089 
4090   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4091   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4092   SCEV *S = new (SCEVAllocator)
4093       SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4094 
4095   UniqueSCEVs.InsertNode(S, IP);
4096   registerUser(S, Ops);
4097   return S;
4098 }
4099 
4100 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4101   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4102   return getSMaxExpr(Ops);
4103 }
4104 
4105 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4106   return getMinMaxExpr(scSMaxExpr, Ops);
4107 }
4108 
4109 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4110   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4111   return getUMaxExpr(Ops);
4112 }
4113 
4114 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4115   return getMinMaxExpr(scUMaxExpr, Ops);
4116 }
4117 
4118 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4119                                          const SCEV *RHS) {
4120   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4121   return getSMinExpr(Ops);
4122 }
4123 
4124 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4125   return getMinMaxExpr(scSMinExpr, Ops);
4126 }
4127 
4128 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4129                                          bool Sequential) {
4130   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4131   return getUMinExpr(Ops, Sequential);
4132 }
4133 
4134 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4135                                          bool Sequential) {
4136   return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4137                     : getMinMaxExpr(scUMinExpr, Ops);
4138 }
4139 
4140 const SCEV *
4141 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
4142                                              ScalableVectorType *ScalableTy) {
4143   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
4144   Constant *One = ConstantInt::get(IntTy, 1);
4145   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
4146   // Note that the expression we created is the final expression, we don't
4147   // want to simplify it any further Also, if we call a normal getSCEV(),
4148   // we'll end up in an endless recursion. So just create an SCEVUnknown.
4149   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
4150 }
4151 
4152 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4153   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
4154     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
4155   // We can bypass creating a target-independent constant expression and then
4156   // folding it back into a ConstantInt. This is just a compile-time
4157   // optimization.
4158   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4159 }
4160 
4161 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4162   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
4163     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
4164   // We can bypass creating a target-independent constant expression and then
4165   // folding it back into a ConstantInt. This is just a compile-time
4166   // optimization.
4167   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4168 }
4169 
4170 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4171                                              StructType *STy,
4172                                              unsigned FieldNo) {
4173   // We can bypass creating a target-independent constant expression and then
4174   // folding it back into a ConstantInt. This is just a compile-time
4175   // optimization.
4176   return getConstant(
4177       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
4178 }
4179 
4180 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4181   // Don't attempt to do anything other than create a SCEVUnknown object
4182   // here.  createSCEV only calls getUnknown after checking for all other
4183   // interesting possibilities, and any other code that calls getUnknown
4184   // is doing so in order to hide a value from SCEV canonicalization.
4185 
4186   FoldingSetNodeID ID;
4187   ID.AddInteger(scUnknown);
4188   ID.AddPointer(V);
4189   void *IP = nullptr;
4190   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4191     assert(cast<SCEVUnknown>(S)->getValue() == V &&
4192            "Stale SCEVUnknown in uniquing map!");
4193     return S;
4194   }
4195   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4196                                             FirstUnknown);
4197   FirstUnknown = cast<SCEVUnknown>(S);
4198   UniqueSCEVs.InsertNode(S, IP);
4199   return S;
4200 }
4201 
4202 //===----------------------------------------------------------------------===//
4203 //            Basic SCEV Analysis and PHI Idiom Recognition Code
4204 //
4205 
4206 /// Test if values of the given type are analyzable within the SCEV
4207 /// framework. This primarily includes integer types, and it can optionally
4208 /// include pointer types if the ScalarEvolution class has access to
4209 /// target-specific information.
4210 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4211   // Integers and pointers are always SCEVable.
4212   return Ty->isIntOrPtrTy();
4213 }
4214 
4215 /// Return the size in bits of the specified type, for which isSCEVable must
4216 /// return true.
4217 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4218   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4219   if (Ty->isPointerTy())
4220     return getDataLayout().getIndexTypeSizeInBits(Ty);
4221   return getDataLayout().getTypeSizeInBits(Ty);
4222 }
4223 
4224 /// Return a type with the same bitwidth as the given type and which represents
4225 /// how SCEV will treat the given type, for which isSCEVable must return
4226 /// true. For pointer types, this is the pointer index sized integer type.
4227 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4228   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4229 
4230   if (Ty->isIntegerTy())
4231     return Ty;
4232 
4233   // The only other support type is pointer.
4234   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4235   return getDataLayout().getIndexType(Ty);
4236 }
4237 
4238 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4239   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4240 }
4241 
4242 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4243                                                          const SCEV *B) {
4244   /// For a valid use point to exist, the defining scope of one operand
4245   /// must dominate the other.
4246   bool PreciseA, PreciseB;
4247   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4248   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4249   if (!PreciseA || !PreciseB)
4250     // Can't tell.
4251     return false;
4252   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4253     DT.dominates(ScopeB, ScopeA);
4254 }
4255 
4256 
4257 const SCEV *ScalarEvolution::getCouldNotCompute() {
4258   return CouldNotCompute.get();
4259 }
4260 
4261 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4262   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4263     auto *SU = dyn_cast<SCEVUnknown>(S);
4264     return SU && SU->getValue() == nullptr;
4265   });
4266 
4267   return !ContainsNulls;
4268 }
4269 
4270 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4271   HasRecMapType::iterator I = HasRecMap.find(S);
4272   if (I != HasRecMap.end())
4273     return I->second;
4274 
4275   bool FoundAddRec =
4276       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4277   HasRecMap.insert({S, FoundAddRec});
4278   return FoundAddRec;
4279 }
4280 
4281 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4282 /// by the value and offset from any ValueOffsetPair in the set.
4283 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4284   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4285   if (SI == ExprValueMap.end())
4286     return None;
4287 #ifndef NDEBUG
4288   if (VerifySCEVMap) {
4289     // Check there is no dangling Value in the set returned.
4290     for (Value *V : SI->second)
4291       assert(ValueExprMap.count(V));
4292   }
4293 #endif
4294   return SI->second.getArrayRef();
4295 }
4296 
4297 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4298 /// cannot be used separately. eraseValueFromMap should be used to remove
4299 /// V from ValueExprMap and ExprValueMap at the same time.
4300 void ScalarEvolution::eraseValueFromMap(Value *V) {
4301   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4302   if (I != ValueExprMap.end()) {
4303     auto EVIt = ExprValueMap.find(I->second);
4304     bool Removed = EVIt->second.remove(V);
4305     (void) Removed;
4306     assert(Removed && "Value not in ExprValueMap?");
4307     ValueExprMap.erase(I);
4308   }
4309 }
4310 
4311 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4312   // A recursive query may have already computed the SCEV. It should be
4313   // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4314   // inferred nowrap flags.
4315   auto It = ValueExprMap.find_as(V);
4316   if (It == ValueExprMap.end()) {
4317     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4318     ExprValueMap[S].insert(V);
4319   }
4320 }
4321 
4322 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4323 /// create a new one.
4324 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4325   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4326 
4327   const SCEV *S = getExistingSCEV(V);
4328   if (S == nullptr) {
4329     S = createSCEV(V);
4330     // During PHI resolution, it is possible to create two SCEVs for the same
4331     // V, so it is needed to double check whether V->S is inserted into
4332     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4333     std::pair<ValueExprMapType::iterator, bool> Pair =
4334         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4335     if (Pair.second)
4336       ExprValueMap[S].insert(V);
4337   }
4338   return S;
4339 }
4340 
4341 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4342   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4343 
4344   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4345   if (I != ValueExprMap.end()) {
4346     const SCEV *S = I->second;
4347     assert(checkValidity(S) &&
4348            "existing SCEV has not been properly invalidated");
4349     return S;
4350   }
4351   return nullptr;
4352 }
4353 
4354 /// Return a SCEV corresponding to -V = -1*V
4355 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4356                                              SCEV::NoWrapFlags Flags) {
4357   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4358     return getConstant(
4359                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4360 
4361   Type *Ty = V->getType();
4362   Ty = getEffectiveSCEVType(Ty);
4363   return getMulExpr(V, getMinusOne(Ty), Flags);
4364 }
4365 
4366 /// If Expr computes ~A, return A else return nullptr
4367 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4368   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4369   if (!Add || Add->getNumOperands() != 2 ||
4370       !Add->getOperand(0)->isAllOnesValue())
4371     return nullptr;
4372 
4373   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4374   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4375       !AddRHS->getOperand(0)->isAllOnesValue())
4376     return nullptr;
4377 
4378   return AddRHS->getOperand(1);
4379 }
4380 
4381 /// Return a SCEV corresponding to ~V = -1-V
4382 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4383   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4384 
4385   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4386     return getConstant(
4387                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4388 
4389   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4390   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4391     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4392       SmallVector<const SCEV *, 2> MatchedOperands;
4393       for (const SCEV *Operand : MME->operands()) {
4394         const SCEV *Matched = MatchNotExpr(Operand);
4395         if (!Matched)
4396           return (const SCEV *)nullptr;
4397         MatchedOperands.push_back(Matched);
4398       }
4399       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4400                            MatchedOperands);
4401     };
4402     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4403       return Replaced;
4404   }
4405 
4406   Type *Ty = V->getType();
4407   Ty = getEffectiveSCEVType(Ty);
4408   return getMinusSCEV(getMinusOne(Ty), V);
4409 }
4410 
4411 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4412   assert(P->getType()->isPointerTy());
4413 
4414   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4415     // The base of an AddRec is the first operand.
4416     SmallVector<const SCEV *> Ops{AddRec->operands()};
4417     Ops[0] = removePointerBase(Ops[0]);
4418     // Don't try to transfer nowrap flags for now. We could in some cases
4419     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4420     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4421   }
4422   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4423     // The base of an Add is the pointer operand.
4424     SmallVector<const SCEV *> Ops{Add->operands()};
4425     const SCEV **PtrOp = nullptr;
4426     for (const SCEV *&AddOp : Ops) {
4427       if (AddOp->getType()->isPointerTy()) {
4428         assert(!PtrOp && "Cannot have multiple pointer ops");
4429         PtrOp = &AddOp;
4430       }
4431     }
4432     *PtrOp = removePointerBase(*PtrOp);
4433     // Don't try to transfer nowrap flags for now. We could in some cases
4434     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4435     return getAddExpr(Ops);
4436   }
4437   // Any other expression must be a pointer base.
4438   return getZero(P->getType());
4439 }
4440 
4441 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4442                                           SCEV::NoWrapFlags Flags,
4443                                           unsigned Depth) {
4444   // Fast path: X - X --> 0.
4445   if (LHS == RHS)
4446     return getZero(LHS->getType());
4447 
4448   // If we subtract two pointers with different pointer bases, bail.
4449   // Eventually, we're going to add an assertion to getMulExpr that we
4450   // can't multiply by a pointer.
4451   if (RHS->getType()->isPointerTy()) {
4452     if (!LHS->getType()->isPointerTy() ||
4453         getPointerBase(LHS) != getPointerBase(RHS))
4454       return getCouldNotCompute();
4455     LHS = removePointerBase(LHS);
4456     RHS = removePointerBase(RHS);
4457   }
4458 
4459   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4460   // makes it so that we cannot make much use of NUW.
4461   auto AddFlags = SCEV::FlagAnyWrap;
4462   const bool RHSIsNotMinSigned =
4463       !getSignedRangeMin(RHS).isMinSignedValue();
4464   if (hasFlags(Flags, SCEV::FlagNSW)) {
4465     // Let M be the minimum representable signed value. Then (-1)*RHS
4466     // signed-wraps if and only if RHS is M. That can happen even for
4467     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4468     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4469     // (-1)*RHS, we need to prove that RHS != M.
4470     //
4471     // If LHS is non-negative and we know that LHS - RHS does not
4472     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4473     // either by proving that RHS > M or that LHS >= 0.
4474     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4475       AddFlags = SCEV::FlagNSW;
4476     }
4477   }
4478 
4479   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4480   // RHS is NSW and LHS >= 0.
4481   //
4482   // The difficulty here is that the NSW flag may have been proven
4483   // relative to a loop that is to be found in a recurrence in LHS and
4484   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4485   // larger scope than intended.
4486   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4487 
4488   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4489 }
4490 
4491 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4492                                                      unsigned Depth) {
4493   Type *SrcTy = V->getType();
4494   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4495          "Cannot truncate or zero extend with non-integer arguments!");
4496   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4497     return V;  // No conversion
4498   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4499     return getTruncateExpr(V, Ty, Depth);
4500   return getZeroExtendExpr(V, Ty, Depth);
4501 }
4502 
4503 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4504                                                      unsigned Depth) {
4505   Type *SrcTy = V->getType();
4506   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4507          "Cannot truncate or zero extend with non-integer arguments!");
4508   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4509     return V;  // No conversion
4510   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4511     return getTruncateExpr(V, Ty, Depth);
4512   return getSignExtendExpr(V, Ty, Depth);
4513 }
4514 
4515 const SCEV *
4516 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4517   Type *SrcTy = V->getType();
4518   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4519          "Cannot noop or zero extend with non-integer arguments!");
4520   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4521          "getNoopOrZeroExtend cannot truncate!");
4522   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4523     return V;  // No conversion
4524   return getZeroExtendExpr(V, Ty);
4525 }
4526 
4527 const SCEV *
4528 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4529   Type *SrcTy = V->getType();
4530   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4531          "Cannot noop or sign extend with non-integer arguments!");
4532   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4533          "getNoopOrSignExtend cannot truncate!");
4534   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4535     return V;  // No conversion
4536   return getSignExtendExpr(V, Ty);
4537 }
4538 
4539 const SCEV *
4540 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4541   Type *SrcTy = V->getType();
4542   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4543          "Cannot noop or any extend with non-integer arguments!");
4544   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4545          "getNoopOrAnyExtend cannot truncate!");
4546   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4547     return V;  // No conversion
4548   return getAnyExtendExpr(V, Ty);
4549 }
4550 
4551 const SCEV *
4552 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4553   Type *SrcTy = V->getType();
4554   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4555          "Cannot truncate or noop with non-integer arguments!");
4556   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4557          "getTruncateOrNoop cannot extend!");
4558   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4559     return V;  // No conversion
4560   return getTruncateExpr(V, Ty);
4561 }
4562 
4563 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4564                                                         const SCEV *RHS) {
4565   const SCEV *PromotedLHS = LHS;
4566   const SCEV *PromotedRHS = RHS;
4567 
4568   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4569     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4570   else
4571     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4572 
4573   return getUMaxExpr(PromotedLHS, PromotedRHS);
4574 }
4575 
4576 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4577                                                         const SCEV *RHS,
4578                                                         bool Sequential) {
4579   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4580   return getUMinFromMismatchedTypes(Ops, Sequential);
4581 }
4582 
4583 const SCEV *
4584 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4585                                             bool Sequential) {
4586   assert(!Ops.empty() && "At least one operand must be!");
4587   // Trivial case.
4588   if (Ops.size() == 1)
4589     return Ops[0];
4590 
4591   // Find the max type first.
4592   Type *MaxType = nullptr;
4593   for (auto *S : Ops)
4594     if (MaxType)
4595       MaxType = getWiderType(MaxType, S->getType());
4596     else
4597       MaxType = S->getType();
4598   assert(MaxType && "Failed to find maximum type!");
4599 
4600   // Extend all ops to max type.
4601   SmallVector<const SCEV *, 2> PromotedOps;
4602   for (auto *S : Ops)
4603     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4604 
4605   // Generate umin.
4606   return getUMinExpr(PromotedOps, Sequential);
4607 }
4608 
4609 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4610   // A pointer operand may evaluate to a nonpointer expression, such as null.
4611   if (!V->getType()->isPointerTy())
4612     return V;
4613 
4614   while (true) {
4615     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4616       V = AddRec->getStart();
4617     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4618       const SCEV *PtrOp = nullptr;
4619       for (const SCEV *AddOp : Add->operands()) {
4620         if (AddOp->getType()->isPointerTy()) {
4621           assert(!PtrOp && "Cannot have multiple pointer ops");
4622           PtrOp = AddOp;
4623         }
4624       }
4625       assert(PtrOp && "Must have pointer op");
4626       V = PtrOp;
4627     } else // Not something we can look further into.
4628       return V;
4629   }
4630 }
4631 
4632 /// Push users of the given Instruction onto the given Worklist.
4633 static void PushDefUseChildren(Instruction *I,
4634                                SmallVectorImpl<Instruction *> &Worklist,
4635                                SmallPtrSetImpl<Instruction *> &Visited) {
4636   // Push the def-use children onto the Worklist stack.
4637   for (User *U : I->users()) {
4638     auto *UserInsn = cast<Instruction>(U);
4639     if (Visited.insert(UserInsn).second)
4640       Worklist.push_back(UserInsn);
4641   }
4642 }
4643 
4644 namespace {
4645 
4646 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4647 /// expression in case its Loop is L. If it is not L then
4648 /// if IgnoreOtherLoops is true then use AddRec itself
4649 /// otherwise rewrite cannot be done.
4650 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4651 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4652 public:
4653   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4654                              bool IgnoreOtherLoops = true) {
4655     SCEVInitRewriter Rewriter(L, SE);
4656     const SCEV *Result = Rewriter.visit(S);
4657     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4658       return SE.getCouldNotCompute();
4659     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4660                ? SE.getCouldNotCompute()
4661                : Result;
4662   }
4663 
4664   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4665     if (!SE.isLoopInvariant(Expr, L))
4666       SeenLoopVariantSCEVUnknown = true;
4667     return Expr;
4668   }
4669 
4670   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4671     // Only re-write AddRecExprs for this loop.
4672     if (Expr->getLoop() == L)
4673       return Expr->getStart();
4674     SeenOtherLoops = true;
4675     return Expr;
4676   }
4677 
4678   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4679 
4680   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4681 
4682 private:
4683   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4684       : SCEVRewriteVisitor(SE), L(L) {}
4685 
4686   const Loop *L;
4687   bool SeenLoopVariantSCEVUnknown = false;
4688   bool SeenOtherLoops = false;
4689 };
4690 
4691 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4692 /// increment expression in case its Loop is L. If it is not L then
4693 /// use AddRec itself.
4694 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4695 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4696 public:
4697   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4698     SCEVPostIncRewriter Rewriter(L, SE);
4699     const SCEV *Result = Rewriter.visit(S);
4700     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4701         ? SE.getCouldNotCompute()
4702         : Result;
4703   }
4704 
4705   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4706     if (!SE.isLoopInvariant(Expr, L))
4707       SeenLoopVariantSCEVUnknown = true;
4708     return Expr;
4709   }
4710 
4711   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4712     // Only re-write AddRecExprs for this loop.
4713     if (Expr->getLoop() == L)
4714       return Expr->getPostIncExpr(SE);
4715     SeenOtherLoops = true;
4716     return Expr;
4717   }
4718 
4719   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4720 
4721   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4722 
4723 private:
4724   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4725       : SCEVRewriteVisitor(SE), L(L) {}
4726 
4727   const Loop *L;
4728   bool SeenLoopVariantSCEVUnknown = false;
4729   bool SeenOtherLoops = false;
4730 };
4731 
4732 /// This class evaluates the compare condition by matching it against the
4733 /// condition of loop latch. If there is a match we assume a true value
4734 /// for the condition while building SCEV nodes.
4735 class SCEVBackedgeConditionFolder
4736     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4737 public:
4738   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4739                              ScalarEvolution &SE) {
4740     bool IsPosBECond = false;
4741     Value *BECond = nullptr;
4742     if (BasicBlock *Latch = L->getLoopLatch()) {
4743       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4744       if (BI && BI->isConditional()) {
4745         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4746                "Both outgoing branches should not target same header!");
4747         BECond = BI->getCondition();
4748         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4749       } else {
4750         return S;
4751       }
4752     }
4753     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4754     return Rewriter.visit(S);
4755   }
4756 
4757   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4758     const SCEV *Result = Expr;
4759     bool InvariantF = SE.isLoopInvariant(Expr, L);
4760 
4761     if (!InvariantF) {
4762       Instruction *I = cast<Instruction>(Expr->getValue());
4763       switch (I->getOpcode()) {
4764       case Instruction::Select: {
4765         SelectInst *SI = cast<SelectInst>(I);
4766         Optional<const SCEV *> Res =
4767             compareWithBackedgeCondition(SI->getCondition());
4768         if (Res.hasValue()) {
4769           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4770           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4771         }
4772         break;
4773       }
4774       default: {
4775         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4776         if (Res.hasValue())
4777           Result = Res.getValue();
4778         break;
4779       }
4780       }
4781     }
4782     return Result;
4783   }
4784 
4785 private:
4786   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4787                                        bool IsPosBECond, ScalarEvolution &SE)
4788       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4789         IsPositiveBECond(IsPosBECond) {}
4790 
4791   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4792 
4793   const Loop *L;
4794   /// Loop back condition.
4795   Value *BackedgeCond = nullptr;
4796   /// Set to true if loop back is on positive branch condition.
4797   bool IsPositiveBECond;
4798 };
4799 
4800 Optional<const SCEV *>
4801 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4802 
4803   // If value matches the backedge condition for loop latch,
4804   // then return a constant evolution node based on loopback
4805   // branch taken.
4806   if (BackedgeCond == IC)
4807     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4808                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4809   return None;
4810 }
4811 
4812 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4813 public:
4814   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4815                              ScalarEvolution &SE) {
4816     SCEVShiftRewriter Rewriter(L, SE);
4817     const SCEV *Result = Rewriter.visit(S);
4818     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4819   }
4820 
4821   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4822     // Only allow AddRecExprs for this loop.
4823     if (!SE.isLoopInvariant(Expr, L))
4824       Valid = false;
4825     return Expr;
4826   }
4827 
4828   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4829     if (Expr->getLoop() == L && Expr->isAffine())
4830       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4831     Valid = false;
4832     return Expr;
4833   }
4834 
4835   bool isValid() { return Valid; }
4836 
4837 private:
4838   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4839       : SCEVRewriteVisitor(SE), L(L) {}
4840 
4841   const Loop *L;
4842   bool Valid = true;
4843 };
4844 
4845 } // end anonymous namespace
4846 
4847 SCEV::NoWrapFlags
4848 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4849   if (!AR->isAffine())
4850     return SCEV::FlagAnyWrap;
4851 
4852   using OBO = OverflowingBinaryOperator;
4853 
4854   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4855 
4856   if (!AR->hasNoSignedWrap()) {
4857     ConstantRange AddRecRange = getSignedRange(AR);
4858     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4859 
4860     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4861         Instruction::Add, IncRange, OBO::NoSignedWrap);
4862     if (NSWRegion.contains(AddRecRange))
4863       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4864   }
4865 
4866   if (!AR->hasNoUnsignedWrap()) {
4867     ConstantRange AddRecRange = getUnsignedRange(AR);
4868     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4869 
4870     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4871         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4872     if (NUWRegion.contains(AddRecRange))
4873       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4874   }
4875 
4876   return Result;
4877 }
4878 
4879 SCEV::NoWrapFlags
4880 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4881   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4882 
4883   if (AR->hasNoSignedWrap())
4884     return Result;
4885 
4886   if (!AR->isAffine())
4887     return Result;
4888 
4889   const SCEV *Step = AR->getStepRecurrence(*this);
4890   const Loop *L = AR->getLoop();
4891 
4892   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4893   // Note that this serves two purposes: It filters out loops that are
4894   // simply not analyzable, and it covers the case where this code is
4895   // being called from within backedge-taken count analysis, such that
4896   // attempting to ask for the backedge-taken count would likely result
4897   // in infinite recursion. In the later case, the analysis code will
4898   // cope with a conservative value, and it will take care to purge
4899   // that value once it has finished.
4900   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4901 
4902   // Normally, in the cases we can prove no-overflow via a
4903   // backedge guarding condition, we can also compute a backedge
4904   // taken count for the loop.  The exceptions are assumptions and
4905   // guards present in the loop -- SCEV is not great at exploiting
4906   // these to compute max backedge taken counts, but can still use
4907   // these to prove lack of overflow.  Use this fact to avoid
4908   // doing extra work that may not pay off.
4909 
4910   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4911       AC.assumptions().empty())
4912     return Result;
4913 
4914   // If the backedge is guarded by a comparison with the pre-inc  value the
4915   // addrec is safe. Also, if the entry is guarded by a comparison with the
4916   // start value and the backedge is guarded by a comparison with the post-inc
4917   // value, the addrec is safe.
4918   ICmpInst::Predicate Pred;
4919   const SCEV *OverflowLimit =
4920     getSignedOverflowLimitForStep(Step, &Pred, this);
4921   if (OverflowLimit &&
4922       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4923        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4924     Result = setFlags(Result, SCEV::FlagNSW);
4925   }
4926   return Result;
4927 }
4928 SCEV::NoWrapFlags
4929 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4930   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4931 
4932   if (AR->hasNoUnsignedWrap())
4933     return Result;
4934 
4935   if (!AR->isAffine())
4936     return Result;
4937 
4938   const SCEV *Step = AR->getStepRecurrence(*this);
4939   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4940   const Loop *L = AR->getLoop();
4941 
4942   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4943   // Note that this serves two purposes: It filters out loops that are
4944   // simply not analyzable, and it covers the case where this code is
4945   // being called from within backedge-taken count analysis, such that
4946   // attempting to ask for the backedge-taken count would likely result
4947   // in infinite recursion. In the later case, the analysis code will
4948   // cope with a conservative value, and it will take care to purge
4949   // that value once it has finished.
4950   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4951 
4952   // Normally, in the cases we can prove no-overflow via a
4953   // backedge guarding condition, we can also compute a backedge
4954   // taken count for the loop.  The exceptions are assumptions and
4955   // guards present in the loop -- SCEV is not great at exploiting
4956   // these to compute max backedge taken counts, but can still use
4957   // these to prove lack of overflow.  Use this fact to avoid
4958   // doing extra work that may not pay off.
4959 
4960   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4961       AC.assumptions().empty())
4962     return Result;
4963 
4964   // If the backedge is guarded by a comparison with the pre-inc  value the
4965   // addrec is safe. Also, if the entry is guarded by a comparison with the
4966   // start value and the backedge is guarded by a comparison with the post-inc
4967   // value, the addrec is safe.
4968   if (isKnownPositive(Step)) {
4969     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4970                                 getUnsignedRangeMax(Step));
4971     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4972         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4973       Result = setFlags(Result, SCEV::FlagNUW);
4974     }
4975   }
4976 
4977   return Result;
4978 }
4979 
4980 namespace {
4981 
4982 /// Represents an abstract binary operation.  This may exist as a
4983 /// normal instruction or constant expression, or may have been
4984 /// derived from an expression tree.
4985 struct BinaryOp {
4986   unsigned Opcode;
4987   Value *LHS;
4988   Value *RHS;
4989   bool IsNSW = false;
4990   bool IsNUW = false;
4991 
4992   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4993   /// constant expression.
4994   Operator *Op = nullptr;
4995 
4996   explicit BinaryOp(Operator *Op)
4997       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4998         Op(Op) {
4999     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5000       IsNSW = OBO->hasNoSignedWrap();
5001       IsNUW = OBO->hasNoUnsignedWrap();
5002     }
5003   }
5004 
5005   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5006                     bool IsNUW = false)
5007       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5008 };
5009 
5010 } // end anonymous namespace
5011 
5012 /// Try to map \p V into a BinaryOp, and return \c None on failure.
5013 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
5014   auto *Op = dyn_cast<Operator>(V);
5015   if (!Op)
5016     return None;
5017 
5018   // Implementation detail: all the cleverness here should happen without
5019   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5020   // SCEV expressions when possible, and we should not break that.
5021 
5022   switch (Op->getOpcode()) {
5023   case Instruction::Add:
5024   case Instruction::Sub:
5025   case Instruction::Mul:
5026   case Instruction::UDiv:
5027   case Instruction::URem:
5028   case Instruction::And:
5029   case Instruction::Or:
5030   case Instruction::AShr:
5031   case Instruction::Shl:
5032     return BinaryOp(Op);
5033 
5034   case Instruction::Xor:
5035     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5036       // If the RHS of the xor is a signmask, then this is just an add.
5037       // Instcombine turns add of signmask into xor as a strength reduction step.
5038       if (RHSC->getValue().isSignMask())
5039         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5040     // Binary `xor` is a bit-wise `add`.
5041     if (V->getType()->isIntegerTy(1))
5042       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5043     return BinaryOp(Op);
5044 
5045   case Instruction::LShr:
5046     // Turn logical shift right of a constant into a unsigned divide.
5047     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5048       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5049 
5050       // If the shift count is not less than the bitwidth, the result of
5051       // the shift is undefined. Don't try to analyze it, because the
5052       // resolution chosen here may differ from the resolution chosen in
5053       // other parts of the compiler.
5054       if (SA->getValue().ult(BitWidth)) {
5055         Constant *X =
5056             ConstantInt::get(SA->getContext(),
5057                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5058         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5059       }
5060     }
5061     return BinaryOp(Op);
5062 
5063   case Instruction::ExtractValue: {
5064     auto *EVI = cast<ExtractValueInst>(Op);
5065     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5066       break;
5067 
5068     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5069     if (!WO)
5070       break;
5071 
5072     Instruction::BinaryOps BinOp = WO->getBinaryOp();
5073     bool Signed = WO->isSigned();
5074     // TODO: Should add nuw/nsw flags for mul as well.
5075     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5076       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5077 
5078     // Now that we know that all uses of the arithmetic-result component of
5079     // CI are guarded by the overflow check, we can go ahead and pretend
5080     // that the arithmetic is non-overflowing.
5081     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5082                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5083   }
5084 
5085   default:
5086     break;
5087   }
5088 
5089   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5090   // semantics as a Sub, return a binary sub expression.
5091   if (auto *II = dyn_cast<IntrinsicInst>(V))
5092     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5093       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5094 
5095   return None;
5096 }
5097 
5098 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5099 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5100 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5101 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5102 /// follows one of the following patterns:
5103 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5104 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5105 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5106 /// we return the type of the truncation operation, and indicate whether the
5107 /// truncated type should be treated as signed/unsigned by setting
5108 /// \p Signed to true/false, respectively.
5109 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5110                                bool &Signed, ScalarEvolution &SE) {
5111   // The case where Op == SymbolicPHI (that is, with no type conversions on
5112   // the way) is handled by the regular add recurrence creating logic and
5113   // would have already been triggered in createAddRecForPHI. Reaching it here
5114   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5115   // because one of the other operands of the SCEVAddExpr updating this PHI is
5116   // not invariant).
5117   //
5118   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5119   // this case predicates that allow us to prove that Op == SymbolicPHI will
5120   // be added.
5121   if (Op == SymbolicPHI)
5122     return nullptr;
5123 
5124   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5125   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5126   if (SourceBits != NewBits)
5127     return nullptr;
5128 
5129   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5130   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5131   if (!SExt && !ZExt)
5132     return nullptr;
5133   const SCEVTruncateExpr *Trunc =
5134       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5135            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5136   if (!Trunc)
5137     return nullptr;
5138   const SCEV *X = Trunc->getOperand();
5139   if (X != SymbolicPHI)
5140     return nullptr;
5141   Signed = SExt != nullptr;
5142   return Trunc->getType();
5143 }
5144 
5145 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5146   if (!PN->getType()->isIntegerTy())
5147     return nullptr;
5148   const Loop *L = LI.getLoopFor(PN->getParent());
5149   if (!L || L->getHeader() != PN->getParent())
5150     return nullptr;
5151   return L;
5152 }
5153 
5154 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5155 // computation that updates the phi follows the following pattern:
5156 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5157 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5158 // If so, try to see if it can be rewritten as an AddRecExpr under some
5159 // Predicates. If successful, return them as a pair. Also cache the results
5160 // of the analysis.
5161 //
5162 // Example usage scenario:
5163 //    Say the Rewriter is called for the following SCEV:
5164 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5165 //    where:
5166 //         %X = phi i64 (%Start, %BEValue)
5167 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5168 //    and call this function with %SymbolicPHI = %X.
5169 //
5170 //    The analysis will find that the value coming around the backedge has
5171 //    the following SCEV:
5172 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5173 //    Upon concluding that this matches the desired pattern, the function
5174 //    will return the pair {NewAddRec, SmallPredsVec} where:
5175 //         NewAddRec = {%Start,+,%Step}
5176 //         SmallPredsVec = {P1, P2, P3} as follows:
5177 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5178 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5179 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5180 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5181 //    under the predicates {P1,P2,P3}.
5182 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5183 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5184 //
5185 // TODO's:
5186 //
5187 // 1) Extend the Induction descriptor to also support inductions that involve
5188 //    casts: When needed (namely, when we are called in the context of the
5189 //    vectorizer induction analysis), a Set of cast instructions will be
5190 //    populated by this method, and provided back to isInductionPHI. This is
5191 //    needed to allow the vectorizer to properly record them to be ignored by
5192 //    the cost model and to avoid vectorizing them (otherwise these casts,
5193 //    which are redundant under the runtime overflow checks, will be
5194 //    vectorized, which can be costly).
5195 //
5196 // 2) Support additional induction/PHISCEV patterns: We also want to support
5197 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5198 //    after the induction update operation (the induction increment):
5199 //
5200 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5201 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5202 //
5203 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5204 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5205 //
5206 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5207 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5208 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5209   SmallVector<const SCEVPredicate *, 3> Predicates;
5210 
5211   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5212   // return an AddRec expression under some predicate.
5213 
5214   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5215   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5216   assert(L && "Expecting an integer loop header phi");
5217 
5218   // The loop may have multiple entrances or multiple exits; we can analyze
5219   // this phi as an addrec if it has a unique entry value and a unique
5220   // backedge value.
5221   Value *BEValueV = nullptr, *StartValueV = nullptr;
5222   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5223     Value *V = PN->getIncomingValue(i);
5224     if (L->contains(PN->getIncomingBlock(i))) {
5225       if (!BEValueV) {
5226         BEValueV = V;
5227       } else if (BEValueV != V) {
5228         BEValueV = nullptr;
5229         break;
5230       }
5231     } else if (!StartValueV) {
5232       StartValueV = V;
5233     } else if (StartValueV != V) {
5234       StartValueV = nullptr;
5235       break;
5236     }
5237   }
5238   if (!BEValueV || !StartValueV)
5239     return None;
5240 
5241   const SCEV *BEValue = getSCEV(BEValueV);
5242 
5243   // If the value coming around the backedge is an add with the symbolic
5244   // value we just inserted, possibly with casts that we can ignore under
5245   // an appropriate runtime guard, then we found a simple induction variable!
5246   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5247   if (!Add)
5248     return None;
5249 
5250   // If there is a single occurrence of the symbolic value, possibly
5251   // casted, replace it with a recurrence.
5252   unsigned FoundIndex = Add->getNumOperands();
5253   Type *TruncTy = nullptr;
5254   bool Signed;
5255   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5256     if ((TruncTy =
5257              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5258       if (FoundIndex == e) {
5259         FoundIndex = i;
5260         break;
5261       }
5262 
5263   if (FoundIndex == Add->getNumOperands())
5264     return None;
5265 
5266   // Create an add with everything but the specified operand.
5267   SmallVector<const SCEV *, 8> Ops;
5268   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5269     if (i != FoundIndex)
5270       Ops.push_back(Add->getOperand(i));
5271   const SCEV *Accum = getAddExpr(Ops);
5272 
5273   // The runtime checks will not be valid if the step amount is
5274   // varying inside the loop.
5275   if (!isLoopInvariant(Accum, L))
5276     return None;
5277 
5278   // *** Part2: Create the predicates
5279 
5280   // Analysis was successful: we have a phi-with-cast pattern for which we
5281   // can return an AddRec expression under the following predicates:
5282   //
5283   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5284   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5285   // P2: An Equal predicate that guarantees that
5286   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5287   // P3: An Equal predicate that guarantees that
5288   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5289   //
5290   // As we next prove, the above predicates guarantee that:
5291   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5292   //
5293   //
5294   // More formally, we want to prove that:
5295   //     Expr(i+1) = Start + (i+1) * Accum
5296   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5297   //
5298   // Given that:
5299   // 1) Expr(0) = Start
5300   // 2) Expr(1) = Start + Accum
5301   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5302   // 3) Induction hypothesis (step i):
5303   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5304   //
5305   // Proof:
5306   //  Expr(i+1) =
5307   //   = Start + (i+1)*Accum
5308   //   = (Start + i*Accum) + Accum
5309   //   = Expr(i) + Accum
5310   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5311   //                                                             :: from step i
5312   //
5313   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5314   //
5315   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5316   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5317   //     + Accum                                                     :: from P3
5318   //
5319   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5320   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5321   //
5322   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5323   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5324   //
5325   // By induction, the same applies to all iterations 1<=i<n:
5326   //
5327 
5328   // Create a truncated addrec for which we will add a no overflow check (P1).
5329   const SCEV *StartVal = getSCEV(StartValueV);
5330   const SCEV *PHISCEV =
5331       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5332                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5333 
5334   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5335   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5336   // will be constant.
5337   //
5338   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5339   // add P1.
5340   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5341     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5342         Signed ? SCEVWrapPredicate::IncrementNSSW
5343                : SCEVWrapPredicate::IncrementNUSW;
5344     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5345     Predicates.push_back(AddRecPred);
5346   }
5347 
5348   // Create the Equal Predicates P2,P3:
5349 
5350   // It is possible that the predicates P2 and/or P3 are computable at
5351   // compile time due to StartVal and/or Accum being constants.
5352   // If either one is, then we can check that now and escape if either P2
5353   // or P3 is false.
5354 
5355   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5356   // for each of StartVal and Accum
5357   auto getExtendedExpr = [&](const SCEV *Expr,
5358                              bool CreateSignExtend) -> const SCEV * {
5359     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5360     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5361     const SCEV *ExtendedExpr =
5362         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5363                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5364     return ExtendedExpr;
5365   };
5366 
5367   // Given:
5368   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5369   //               = getExtendedExpr(Expr)
5370   // Determine whether the predicate P: Expr == ExtendedExpr
5371   // is known to be false at compile time
5372   auto PredIsKnownFalse = [&](const SCEV *Expr,
5373                               const SCEV *ExtendedExpr) -> bool {
5374     return Expr != ExtendedExpr &&
5375            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5376   };
5377 
5378   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5379   if (PredIsKnownFalse(StartVal, StartExtended)) {
5380     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5381     return None;
5382   }
5383 
5384   // The Step is always Signed (because the overflow checks are either
5385   // NSSW or NUSW)
5386   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5387   if (PredIsKnownFalse(Accum, AccumExtended)) {
5388     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5389     return None;
5390   }
5391 
5392   auto AppendPredicate = [&](const SCEV *Expr,
5393                              const SCEV *ExtendedExpr) -> void {
5394     if (Expr != ExtendedExpr &&
5395         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5396       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5397       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5398       Predicates.push_back(Pred);
5399     }
5400   };
5401 
5402   AppendPredicate(StartVal, StartExtended);
5403   AppendPredicate(Accum, AccumExtended);
5404 
5405   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5406   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5407   // into NewAR if it will also add the runtime overflow checks specified in
5408   // Predicates.
5409   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5410 
5411   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5412       std::make_pair(NewAR, Predicates);
5413   // Remember the result of the analysis for this SCEV at this locayyytion.
5414   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5415   return PredRewrite;
5416 }
5417 
5418 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5419 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5420   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5421   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5422   if (!L)
5423     return None;
5424 
5425   // Check to see if we already analyzed this PHI.
5426   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5427   if (I != PredicatedSCEVRewrites.end()) {
5428     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5429         I->second;
5430     // Analysis was done before and failed to create an AddRec:
5431     if (Rewrite.first == SymbolicPHI)
5432       return None;
5433     // Analysis was done before and succeeded to create an AddRec under
5434     // a predicate:
5435     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5436     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5437     return Rewrite;
5438   }
5439 
5440   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5441     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5442 
5443   // Record in the cache that the analysis failed
5444   if (!Rewrite) {
5445     SmallVector<const SCEVPredicate *, 3> Predicates;
5446     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5447     return None;
5448   }
5449 
5450   return Rewrite;
5451 }
5452 
5453 // FIXME: This utility is currently required because the Rewriter currently
5454 // does not rewrite this expression:
5455 // {0, +, (sext ix (trunc iy to ix) to iy)}
5456 // into {0, +, %step},
5457 // even when the following Equal predicate exists:
5458 // "%step == (sext ix (trunc iy to ix) to iy)".
5459 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5460     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5461   if (AR1 == AR2)
5462     return true;
5463 
5464   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5465     if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5466         !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5467       return false;
5468     return true;
5469   };
5470 
5471   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5472       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5473     return false;
5474   return true;
5475 }
5476 
5477 /// A helper function for createAddRecFromPHI to handle simple cases.
5478 ///
5479 /// This function tries to find an AddRec expression for the simplest (yet most
5480 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5481 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5482 /// technique for finding the AddRec expression.
5483 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5484                                                       Value *BEValueV,
5485                                                       Value *StartValueV) {
5486   const Loop *L = LI.getLoopFor(PN->getParent());
5487   assert(L && L->getHeader() == PN->getParent());
5488   assert(BEValueV && StartValueV);
5489 
5490   auto BO = MatchBinaryOp(BEValueV, DT);
5491   if (!BO)
5492     return nullptr;
5493 
5494   if (BO->Opcode != Instruction::Add)
5495     return nullptr;
5496 
5497   const SCEV *Accum = nullptr;
5498   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5499     Accum = getSCEV(BO->RHS);
5500   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5501     Accum = getSCEV(BO->LHS);
5502 
5503   if (!Accum)
5504     return nullptr;
5505 
5506   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5507   if (BO->IsNUW)
5508     Flags = setFlags(Flags, SCEV::FlagNUW);
5509   if (BO->IsNSW)
5510     Flags = setFlags(Flags, SCEV::FlagNSW);
5511 
5512   const SCEV *StartVal = getSCEV(StartValueV);
5513   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5514   insertValueToMap(PN, PHISCEV);
5515 
5516   // We can add Flags to the post-inc expression only if we
5517   // know that it is *undefined behavior* for BEValueV to
5518   // overflow.
5519   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5520     assert(isLoopInvariant(Accum, L) &&
5521            "Accum is defined outside L, but is not invariant?");
5522     if (isAddRecNeverPoison(BEInst, L))
5523       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5524   }
5525 
5526   return PHISCEV;
5527 }
5528 
5529 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5530   const Loop *L = LI.getLoopFor(PN->getParent());
5531   if (!L || L->getHeader() != PN->getParent())
5532     return nullptr;
5533 
5534   // The loop may have multiple entrances or multiple exits; we can analyze
5535   // this phi as an addrec if it has a unique entry value and a unique
5536   // backedge value.
5537   Value *BEValueV = nullptr, *StartValueV = nullptr;
5538   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5539     Value *V = PN->getIncomingValue(i);
5540     if (L->contains(PN->getIncomingBlock(i))) {
5541       if (!BEValueV) {
5542         BEValueV = V;
5543       } else if (BEValueV != V) {
5544         BEValueV = nullptr;
5545         break;
5546       }
5547     } else if (!StartValueV) {
5548       StartValueV = V;
5549     } else if (StartValueV != V) {
5550       StartValueV = nullptr;
5551       break;
5552     }
5553   }
5554   if (!BEValueV || !StartValueV)
5555     return nullptr;
5556 
5557   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5558          "PHI node already processed?");
5559 
5560   // First, try to find AddRec expression without creating a fictituos symbolic
5561   // value for PN.
5562   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5563     return S;
5564 
5565   // Handle PHI node value symbolically.
5566   const SCEV *SymbolicName = getUnknown(PN);
5567   insertValueToMap(PN, SymbolicName);
5568 
5569   // Using this symbolic name for the PHI, analyze the value coming around
5570   // the back-edge.
5571   const SCEV *BEValue = getSCEV(BEValueV);
5572 
5573   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5574   // has a special value for the first iteration of the loop.
5575 
5576   // If the value coming around the backedge is an add with the symbolic
5577   // value we just inserted, then we found a simple induction variable!
5578   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5579     // If there is a single occurrence of the symbolic value, replace it
5580     // with a recurrence.
5581     unsigned FoundIndex = Add->getNumOperands();
5582     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5583       if (Add->getOperand(i) == SymbolicName)
5584         if (FoundIndex == e) {
5585           FoundIndex = i;
5586           break;
5587         }
5588 
5589     if (FoundIndex != Add->getNumOperands()) {
5590       // Create an add with everything but the specified operand.
5591       SmallVector<const SCEV *, 8> Ops;
5592       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5593         if (i != FoundIndex)
5594           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5595                                                              L, *this));
5596       const SCEV *Accum = getAddExpr(Ops);
5597 
5598       // This is not a valid addrec if the step amount is varying each
5599       // loop iteration, but is not itself an addrec in this loop.
5600       if (isLoopInvariant(Accum, L) ||
5601           (isa<SCEVAddRecExpr>(Accum) &&
5602            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5603         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5604 
5605         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5606           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5607             if (BO->IsNUW)
5608               Flags = setFlags(Flags, SCEV::FlagNUW);
5609             if (BO->IsNSW)
5610               Flags = setFlags(Flags, SCEV::FlagNSW);
5611           }
5612         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5613           // If the increment is an inbounds GEP, then we know the address
5614           // space cannot be wrapped around. We cannot make any guarantee
5615           // about signed or unsigned overflow because pointers are
5616           // unsigned but we may have a negative index from the base
5617           // pointer. We can guarantee that no unsigned wrap occurs if the
5618           // indices form a positive value.
5619           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5620             Flags = setFlags(Flags, SCEV::FlagNW);
5621 
5622             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5623             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5624               Flags = setFlags(Flags, SCEV::FlagNUW);
5625           }
5626 
5627           // We cannot transfer nuw and nsw flags from subtraction
5628           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5629           // for instance.
5630         }
5631 
5632         const SCEV *StartVal = getSCEV(StartValueV);
5633         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5634 
5635         // Okay, for the entire analysis of this edge we assumed the PHI
5636         // to be symbolic.  We now need to go back and purge all of the
5637         // entries for the scalars that use the symbolic expression.
5638         forgetMemoizedResults(SymbolicName);
5639         insertValueToMap(PN, PHISCEV);
5640 
5641         // We can add Flags to the post-inc expression only if we
5642         // know that it is *undefined behavior* for BEValueV to
5643         // overflow.
5644         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5645           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5646             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5647 
5648         return PHISCEV;
5649       }
5650     }
5651   } else {
5652     // Otherwise, this could be a loop like this:
5653     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5654     // In this case, j = {1,+,1}  and BEValue is j.
5655     // Because the other in-value of i (0) fits the evolution of BEValue
5656     // i really is an addrec evolution.
5657     //
5658     // We can generalize this saying that i is the shifted value of BEValue
5659     // by one iteration:
5660     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5661     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5662     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5663     if (Shifted != getCouldNotCompute() &&
5664         Start != getCouldNotCompute()) {
5665       const SCEV *StartVal = getSCEV(StartValueV);
5666       if (Start == StartVal) {
5667         // Okay, for the entire analysis of this edge we assumed the PHI
5668         // to be symbolic.  We now need to go back and purge all of the
5669         // entries for the scalars that use the symbolic expression.
5670         forgetMemoizedResults(SymbolicName);
5671         insertValueToMap(PN, Shifted);
5672         return Shifted;
5673       }
5674     }
5675   }
5676 
5677   // Remove the temporary PHI node SCEV that has been inserted while intending
5678   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5679   // as it will prevent later (possibly simpler) SCEV expressions to be added
5680   // to the ValueExprMap.
5681   eraseValueFromMap(PN);
5682 
5683   return nullptr;
5684 }
5685 
5686 // Checks if the SCEV S is available at BB.  S is considered available at BB
5687 // if S can be materialized at BB without introducing a fault.
5688 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5689                                BasicBlock *BB) {
5690   struct CheckAvailable {
5691     bool TraversalDone = false;
5692     bool Available = true;
5693 
5694     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5695     BasicBlock *BB = nullptr;
5696     DominatorTree &DT;
5697 
5698     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5699       : L(L), BB(BB), DT(DT) {}
5700 
5701     bool setUnavailable() {
5702       TraversalDone = true;
5703       Available = false;
5704       return false;
5705     }
5706 
5707     bool follow(const SCEV *S) {
5708       switch (S->getSCEVType()) {
5709       case scConstant:
5710       case scPtrToInt:
5711       case scTruncate:
5712       case scZeroExtend:
5713       case scSignExtend:
5714       case scAddExpr:
5715       case scMulExpr:
5716       case scUMaxExpr:
5717       case scSMaxExpr:
5718       case scUMinExpr:
5719       case scSMinExpr:
5720       case scSequentialUMinExpr:
5721         // These expressions are available if their operand(s) is/are.
5722         return true;
5723 
5724       case scAddRecExpr: {
5725         // We allow add recurrences that are on the loop BB is in, or some
5726         // outer loop.  This guarantees availability because the value of the
5727         // add recurrence at BB is simply the "current" value of the induction
5728         // variable.  We can relax this in the future; for instance an add
5729         // recurrence on a sibling dominating loop is also available at BB.
5730         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5731         if (L && (ARLoop == L || ARLoop->contains(L)))
5732           return true;
5733 
5734         return setUnavailable();
5735       }
5736 
5737       case scUnknown: {
5738         // For SCEVUnknown, we check for simple dominance.
5739         const auto *SU = cast<SCEVUnknown>(S);
5740         Value *V = SU->getValue();
5741 
5742         if (isa<Argument>(V))
5743           return false;
5744 
5745         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5746           return false;
5747 
5748         return setUnavailable();
5749       }
5750 
5751       case scUDivExpr:
5752       case scCouldNotCompute:
5753         // We do not try to smart about these at all.
5754         return setUnavailable();
5755       }
5756       llvm_unreachable("Unknown SCEV kind!");
5757     }
5758 
5759     bool isDone() { return TraversalDone; }
5760   };
5761 
5762   CheckAvailable CA(L, BB, DT);
5763   SCEVTraversal<CheckAvailable> ST(CA);
5764 
5765   ST.visitAll(S);
5766   return CA.Available;
5767 }
5768 
5769 // Try to match a control flow sequence that branches out at BI and merges back
5770 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5771 // match.
5772 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5773                           Value *&C, Value *&LHS, Value *&RHS) {
5774   C = BI->getCondition();
5775 
5776   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5777   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5778 
5779   if (!LeftEdge.isSingleEdge())
5780     return false;
5781 
5782   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5783 
5784   Use &LeftUse = Merge->getOperandUse(0);
5785   Use &RightUse = Merge->getOperandUse(1);
5786 
5787   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5788     LHS = LeftUse;
5789     RHS = RightUse;
5790     return true;
5791   }
5792 
5793   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5794     LHS = RightUse;
5795     RHS = LeftUse;
5796     return true;
5797   }
5798 
5799   return false;
5800 }
5801 
5802 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5803   auto IsReachable =
5804       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5805   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5806     const Loop *L = LI.getLoopFor(PN->getParent());
5807 
5808     // We don't want to break LCSSA, even in a SCEV expression tree.
5809     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5810       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5811         return nullptr;
5812 
5813     // Try to match
5814     //
5815     //  br %cond, label %left, label %right
5816     // left:
5817     //  br label %merge
5818     // right:
5819     //  br label %merge
5820     // merge:
5821     //  V = phi [ %x, %left ], [ %y, %right ]
5822     //
5823     // as "select %cond, %x, %y"
5824 
5825     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5826     assert(IDom && "At least the entry block should dominate PN");
5827 
5828     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5829     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5830 
5831     if (BI && BI->isConditional() &&
5832         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5833         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5834         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5835       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5836   }
5837 
5838   return nullptr;
5839 }
5840 
5841 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5842   if (const SCEV *S = createAddRecFromPHI(PN))
5843     return S;
5844 
5845   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5846     return S;
5847 
5848   // If the PHI has a single incoming value, follow that value, unless the
5849   // PHI's incoming blocks are in a different loop, in which case doing so
5850   // risks breaking LCSSA form. Instcombine would normally zap these, but
5851   // it doesn't have DominatorTree information, so it may miss cases.
5852   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5853     if (LI.replacementPreservesLCSSAForm(PN, V))
5854       return getSCEV(V);
5855 
5856   // If it's not a loop phi, we can't handle it yet.
5857   return getUnknown(PN);
5858 }
5859 
5860 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5861                             SCEVTypes RootKind) {
5862   struct FindClosure {
5863     const SCEV *OperandToFind;
5864     const SCEVTypes RootKind; // Must be a sequential min/max expression.
5865     const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5866 
5867     bool Found = false;
5868 
5869     bool canRecurseInto(SCEVTypes Kind) const {
5870       // We can only recurse into the SCEV expression of the same effective type
5871       // as the type of our root SCEV expression, and into zero-extensions.
5872       return RootKind == Kind || NonSequentialRootKind == Kind ||
5873              scZeroExtend == Kind;
5874     };
5875 
5876     FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5877         : OperandToFind(OperandToFind), RootKind(RootKind),
5878           NonSequentialRootKind(
5879               SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5880                   RootKind)) {}
5881 
5882     bool follow(const SCEV *S) {
5883       Found = S == OperandToFind;
5884 
5885       return !isDone() && canRecurseInto(S->getSCEVType());
5886     }
5887 
5888     bool isDone() const { return Found; }
5889   };
5890 
5891   FindClosure FC(OperandToFind, RootKind);
5892   visitAll(Root, FC);
5893   return FC.Found;
5894 }
5895 
5896 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(
5897     Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) {
5898   // Try to match some simple smax or umax patterns.
5899   auto *ICI = Cond;
5900 
5901   Value *LHS = ICI->getOperand(0);
5902   Value *RHS = ICI->getOperand(1);
5903 
5904   switch (ICI->getPredicate()) {
5905   case ICmpInst::ICMP_SLT:
5906   case ICmpInst::ICMP_SLE:
5907   case ICmpInst::ICMP_ULT:
5908   case ICmpInst::ICMP_ULE:
5909     std::swap(LHS, RHS);
5910     LLVM_FALLTHROUGH;
5911   case ICmpInst::ICMP_SGT:
5912   case ICmpInst::ICMP_SGE:
5913   case ICmpInst::ICMP_UGT:
5914   case ICmpInst::ICMP_UGE:
5915     // a > b ? a+x : b+x  ->  max(a, b)+x
5916     // a > b ? b+x : a+x  ->  min(a, b)+x
5917     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5918       bool Signed = ICI->isSigned();
5919       const SCEV *LA = getSCEV(TrueVal);
5920       const SCEV *RA = getSCEV(FalseVal);
5921       const SCEV *LS = getSCEV(LHS);
5922       const SCEV *RS = getSCEV(RHS);
5923       if (LA->getType()->isPointerTy()) {
5924         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5925         // Need to make sure we can't produce weird expressions involving
5926         // negated pointers.
5927         if (LA == LS && RA == RS)
5928           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5929         if (LA == RS && RA == LS)
5930           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5931       }
5932       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5933         if (Op->getType()->isPointerTy()) {
5934           Op = getLosslessPtrToIntExpr(Op);
5935           if (isa<SCEVCouldNotCompute>(Op))
5936             return Op;
5937         }
5938         if (Signed)
5939           Op = getNoopOrSignExtend(Op, I->getType());
5940         else
5941           Op = getNoopOrZeroExtend(Op, I->getType());
5942         return Op;
5943       };
5944       LS = CoerceOperand(LS);
5945       RS = CoerceOperand(RS);
5946       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
5947         break;
5948       const SCEV *LDiff = getMinusSCEV(LA, LS);
5949       const SCEV *RDiff = getMinusSCEV(RA, RS);
5950       if (LDiff == RDiff)
5951         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
5952                           LDiff);
5953       LDiff = getMinusSCEV(LA, RS);
5954       RDiff = getMinusSCEV(RA, LS);
5955       if (LDiff == RDiff)
5956         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
5957                           LDiff);
5958     }
5959     break;
5960   case ICmpInst::ICMP_NE:
5961     // x != 0 ? x+y : C+y  ->  x == 0 ? C+y : x+y
5962     std::swap(TrueVal, FalseVal);
5963     LLVM_FALLTHROUGH;
5964   case ICmpInst::ICMP_EQ:
5965     // x == 0 ? C+y : x+y  ->  umax(x, C)+y   iff C u<= 1
5966     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5967         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5968       const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5969       const SCEV *TrueValExpr = getSCEV(TrueVal);    // C+y
5970       const SCEV *FalseValExpr = getSCEV(FalseVal);  // x+y
5971       const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
5972       const SCEV *C = getMinusSCEV(TrueValExpr, Y);  // C = (C+y)-y
5973       if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
5974         return getAddExpr(getUMaxExpr(X, C), Y);
5975     }
5976     // x == 0 ? 0 : umin    (..., x, ...)  ->  umin_seq(x, umin    (...))
5977     // x == 0 ? 0 : umin_seq(..., x, ...)  ->  umin_seq(x, umin_seq(...))
5978     // x == 0 ? 0 : umin    (..., umin_seq(..., x, ...), ...)
5979     //                    ->  umin_seq(x, umin (..., umin_seq(...), ...))
5980     if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
5981         isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
5982       const SCEV *X = getSCEV(LHS);
5983       while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
5984         X = ZExt->getOperand();
5985       if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) {
5986         const SCEV *FalseValExpr = getSCEV(FalseVal);
5987         if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
5988           return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr,
5989                              /*Sequential=*/true);
5990       }
5991     }
5992     break;
5993   default:
5994     break;
5995   }
5996 
5997   return getUnknown(I);
5998 }
5999 
6000 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6001     Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6002   // For now, only deal with i1-typed `select`s.
6003   if (!V->getType()->isIntegerTy(1) || !Cond->getType()->isIntegerTy(1) ||
6004       !TrueVal->getType()->isIntegerTy(1) ||
6005       !FalseVal->getType()->isIntegerTy(1))
6006     return getUnknown(V);
6007 
6008   // i1 cond ? i1 x : i1 C  -->  C + (i1  cond ? (i1 x - i1 C) : i1 0)
6009   //                        -->  C + (umin_seq  cond, x - C)
6010   //
6011   // i1 cond ? i1 C : i1 x  -->  C + (i1  cond ? i1 0 : (i1 x - i1 C))
6012   //                        -->  C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6013   //                        -->  C + (umin_seq ~cond, x - C)
6014   if (isa<ConstantInt>(TrueVal) || isa<ConstantInt>(FalseVal)) {
6015     const SCEV *CondExpr = getSCEV(Cond);
6016     const SCEV *TrueExpr = getSCEV(TrueVal);
6017     const SCEV *FalseExpr = getSCEV(FalseVal);
6018     const SCEV *X, *C;
6019     if (isa<ConstantInt>(TrueVal)) {
6020       CondExpr = getNotSCEV(CondExpr);
6021       X = FalseExpr;
6022       C = TrueExpr;
6023     } else {
6024       X = TrueExpr;
6025       C = FalseExpr;
6026     }
6027     return getAddExpr(
6028         C, getUMinExpr(CondExpr, getMinusSCEV(X, C), /*Sequential=*/true));
6029   }
6030 
6031   return getUnknown(V);
6032 }
6033 
6034 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6035                                                       Value *TrueVal,
6036                                                       Value *FalseVal) {
6037   // Handle "constant" branch or select. This can occur for instance when a
6038   // loop pass transforms an inner loop and moves on to process the outer loop.
6039   if (auto *CI = dyn_cast<ConstantInt>(Cond))
6040     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6041 
6042   if (auto *I = dyn_cast<Instruction>(V)) {
6043     if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6044       const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond(
6045           I, ICI, TrueVal, FalseVal);
6046       if (!isa<SCEVUnknown>(S))
6047         return S;
6048     }
6049   }
6050 
6051   return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6052 }
6053 
6054 /// Expand GEP instructions into add and multiply operations. This allows them
6055 /// to be analyzed by regular SCEV code.
6056 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6057   // Don't attempt to analyze GEPs over unsized objects.
6058   if (!GEP->getSourceElementType()->isSized())
6059     return getUnknown(GEP);
6060 
6061   SmallVector<const SCEV *, 4> IndexExprs;
6062   for (Value *Index : GEP->indices())
6063     IndexExprs.push_back(getSCEV(Index));
6064   return getGEPExpr(GEP, IndexExprs);
6065 }
6066 
6067 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
6068   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6069     return C->getAPInt().countTrailingZeros();
6070 
6071   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
6072     return GetMinTrailingZeros(I->getOperand());
6073 
6074   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
6075     return std::min(GetMinTrailingZeros(T->getOperand()),
6076                     (uint32_t)getTypeSizeInBits(T->getType()));
6077 
6078   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
6079     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6080     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6081                ? getTypeSizeInBits(E->getType())
6082                : OpRes;
6083   }
6084 
6085   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
6086     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6087     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6088                ? getTypeSizeInBits(E->getType())
6089                : OpRes;
6090   }
6091 
6092   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
6093     // The result is the min of all operands results.
6094     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6095     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6096       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6097     return MinOpRes;
6098   }
6099 
6100   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
6101     // The result is the sum of all operands results.
6102     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
6103     uint32_t BitWidth = getTypeSizeInBits(M->getType());
6104     for (unsigned i = 1, e = M->getNumOperands();
6105          SumOpRes != BitWidth && i != e; ++i)
6106       SumOpRes =
6107           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
6108     return SumOpRes;
6109   }
6110 
6111   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
6112     // The result is the min of all operands results.
6113     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6114     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6115       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6116     return MinOpRes;
6117   }
6118 
6119   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
6120     // The result is the min of all operands results.
6121     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6122     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6123       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6124     return MinOpRes;
6125   }
6126 
6127   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
6128     // The result is the min of all operands results.
6129     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6130     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6131       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6132     return MinOpRes;
6133   }
6134 
6135   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6136     // For a SCEVUnknown, ask ValueTracking.
6137     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
6138     return Known.countMinTrailingZeros();
6139   }
6140 
6141   // SCEVUDivExpr
6142   return 0;
6143 }
6144 
6145 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
6146   auto I = MinTrailingZerosCache.find(S);
6147   if (I != MinTrailingZerosCache.end())
6148     return I->second;
6149 
6150   uint32_t Result = GetMinTrailingZerosImpl(S);
6151   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
6152   assert(InsertPair.second && "Should insert a new key");
6153   return InsertPair.first->second;
6154 }
6155 
6156 /// Helper method to assign a range to V from metadata present in the IR.
6157 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6158   if (Instruction *I = dyn_cast<Instruction>(V))
6159     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6160       return getConstantRangeFromMetadata(*MD);
6161 
6162   return None;
6163 }
6164 
6165 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6166                                      SCEV::NoWrapFlags Flags) {
6167   if (AddRec->getNoWrapFlags(Flags) != Flags) {
6168     AddRec->setNoWrapFlags(Flags);
6169     UnsignedRanges.erase(AddRec);
6170     SignedRanges.erase(AddRec);
6171   }
6172 }
6173 
6174 ConstantRange ScalarEvolution::
6175 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6176   const DataLayout &DL = getDataLayout();
6177 
6178   unsigned BitWidth = getTypeSizeInBits(U->getType());
6179   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6180 
6181   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6182   // use information about the trip count to improve our available range.  Note
6183   // that the trip count independent cases are already handled by known bits.
6184   // WARNING: The definition of recurrence used here is subtly different than
6185   // the one used by AddRec (and thus most of this file).  Step is allowed to
6186   // be arbitrarily loop varying here, where AddRec allows only loop invariant
6187   // and other addrecs in the same loop (for non-affine addrecs).  The code
6188   // below intentionally handles the case where step is not loop invariant.
6189   auto *P = dyn_cast<PHINode>(U->getValue());
6190   if (!P)
6191     return FullSet;
6192 
6193   // Make sure that no Phi input comes from an unreachable block. Otherwise,
6194   // even the values that are not available in these blocks may come from them,
6195   // and this leads to false-positive recurrence test.
6196   for (auto *Pred : predecessors(P->getParent()))
6197     if (!DT.isReachableFromEntry(Pred))
6198       return FullSet;
6199 
6200   BinaryOperator *BO;
6201   Value *Start, *Step;
6202   if (!matchSimpleRecurrence(P, BO, Start, Step))
6203     return FullSet;
6204 
6205   // If we found a recurrence in reachable code, we must be in a loop. Note
6206   // that BO might be in some subloop of L, and that's completely okay.
6207   auto *L = LI.getLoopFor(P->getParent());
6208   assert(L && L->getHeader() == P->getParent());
6209   if (!L->contains(BO->getParent()))
6210     // NOTE: This bailout should be an assert instead.  However, asserting
6211     // the condition here exposes a case where LoopFusion is querying SCEV
6212     // with malformed loop information during the midst of the transform.
6213     // There doesn't appear to be an obvious fix, so for the moment bailout
6214     // until the caller issue can be fixed.  PR49566 tracks the bug.
6215     return FullSet;
6216 
6217   // TODO: Extend to other opcodes such as mul, and div
6218   switch (BO->getOpcode()) {
6219   default:
6220     return FullSet;
6221   case Instruction::AShr:
6222   case Instruction::LShr:
6223   case Instruction::Shl:
6224     break;
6225   };
6226 
6227   if (BO->getOperand(0) != P)
6228     // TODO: Handle the power function forms some day.
6229     return FullSet;
6230 
6231   unsigned TC = getSmallConstantMaxTripCount(L);
6232   if (!TC || TC >= BitWidth)
6233     return FullSet;
6234 
6235   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6236   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6237   assert(KnownStart.getBitWidth() == BitWidth &&
6238          KnownStep.getBitWidth() == BitWidth);
6239 
6240   // Compute total shift amount, being careful of overflow and bitwidths.
6241   auto MaxShiftAmt = KnownStep.getMaxValue();
6242   APInt TCAP(BitWidth, TC-1);
6243   bool Overflow = false;
6244   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6245   if (Overflow)
6246     return FullSet;
6247 
6248   switch (BO->getOpcode()) {
6249   default:
6250     llvm_unreachable("filtered out above");
6251   case Instruction::AShr: {
6252     // For each ashr, three cases:
6253     //   shift = 0 => unchanged value
6254     //   saturation => 0 or -1
6255     //   other => a value closer to zero (of the same sign)
6256     // Thus, the end value is closer to zero than the start.
6257     auto KnownEnd = KnownBits::ashr(KnownStart,
6258                                     KnownBits::makeConstant(TotalShift));
6259     if (KnownStart.isNonNegative())
6260       // Analogous to lshr (simply not yet canonicalized)
6261       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6262                                         KnownStart.getMaxValue() + 1);
6263     if (KnownStart.isNegative())
6264       // End >=u Start && End <=s Start
6265       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6266                                         KnownEnd.getMaxValue() + 1);
6267     break;
6268   }
6269   case Instruction::LShr: {
6270     // For each lshr, three cases:
6271     //   shift = 0 => unchanged value
6272     //   saturation => 0
6273     //   other => a smaller positive number
6274     // Thus, the low end of the unsigned range is the last value produced.
6275     auto KnownEnd = KnownBits::lshr(KnownStart,
6276                                     KnownBits::makeConstant(TotalShift));
6277     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6278                                       KnownStart.getMaxValue() + 1);
6279   }
6280   case Instruction::Shl: {
6281     // Iff no bits are shifted out, value increases on every shift.
6282     auto KnownEnd = KnownBits::shl(KnownStart,
6283                                    KnownBits::makeConstant(TotalShift));
6284     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6285       return ConstantRange(KnownStart.getMinValue(),
6286                            KnownEnd.getMaxValue() + 1);
6287     break;
6288   }
6289   };
6290   return FullSet;
6291 }
6292 
6293 /// Determine the range for a particular SCEV.  If SignHint is
6294 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6295 /// with a "cleaner" unsigned (resp. signed) representation.
6296 const ConstantRange &
6297 ScalarEvolution::getRangeRef(const SCEV *S,
6298                              ScalarEvolution::RangeSignHint SignHint) {
6299   DenseMap<const SCEV *, ConstantRange> &Cache =
6300       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6301                                                        : SignedRanges;
6302   ConstantRange::PreferredRangeType RangeType =
6303       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
6304           ? ConstantRange::Unsigned : ConstantRange::Signed;
6305 
6306   // See if we've computed this range already.
6307   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6308   if (I != Cache.end())
6309     return I->second;
6310 
6311   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6312     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6313 
6314   unsigned BitWidth = getTypeSizeInBits(S->getType());
6315   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6316   using OBO = OverflowingBinaryOperator;
6317 
6318   // If the value has known zeros, the maximum value will have those known zeros
6319   // as well.
6320   uint32_t TZ = GetMinTrailingZeros(S);
6321   if (TZ != 0) {
6322     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6323       ConservativeResult =
6324           ConstantRange(APInt::getMinValue(BitWidth),
6325                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6326     else
6327       ConservativeResult = ConstantRange(
6328           APInt::getSignedMinValue(BitWidth),
6329           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6330   }
6331 
6332   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6333     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6334     unsigned WrapType = OBO::AnyWrap;
6335     if (Add->hasNoSignedWrap())
6336       WrapType |= OBO::NoSignedWrap;
6337     if (Add->hasNoUnsignedWrap())
6338       WrapType |= OBO::NoUnsignedWrap;
6339     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6340       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6341                           WrapType, RangeType);
6342     return setRange(Add, SignHint,
6343                     ConservativeResult.intersectWith(X, RangeType));
6344   }
6345 
6346   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6347     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6348     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6349       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6350     return setRange(Mul, SignHint,
6351                     ConservativeResult.intersectWith(X, RangeType));
6352   }
6353 
6354   if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) {
6355     Intrinsic::ID ID;
6356     switch (S->getSCEVType()) {
6357     case scUMaxExpr:
6358       ID = Intrinsic::umax;
6359       break;
6360     case scSMaxExpr:
6361       ID = Intrinsic::smax;
6362       break;
6363     case scUMinExpr:
6364     case scSequentialUMinExpr:
6365       ID = Intrinsic::umin;
6366       break;
6367     case scSMinExpr:
6368       ID = Intrinsic::smin;
6369       break;
6370     default:
6371       llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6372     }
6373 
6374     const auto *NAry = cast<SCEVNAryExpr>(S);
6375     ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint);
6376     for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6377       X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)});
6378     return setRange(S, SignHint,
6379                     ConservativeResult.intersectWith(X, RangeType));
6380   }
6381 
6382   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6383     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6384     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6385     return setRange(UDiv, SignHint,
6386                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6387   }
6388 
6389   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6390     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6391     return setRange(ZExt, SignHint,
6392                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6393                                                      RangeType));
6394   }
6395 
6396   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6397     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6398     return setRange(SExt, SignHint,
6399                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6400                                                      RangeType));
6401   }
6402 
6403   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6404     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6405     return setRange(PtrToInt, SignHint, X);
6406   }
6407 
6408   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6409     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6410     return setRange(Trunc, SignHint,
6411                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6412                                                      RangeType));
6413   }
6414 
6415   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6416     // If there's no unsigned wrap, the value will never be less than its
6417     // initial value.
6418     if (AddRec->hasNoUnsignedWrap()) {
6419       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6420       if (!UnsignedMinValue.isZero())
6421         ConservativeResult = ConservativeResult.intersectWith(
6422             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6423     }
6424 
6425     // If there's no signed wrap, and all the operands except initial value have
6426     // the same sign or zero, the value won't ever be:
6427     // 1: smaller than initial value if operands are non negative,
6428     // 2: bigger than initial value if operands are non positive.
6429     // For both cases, value can not cross signed min/max boundary.
6430     if (AddRec->hasNoSignedWrap()) {
6431       bool AllNonNeg = true;
6432       bool AllNonPos = true;
6433       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6434         if (!isKnownNonNegative(AddRec->getOperand(i)))
6435           AllNonNeg = false;
6436         if (!isKnownNonPositive(AddRec->getOperand(i)))
6437           AllNonPos = false;
6438       }
6439       if (AllNonNeg)
6440         ConservativeResult = ConservativeResult.intersectWith(
6441             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6442                                        APInt::getSignedMinValue(BitWidth)),
6443             RangeType);
6444       else if (AllNonPos)
6445         ConservativeResult = ConservativeResult.intersectWith(
6446             ConstantRange::getNonEmpty(
6447                 APInt::getSignedMinValue(BitWidth),
6448                 getSignedRangeMax(AddRec->getStart()) + 1),
6449             RangeType);
6450     }
6451 
6452     // TODO: non-affine addrec
6453     if (AddRec->isAffine()) {
6454       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6455       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6456           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6457         auto RangeFromAffine = getRangeForAffineAR(
6458             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6459             BitWidth);
6460         ConservativeResult =
6461             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6462 
6463         auto RangeFromFactoring = getRangeViaFactoring(
6464             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6465             BitWidth);
6466         ConservativeResult =
6467             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6468       }
6469 
6470       // Now try symbolic BE count and more powerful methods.
6471       if (UseExpensiveRangeSharpening) {
6472         const SCEV *SymbolicMaxBECount =
6473             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6474         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6475             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6476             AddRec->hasNoSelfWrap()) {
6477           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6478               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6479           ConservativeResult =
6480               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6481         }
6482       }
6483     }
6484 
6485     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6486   }
6487 
6488   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6489 
6490     // Check if the IR explicitly contains !range metadata.
6491     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6492     if (MDRange.hasValue())
6493       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6494                                                             RangeType);
6495 
6496     // Use facts about recurrences in the underlying IR.  Note that add
6497     // recurrences are AddRecExprs and thus don't hit this path.  This
6498     // primarily handles shift recurrences.
6499     auto CR = getRangeForUnknownRecurrence(U);
6500     ConservativeResult = ConservativeResult.intersectWith(CR);
6501 
6502     // See if ValueTracking can give us a useful range.
6503     const DataLayout &DL = getDataLayout();
6504     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6505     if (Known.getBitWidth() != BitWidth)
6506       Known = Known.zextOrTrunc(BitWidth);
6507 
6508     // ValueTracking may be able to compute a tighter result for the number of
6509     // sign bits than for the value of those sign bits.
6510     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6511     if (U->getType()->isPointerTy()) {
6512       // If the pointer size is larger than the index size type, this can cause
6513       // NS to be larger than BitWidth. So compensate for this.
6514       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6515       int ptrIdxDiff = ptrSize - BitWidth;
6516       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6517         NS -= ptrIdxDiff;
6518     }
6519 
6520     if (NS > 1) {
6521       // If we know any of the sign bits, we know all of the sign bits.
6522       if (!Known.Zero.getHiBits(NS).isZero())
6523         Known.Zero.setHighBits(NS);
6524       if (!Known.One.getHiBits(NS).isZero())
6525         Known.One.setHighBits(NS);
6526     }
6527 
6528     if (Known.getMinValue() != Known.getMaxValue() + 1)
6529       ConservativeResult = ConservativeResult.intersectWith(
6530           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6531           RangeType);
6532     if (NS > 1)
6533       ConservativeResult = ConservativeResult.intersectWith(
6534           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6535                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6536           RangeType);
6537 
6538     // A range of Phi is a subset of union of all ranges of its input.
6539     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6540       // Make sure that we do not run over cycled Phis.
6541       if (PendingPhiRanges.insert(Phi).second) {
6542         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6543         for (auto &Op : Phi->operands()) {
6544           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6545           RangeFromOps = RangeFromOps.unionWith(OpRange);
6546           // No point to continue if we already have a full set.
6547           if (RangeFromOps.isFullSet())
6548             break;
6549         }
6550         ConservativeResult =
6551             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6552         bool Erased = PendingPhiRanges.erase(Phi);
6553         assert(Erased && "Failed to erase Phi properly?");
6554         (void) Erased;
6555       }
6556     }
6557 
6558     return setRange(U, SignHint, std::move(ConservativeResult));
6559   }
6560 
6561   return setRange(S, SignHint, std::move(ConservativeResult));
6562 }
6563 
6564 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6565 // values that the expression can take. Initially, the expression has a value
6566 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6567 // argument defines if we treat Step as signed or unsigned.
6568 static ConstantRange getRangeForAffineARHelper(APInt Step,
6569                                                const ConstantRange &StartRange,
6570                                                const APInt &MaxBECount,
6571                                                unsigned BitWidth, bool Signed) {
6572   // If either Step or MaxBECount is 0, then the expression won't change, and we
6573   // just need to return the initial range.
6574   if (Step == 0 || MaxBECount == 0)
6575     return StartRange;
6576 
6577   // If we don't know anything about the initial value (i.e. StartRange is
6578   // FullRange), then we don't know anything about the final range either.
6579   // Return FullRange.
6580   if (StartRange.isFullSet())
6581     return ConstantRange::getFull(BitWidth);
6582 
6583   // If Step is signed and negative, then we use its absolute value, but we also
6584   // note that we're moving in the opposite direction.
6585   bool Descending = Signed && Step.isNegative();
6586 
6587   if (Signed)
6588     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6589     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6590     // This equations hold true due to the well-defined wrap-around behavior of
6591     // APInt.
6592     Step = Step.abs();
6593 
6594   // Check if Offset is more than full span of BitWidth. If it is, the
6595   // expression is guaranteed to overflow.
6596   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6597     return ConstantRange::getFull(BitWidth);
6598 
6599   // Offset is by how much the expression can change. Checks above guarantee no
6600   // overflow here.
6601   APInt Offset = Step * MaxBECount;
6602 
6603   // Minimum value of the final range will match the minimal value of StartRange
6604   // if the expression is increasing and will be decreased by Offset otherwise.
6605   // Maximum value of the final range will match the maximal value of StartRange
6606   // if the expression is decreasing and will be increased by Offset otherwise.
6607   APInt StartLower = StartRange.getLower();
6608   APInt StartUpper = StartRange.getUpper() - 1;
6609   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6610                                    : (StartUpper + std::move(Offset));
6611 
6612   // It's possible that the new minimum/maximum value will fall into the initial
6613   // range (due to wrap around). This means that the expression can take any
6614   // value in this bitwidth, and we have to return full range.
6615   if (StartRange.contains(MovedBoundary))
6616     return ConstantRange::getFull(BitWidth);
6617 
6618   APInt NewLower =
6619       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6620   APInt NewUpper =
6621       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6622   NewUpper += 1;
6623 
6624   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6625   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6626 }
6627 
6628 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6629                                                    const SCEV *Step,
6630                                                    const SCEV *MaxBECount,
6631                                                    unsigned BitWidth) {
6632   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6633          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6634          "Precondition!");
6635 
6636   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6637   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6638 
6639   // First, consider step signed.
6640   ConstantRange StartSRange = getSignedRange(Start);
6641   ConstantRange StepSRange = getSignedRange(Step);
6642 
6643   // If Step can be both positive and negative, we need to find ranges for the
6644   // maximum absolute step values in both directions and union them.
6645   ConstantRange SR =
6646       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6647                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6648   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6649                                               StartSRange, MaxBECountValue,
6650                                               BitWidth, /* Signed = */ true));
6651 
6652   // Next, consider step unsigned.
6653   ConstantRange UR = getRangeForAffineARHelper(
6654       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6655       MaxBECountValue, BitWidth, /* Signed = */ false);
6656 
6657   // Finally, intersect signed and unsigned ranges.
6658   return SR.intersectWith(UR, ConstantRange::Smallest);
6659 }
6660 
6661 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6662     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6663     ScalarEvolution::RangeSignHint SignHint) {
6664   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6665   assert(AddRec->hasNoSelfWrap() &&
6666          "This only works for non-self-wrapping AddRecs!");
6667   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6668   const SCEV *Step = AddRec->getStepRecurrence(*this);
6669   // Only deal with constant step to save compile time.
6670   if (!isa<SCEVConstant>(Step))
6671     return ConstantRange::getFull(BitWidth);
6672   // Let's make sure that we can prove that we do not self-wrap during
6673   // MaxBECount iterations. We need this because MaxBECount is a maximum
6674   // iteration count estimate, and we might infer nw from some exit for which we
6675   // do not know max exit count (or any other side reasoning).
6676   // TODO: Turn into assert at some point.
6677   if (getTypeSizeInBits(MaxBECount->getType()) >
6678       getTypeSizeInBits(AddRec->getType()))
6679     return ConstantRange::getFull(BitWidth);
6680   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6681   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6682   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6683   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6684   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6685                                          MaxItersWithoutWrap))
6686     return ConstantRange::getFull(BitWidth);
6687 
6688   ICmpInst::Predicate LEPred =
6689       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6690   ICmpInst::Predicate GEPred =
6691       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6692   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6693 
6694   // We know that there is no self-wrap. Let's take Start and End values and
6695   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6696   // the iteration. They either lie inside the range [Min(Start, End),
6697   // Max(Start, End)] or outside it:
6698   //
6699   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6700   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6701   //
6702   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6703   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6704   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6705   // Start <= End and step is positive, or Start >= End and step is negative.
6706   const SCEV *Start = AddRec->getStart();
6707   ConstantRange StartRange = getRangeRef(Start, SignHint);
6708   ConstantRange EndRange = getRangeRef(End, SignHint);
6709   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6710   // If they already cover full iteration space, we will know nothing useful
6711   // even if we prove what we want to prove.
6712   if (RangeBetween.isFullSet())
6713     return RangeBetween;
6714   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6715   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6716                                : RangeBetween.isWrappedSet();
6717   if (IsWrappedSet)
6718     return ConstantRange::getFull(BitWidth);
6719 
6720   if (isKnownPositive(Step) &&
6721       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6722     return RangeBetween;
6723   else if (isKnownNegative(Step) &&
6724            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6725     return RangeBetween;
6726   return ConstantRange::getFull(BitWidth);
6727 }
6728 
6729 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6730                                                     const SCEV *Step,
6731                                                     const SCEV *MaxBECount,
6732                                                     unsigned BitWidth) {
6733   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6734   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6735 
6736   struct SelectPattern {
6737     Value *Condition = nullptr;
6738     APInt TrueValue;
6739     APInt FalseValue;
6740 
6741     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6742                            const SCEV *S) {
6743       Optional<unsigned> CastOp;
6744       APInt Offset(BitWidth, 0);
6745 
6746       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6747              "Should be!");
6748 
6749       // Peel off a constant offset:
6750       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6751         // In the future we could consider being smarter here and handle
6752         // {Start+Step,+,Step} too.
6753         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6754           return;
6755 
6756         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6757         S = SA->getOperand(1);
6758       }
6759 
6760       // Peel off a cast operation
6761       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6762         CastOp = SCast->getSCEVType();
6763         S = SCast->getOperand();
6764       }
6765 
6766       using namespace llvm::PatternMatch;
6767 
6768       auto *SU = dyn_cast<SCEVUnknown>(S);
6769       const APInt *TrueVal, *FalseVal;
6770       if (!SU ||
6771           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6772                                           m_APInt(FalseVal)))) {
6773         Condition = nullptr;
6774         return;
6775       }
6776 
6777       TrueValue = *TrueVal;
6778       FalseValue = *FalseVal;
6779 
6780       // Re-apply the cast we peeled off earlier
6781       if (CastOp.hasValue())
6782         switch (*CastOp) {
6783         default:
6784           llvm_unreachable("Unknown SCEV cast type!");
6785 
6786         case scTruncate:
6787           TrueValue = TrueValue.trunc(BitWidth);
6788           FalseValue = FalseValue.trunc(BitWidth);
6789           break;
6790         case scZeroExtend:
6791           TrueValue = TrueValue.zext(BitWidth);
6792           FalseValue = FalseValue.zext(BitWidth);
6793           break;
6794         case scSignExtend:
6795           TrueValue = TrueValue.sext(BitWidth);
6796           FalseValue = FalseValue.sext(BitWidth);
6797           break;
6798         }
6799 
6800       // Re-apply the constant offset we peeled off earlier
6801       TrueValue += Offset;
6802       FalseValue += Offset;
6803     }
6804 
6805     bool isRecognized() { return Condition != nullptr; }
6806   };
6807 
6808   SelectPattern StartPattern(*this, BitWidth, Start);
6809   if (!StartPattern.isRecognized())
6810     return ConstantRange::getFull(BitWidth);
6811 
6812   SelectPattern StepPattern(*this, BitWidth, Step);
6813   if (!StepPattern.isRecognized())
6814     return ConstantRange::getFull(BitWidth);
6815 
6816   if (StartPattern.Condition != StepPattern.Condition) {
6817     // We don't handle this case today; but we could, by considering four
6818     // possibilities below instead of two. I'm not sure if there are cases where
6819     // that will help over what getRange already does, though.
6820     return ConstantRange::getFull(BitWidth);
6821   }
6822 
6823   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6824   // construct arbitrary general SCEV expressions here.  This function is called
6825   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6826   // say) can end up caching a suboptimal value.
6827 
6828   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6829   // C2352 and C2512 (otherwise it isn't needed).
6830 
6831   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6832   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6833   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6834   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6835 
6836   ConstantRange TrueRange =
6837       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6838   ConstantRange FalseRange =
6839       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6840 
6841   return TrueRange.unionWith(FalseRange);
6842 }
6843 
6844 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6845   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6846   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6847 
6848   // Return early if there are no flags to propagate to the SCEV.
6849   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6850   if (BinOp->hasNoUnsignedWrap())
6851     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6852   if (BinOp->hasNoSignedWrap())
6853     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6854   if (Flags == SCEV::FlagAnyWrap)
6855     return SCEV::FlagAnyWrap;
6856 
6857   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6858 }
6859 
6860 const Instruction *
6861 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
6862   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
6863     return &*AddRec->getLoop()->getHeader()->begin();
6864   if (auto *U = dyn_cast<SCEVUnknown>(S))
6865     if (auto *I = dyn_cast<Instruction>(U->getValue()))
6866       return I;
6867   return nullptr;
6868 }
6869 
6870 /// Fills \p Ops with unique operands of \p S, if it has operands. If not,
6871 /// \p Ops remains unmodified.
6872 static void collectUniqueOps(const SCEV *S,
6873                              SmallVectorImpl<const SCEV *> &Ops) {
6874   SmallPtrSet<const SCEV *, 4> Unique;
6875   auto InsertUnique = [&](const SCEV *S) {
6876     if (Unique.insert(S).second)
6877       Ops.push_back(S);
6878   };
6879   if (auto *S2 = dyn_cast<SCEVCastExpr>(S))
6880     for (auto *Op : S2->operands())
6881       InsertUnique(Op);
6882   else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S))
6883     for (auto *Op : S2->operands())
6884       InsertUnique(Op);
6885   else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S))
6886     for (auto *Op : S2->operands())
6887       InsertUnique(Op);
6888 }
6889 
6890 const Instruction *
6891 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
6892                                        bool &Precise) {
6893   Precise = true;
6894   // Do a bounded search of the def relation of the requested SCEVs.
6895   SmallSet<const SCEV *, 16> Visited;
6896   SmallVector<const SCEV *> Worklist;
6897   auto pushOp = [&](const SCEV *S) {
6898     if (!Visited.insert(S).second)
6899       return;
6900     // Threshold of 30 here is arbitrary.
6901     if (Visited.size() > 30) {
6902       Precise = false;
6903       return;
6904     }
6905     Worklist.push_back(S);
6906   };
6907 
6908   for (auto *S : Ops)
6909     pushOp(S);
6910 
6911   const Instruction *Bound = nullptr;
6912   while (!Worklist.empty()) {
6913     auto *S = Worklist.pop_back_val();
6914     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
6915       if (!Bound || DT.dominates(Bound, DefI))
6916         Bound = DefI;
6917     } else {
6918       SmallVector<const SCEV *, 4> Ops;
6919       collectUniqueOps(S, Ops);
6920       for (auto *Op : Ops)
6921         pushOp(Op);
6922     }
6923   }
6924   return Bound ? Bound : &*F.getEntryBlock().begin();
6925 }
6926 
6927 const Instruction *
6928 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
6929   bool Discard;
6930   return getDefiningScopeBound(Ops, Discard);
6931 }
6932 
6933 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
6934                                                         const Instruction *B) {
6935   if (A->getParent() == B->getParent() &&
6936       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
6937                                                  B->getIterator()))
6938     return true;
6939 
6940   auto *BLoop = LI.getLoopFor(B->getParent());
6941   if (BLoop && BLoop->getHeader() == B->getParent() &&
6942       BLoop->getLoopPreheader() == A->getParent() &&
6943       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
6944                                                  A->getParent()->end()) &&
6945       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
6946                                                  B->getIterator()))
6947     return true;
6948   return false;
6949 }
6950 
6951 
6952 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6953   // Only proceed if we can prove that I does not yield poison.
6954   if (!programUndefinedIfPoison(I))
6955     return false;
6956 
6957   // At this point we know that if I is executed, then it does not wrap
6958   // according to at least one of NSW or NUW. If I is not executed, then we do
6959   // not know if the calculation that I represents would wrap. Multiple
6960   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6961   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6962   // derived from other instructions that map to the same SCEV. We cannot make
6963   // that guarantee for cases where I is not executed. So we need to find a
6964   // upper bound on the defining scope for the SCEV, and prove that I is
6965   // executed every time we enter that scope.  When the bounding scope is a
6966   // loop (the common case), this is equivalent to proving I executes on every
6967   // iteration of that loop.
6968   SmallVector<const SCEV *> SCEVOps;
6969   for (const Use &Op : I->operands()) {
6970     // I could be an extractvalue from a call to an overflow intrinsic.
6971     // TODO: We can do better here in some cases.
6972     if (isSCEVable(Op->getType()))
6973       SCEVOps.push_back(getSCEV(Op));
6974   }
6975   auto *DefI = getDefiningScopeBound(SCEVOps);
6976   return isGuaranteedToTransferExecutionTo(DefI, I);
6977 }
6978 
6979 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6980   // If we know that \c I can never be poison period, then that's enough.
6981   if (isSCEVExprNeverPoison(I))
6982     return true;
6983 
6984   // For an add recurrence specifically, we assume that infinite loops without
6985   // side effects are undefined behavior, and then reason as follows:
6986   //
6987   // If the add recurrence is poison in any iteration, it is poison on all
6988   // future iterations (since incrementing poison yields poison). If the result
6989   // of the add recurrence is fed into the loop latch condition and the loop
6990   // does not contain any throws or exiting blocks other than the latch, we now
6991   // have the ability to "choose" whether the backedge is taken or not (by
6992   // choosing a sufficiently evil value for the poison feeding into the branch)
6993   // for every iteration including and after the one in which \p I first became
6994   // poison.  There are two possibilities (let's call the iteration in which \p
6995   // I first became poison as K):
6996   //
6997   //  1. In the set of iterations including and after K, the loop body executes
6998   //     no side effects.  In this case executing the backege an infinte number
6999   //     of times will yield undefined behavior.
7000   //
7001   //  2. In the set of iterations including and after K, the loop body executes
7002   //     at least one side effect.  In this case, that specific instance of side
7003   //     effect is control dependent on poison, which also yields undefined
7004   //     behavior.
7005 
7006   auto *ExitingBB = L->getExitingBlock();
7007   auto *LatchBB = L->getLoopLatch();
7008   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
7009     return false;
7010 
7011   SmallPtrSet<const Instruction *, 16> Pushed;
7012   SmallVector<const Instruction *, 8> PoisonStack;
7013 
7014   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
7015   // things that are known to be poison under that assumption go on the
7016   // PoisonStack.
7017   Pushed.insert(I);
7018   PoisonStack.push_back(I);
7019 
7020   bool LatchControlDependentOnPoison = false;
7021   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
7022     const Instruction *Poison = PoisonStack.pop_back_val();
7023 
7024     for (auto *PoisonUser : Poison->users()) {
7025       if (propagatesPoison(cast<Operator>(PoisonUser))) {
7026         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
7027           PoisonStack.push_back(cast<Instruction>(PoisonUser));
7028       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
7029         assert(BI->isConditional() && "Only possibility!");
7030         if (BI->getParent() == LatchBB) {
7031           LatchControlDependentOnPoison = true;
7032           break;
7033         }
7034       }
7035     }
7036   }
7037 
7038   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
7039 }
7040 
7041 ScalarEvolution::LoopProperties
7042 ScalarEvolution::getLoopProperties(const Loop *L) {
7043   using LoopProperties = ScalarEvolution::LoopProperties;
7044 
7045   auto Itr = LoopPropertiesCache.find(L);
7046   if (Itr == LoopPropertiesCache.end()) {
7047     auto HasSideEffects = [](Instruction *I) {
7048       if (auto *SI = dyn_cast<StoreInst>(I))
7049         return !SI->isSimple();
7050 
7051       return I->mayThrow() || I->mayWriteToMemory();
7052     };
7053 
7054     LoopProperties LP = {/* HasNoAbnormalExits */ true,
7055                          /*HasNoSideEffects*/ true};
7056 
7057     for (auto *BB : L->getBlocks())
7058       for (auto &I : *BB) {
7059         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7060           LP.HasNoAbnormalExits = false;
7061         if (HasSideEffects(&I))
7062           LP.HasNoSideEffects = false;
7063         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7064           break; // We're already as pessimistic as we can get.
7065       }
7066 
7067     auto InsertPair = LoopPropertiesCache.insert({L, LP});
7068     assert(InsertPair.second && "We just checked!");
7069     Itr = InsertPair.first;
7070   }
7071 
7072   return Itr->second;
7073 }
7074 
7075 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7076   // A mustprogress loop without side effects must be finite.
7077   // TODO: The check used here is very conservative.  It's only *specific*
7078   // side effects which are well defined in infinite loops.
7079   return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7080 }
7081 
7082 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7083   if (!isSCEVable(V->getType()))
7084     return getUnknown(V);
7085 
7086   if (Instruction *I = dyn_cast<Instruction>(V)) {
7087     // Don't attempt to analyze instructions in blocks that aren't
7088     // reachable. Such instructions don't matter, and they aren't required
7089     // to obey basic rules for definitions dominating uses which this
7090     // analysis depends on.
7091     if (!DT.isReachableFromEntry(I->getParent()))
7092       return getUnknown(UndefValue::get(V->getType()));
7093   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7094     return getConstant(CI);
7095   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
7096     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
7097   else if (!isa<ConstantExpr>(V))
7098     return getUnknown(V);
7099 
7100   Operator *U = cast<Operator>(V);
7101   if (auto BO = MatchBinaryOp(U, DT)) {
7102     switch (BO->Opcode) {
7103     case Instruction::Add: {
7104       // The simple thing to do would be to just call getSCEV on both operands
7105       // and call getAddExpr with the result. However if we're looking at a
7106       // bunch of things all added together, this can be quite inefficient,
7107       // because it leads to N-1 getAddExpr calls for N ultimate operands.
7108       // Instead, gather up all the operands and make a single getAddExpr call.
7109       // LLVM IR canonical form means we need only traverse the left operands.
7110       SmallVector<const SCEV *, 4> AddOps;
7111       do {
7112         if (BO->Op) {
7113           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7114             AddOps.push_back(OpSCEV);
7115             break;
7116           }
7117 
7118           // If a NUW or NSW flag can be applied to the SCEV for this
7119           // addition, then compute the SCEV for this addition by itself
7120           // with a separate call to getAddExpr. We need to do that
7121           // instead of pushing the operands of the addition onto AddOps,
7122           // since the flags are only known to apply to this particular
7123           // addition - they may not apply to other additions that can be
7124           // formed with operands from AddOps.
7125           const SCEV *RHS = getSCEV(BO->RHS);
7126           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7127           if (Flags != SCEV::FlagAnyWrap) {
7128             const SCEV *LHS = getSCEV(BO->LHS);
7129             if (BO->Opcode == Instruction::Sub)
7130               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7131             else
7132               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7133             break;
7134           }
7135         }
7136 
7137         if (BO->Opcode == Instruction::Sub)
7138           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7139         else
7140           AddOps.push_back(getSCEV(BO->RHS));
7141 
7142         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7143         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7144                        NewBO->Opcode != Instruction::Sub)) {
7145           AddOps.push_back(getSCEV(BO->LHS));
7146           break;
7147         }
7148         BO = NewBO;
7149       } while (true);
7150 
7151       return getAddExpr(AddOps);
7152     }
7153 
7154     case Instruction::Mul: {
7155       SmallVector<const SCEV *, 4> MulOps;
7156       do {
7157         if (BO->Op) {
7158           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7159             MulOps.push_back(OpSCEV);
7160             break;
7161           }
7162 
7163           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7164           if (Flags != SCEV::FlagAnyWrap) {
7165             MulOps.push_back(
7166                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
7167             break;
7168           }
7169         }
7170 
7171         MulOps.push_back(getSCEV(BO->RHS));
7172         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7173         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7174           MulOps.push_back(getSCEV(BO->LHS));
7175           break;
7176         }
7177         BO = NewBO;
7178       } while (true);
7179 
7180       return getMulExpr(MulOps);
7181     }
7182     case Instruction::UDiv:
7183       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7184     case Instruction::URem:
7185       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7186     case Instruction::Sub: {
7187       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7188       if (BO->Op)
7189         Flags = getNoWrapFlagsFromUB(BO->Op);
7190       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
7191     }
7192     case Instruction::And:
7193       // For an expression like x&255 that merely masks off the high bits,
7194       // use zext(trunc(x)) as the SCEV expression.
7195       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7196         if (CI->isZero())
7197           return getSCEV(BO->RHS);
7198         if (CI->isMinusOne())
7199           return getSCEV(BO->LHS);
7200         const APInt &A = CI->getValue();
7201 
7202         // Instcombine's ShrinkDemandedConstant may strip bits out of
7203         // constants, obscuring what would otherwise be a low-bits mask.
7204         // Use computeKnownBits to compute what ShrinkDemandedConstant
7205         // knew about to reconstruct a low-bits mask value.
7206         unsigned LZ = A.countLeadingZeros();
7207         unsigned TZ = A.countTrailingZeros();
7208         unsigned BitWidth = A.getBitWidth();
7209         KnownBits Known(BitWidth);
7210         computeKnownBits(BO->LHS, Known, getDataLayout(),
7211                          0, &AC, nullptr, &DT);
7212 
7213         APInt EffectiveMask =
7214             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7215         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7216           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7217           const SCEV *LHS = getSCEV(BO->LHS);
7218           const SCEV *ShiftedLHS = nullptr;
7219           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7220             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7221               // For an expression like (x * 8) & 8, simplify the multiply.
7222               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
7223               unsigned GCD = std::min(MulZeros, TZ);
7224               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7225               SmallVector<const SCEV*, 4> MulOps;
7226               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7227               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
7228               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7229               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7230             }
7231           }
7232           if (!ShiftedLHS)
7233             ShiftedLHS = getUDivExpr(LHS, MulCount);
7234           return getMulExpr(
7235               getZeroExtendExpr(
7236                   getTruncateExpr(ShiftedLHS,
7237                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7238                   BO->LHS->getType()),
7239               MulCount);
7240         }
7241       }
7242       // Binary `and` is a bit-wise `umin`.
7243       if (BO->LHS->getType()->isIntegerTy(1))
7244         return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7245       break;
7246 
7247     case Instruction::Or:
7248       // If the RHS of the Or is a constant, we may have something like:
7249       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
7250       // optimizations will transparently handle this case.
7251       //
7252       // In order for this transformation to be safe, the LHS must be of the
7253       // form X*(2^n) and the Or constant must be less than 2^n.
7254       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7255         const SCEV *LHS = getSCEV(BO->LHS);
7256         const APInt &CIVal = CI->getValue();
7257         if (GetMinTrailingZeros(LHS) >=
7258             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
7259           // Build a plain add SCEV.
7260           return getAddExpr(LHS, getSCEV(CI),
7261                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
7262         }
7263       }
7264       // Binary `or` is a bit-wise `umax`.
7265       if (BO->LHS->getType()->isIntegerTy(1))
7266         return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7267       break;
7268 
7269     case Instruction::Xor:
7270       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7271         // If the RHS of xor is -1, then this is a not operation.
7272         if (CI->isMinusOne())
7273           return getNotSCEV(getSCEV(BO->LHS));
7274 
7275         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7276         // This is a variant of the check for xor with -1, and it handles
7277         // the case where instcombine has trimmed non-demanded bits out
7278         // of an xor with -1.
7279         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7280           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7281             if (LBO->getOpcode() == Instruction::And &&
7282                 LCI->getValue() == CI->getValue())
7283               if (const SCEVZeroExtendExpr *Z =
7284                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7285                 Type *UTy = BO->LHS->getType();
7286                 const SCEV *Z0 = Z->getOperand();
7287                 Type *Z0Ty = Z0->getType();
7288                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7289 
7290                 // If C is a low-bits mask, the zero extend is serving to
7291                 // mask off the high bits. Complement the operand and
7292                 // re-apply the zext.
7293                 if (CI->getValue().isMask(Z0TySize))
7294                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7295 
7296                 // If C is a single bit, it may be in the sign-bit position
7297                 // before the zero-extend. In this case, represent the xor
7298                 // using an add, which is equivalent, and re-apply the zext.
7299                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7300                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7301                     Trunc.isSignMask())
7302                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7303                                            UTy);
7304               }
7305       }
7306       break;
7307 
7308     case Instruction::Shl:
7309       // Turn shift left of a constant amount into a multiply.
7310       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7311         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7312 
7313         // If the shift count is not less than the bitwidth, the result of
7314         // the shift is undefined. Don't try to analyze it, because the
7315         // resolution chosen here may differ from the resolution chosen in
7316         // other parts of the compiler.
7317         if (SA->getValue().uge(BitWidth))
7318           break;
7319 
7320         // We can safely preserve the nuw flag in all cases. It's also safe to
7321         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7322         // requires special handling. It can be preserved as long as we're not
7323         // left shifting by bitwidth - 1.
7324         auto Flags = SCEV::FlagAnyWrap;
7325         if (BO->Op) {
7326           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7327           if ((MulFlags & SCEV::FlagNSW) &&
7328               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7329             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7330           if (MulFlags & SCEV::FlagNUW)
7331             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7332         }
7333 
7334         Constant *X = ConstantInt::get(
7335             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7336         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
7337       }
7338       break;
7339 
7340     case Instruction::AShr: {
7341       // AShr X, C, where C is a constant.
7342       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7343       if (!CI)
7344         break;
7345 
7346       Type *OuterTy = BO->LHS->getType();
7347       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7348       // If the shift count is not less than the bitwidth, the result of
7349       // the shift is undefined. Don't try to analyze it, because the
7350       // resolution chosen here may differ from the resolution chosen in
7351       // other parts of the compiler.
7352       if (CI->getValue().uge(BitWidth))
7353         break;
7354 
7355       if (CI->isZero())
7356         return getSCEV(BO->LHS); // shift by zero --> noop
7357 
7358       uint64_t AShrAmt = CI->getZExtValue();
7359       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7360 
7361       Operator *L = dyn_cast<Operator>(BO->LHS);
7362       if (L && L->getOpcode() == Instruction::Shl) {
7363         // X = Shl A, n
7364         // Y = AShr X, m
7365         // Both n and m are constant.
7366 
7367         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7368         if (L->getOperand(1) == BO->RHS)
7369           // For a two-shift sext-inreg, i.e. n = m,
7370           // use sext(trunc(x)) as the SCEV expression.
7371           return getSignExtendExpr(
7372               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7373 
7374         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7375         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7376           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7377           if (ShlAmt > AShrAmt) {
7378             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7379             // expression. We already checked that ShlAmt < BitWidth, so
7380             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7381             // ShlAmt - AShrAmt < Amt.
7382             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7383                                             ShlAmt - AShrAmt);
7384             return getSignExtendExpr(
7385                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7386                 getConstant(Mul)), OuterTy);
7387           }
7388         }
7389       }
7390       break;
7391     }
7392     }
7393   }
7394 
7395   switch (U->getOpcode()) {
7396   case Instruction::Trunc:
7397     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7398 
7399   case Instruction::ZExt:
7400     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7401 
7402   case Instruction::SExt:
7403     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7404       // The NSW flag of a subtract does not always survive the conversion to
7405       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7406       // more likely to preserve NSW and allow later AddRec optimisations.
7407       //
7408       // NOTE: This is effectively duplicating this logic from getSignExtend:
7409       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7410       // but by that point the NSW information has potentially been lost.
7411       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7412         Type *Ty = U->getType();
7413         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7414         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7415         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7416       }
7417     }
7418     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7419 
7420   case Instruction::BitCast:
7421     // BitCasts are no-op casts so we just eliminate the cast.
7422     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7423       return getSCEV(U->getOperand(0));
7424     break;
7425 
7426   case Instruction::PtrToInt: {
7427     // Pointer to integer cast is straight-forward, so do model it.
7428     const SCEV *Op = getSCEV(U->getOperand(0));
7429     Type *DstIntTy = U->getType();
7430     // But only if effective SCEV (integer) type is wide enough to represent
7431     // all possible pointer values.
7432     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7433     if (isa<SCEVCouldNotCompute>(IntOp))
7434       return getUnknown(V);
7435     return IntOp;
7436   }
7437   case Instruction::IntToPtr:
7438     // Just don't deal with inttoptr casts.
7439     return getUnknown(V);
7440 
7441   case Instruction::SDiv:
7442     // If both operands are non-negative, this is just an udiv.
7443     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7444         isKnownNonNegative(getSCEV(U->getOperand(1))))
7445       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7446     break;
7447 
7448   case Instruction::SRem:
7449     // If both operands are non-negative, this is just an urem.
7450     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7451         isKnownNonNegative(getSCEV(U->getOperand(1))))
7452       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7453     break;
7454 
7455   case Instruction::GetElementPtr:
7456     return createNodeForGEP(cast<GEPOperator>(U));
7457 
7458   case Instruction::PHI:
7459     return createNodeForPHI(cast<PHINode>(U));
7460 
7461   case Instruction::Select:
7462     return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
7463                                     U->getOperand(2));
7464 
7465   case Instruction::Call:
7466   case Instruction::Invoke:
7467     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7468       return getSCEV(RV);
7469 
7470     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7471       switch (II->getIntrinsicID()) {
7472       case Intrinsic::abs:
7473         return getAbsExpr(
7474             getSCEV(II->getArgOperand(0)),
7475             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7476       case Intrinsic::umax:
7477         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7478                            getSCEV(II->getArgOperand(1)));
7479       case Intrinsic::umin:
7480         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7481                            getSCEV(II->getArgOperand(1)));
7482       case Intrinsic::smax:
7483         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7484                            getSCEV(II->getArgOperand(1)));
7485       case Intrinsic::smin:
7486         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7487                            getSCEV(II->getArgOperand(1)));
7488       case Intrinsic::usub_sat: {
7489         const SCEV *X = getSCEV(II->getArgOperand(0));
7490         const SCEV *Y = getSCEV(II->getArgOperand(1));
7491         const SCEV *ClampedY = getUMinExpr(X, Y);
7492         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7493       }
7494       case Intrinsic::uadd_sat: {
7495         const SCEV *X = getSCEV(II->getArgOperand(0));
7496         const SCEV *Y = getSCEV(II->getArgOperand(1));
7497         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7498         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7499       }
7500       case Intrinsic::start_loop_iterations:
7501         // A start_loop_iterations is just equivalent to the first operand for
7502         // SCEV purposes.
7503         return getSCEV(II->getArgOperand(0));
7504       default:
7505         break;
7506       }
7507     }
7508     break;
7509   }
7510 
7511   return getUnknown(V);
7512 }
7513 
7514 //===----------------------------------------------------------------------===//
7515 //                   Iteration Count Computation Code
7516 //
7517 
7518 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
7519                                                        bool Extend) {
7520   if (isa<SCEVCouldNotCompute>(ExitCount))
7521     return getCouldNotCompute();
7522 
7523   auto *ExitCountType = ExitCount->getType();
7524   assert(ExitCountType->isIntegerTy());
7525 
7526   if (!Extend)
7527     return getAddExpr(ExitCount, getOne(ExitCountType));
7528 
7529   auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
7530                                     1 + ExitCountType->getScalarSizeInBits());
7531   return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
7532                     getOne(WiderType));
7533 }
7534 
7535 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7536   if (!ExitCount)
7537     return 0;
7538 
7539   ConstantInt *ExitConst = ExitCount->getValue();
7540 
7541   // Guard against huge trip counts.
7542   if (ExitConst->getValue().getActiveBits() > 32)
7543     return 0;
7544 
7545   // In case of integer overflow, this returns 0, which is correct.
7546   return ((unsigned)ExitConst->getZExtValue()) + 1;
7547 }
7548 
7549 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7550   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7551   return getConstantTripCount(ExitCount);
7552 }
7553 
7554 unsigned
7555 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7556                                            const BasicBlock *ExitingBlock) {
7557   assert(ExitingBlock && "Must pass a non-null exiting block!");
7558   assert(L->isLoopExiting(ExitingBlock) &&
7559          "Exiting block must actually branch out of the loop!");
7560   const SCEVConstant *ExitCount =
7561       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7562   return getConstantTripCount(ExitCount);
7563 }
7564 
7565 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7566   const auto *MaxExitCount =
7567       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7568   return getConstantTripCount(MaxExitCount);
7569 }
7570 
7571 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
7572   // We can't infer from Array in Irregular Loop.
7573   // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
7574   if (!L->isLoopSimplifyForm() || !L->isInnermost())
7575     return getCouldNotCompute();
7576 
7577   // FIXME: To make the scene more typical, we only analysis loops that have
7578   // one exiting block and that block must be the latch. To make it easier to
7579   // capture loops that have memory access and memory access will be executed
7580   // in each iteration.
7581   const BasicBlock *LoopLatch = L->getLoopLatch();
7582   assert(LoopLatch && "See defination of simplify form loop.");
7583   if (L->getExitingBlock() != LoopLatch)
7584     return getCouldNotCompute();
7585 
7586   const DataLayout &DL = getDataLayout();
7587   SmallVector<const SCEV *> InferCountColl;
7588   for (auto *BB : L->getBlocks()) {
7589     // Go here, we can know that Loop is a single exiting and simplified form
7590     // loop. Make sure that infer from Memory Operation in those BBs must be
7591     // executed in loop. First step, we can make sure that max execution time
7592     // of MemAccessBB in loop represents latch max excution time.
7593     // If MemAccessBB does not dom Latch, skip.
7594     //            Entry
7595     //              │
7596     //        ┌─────▼─────┐
7597     //        │Loop Header◄─────┐
7598     //        └──┬──────┬─┘     │
7599     //           │      │       │
7600     //  ┌────────▼──┐ ┌─▼─────┐ │
7601     //  │MemAccessBB│ │OtherBB│ │
7602     //  └────────┬──┘ └─┬─────┘ │
7603     //           │      │       │
7604     //         ┌─▼──────▼─┐     │
7605     //         │Loop Latch├─────┘
7606     //         └────┬─────┘
7607     //              ▼
7608     //             Exit
7609     if (!DT.dominates(BB, LoopLatch))
7610       continue;
7611 
7612     for (Instruction &Inst : *BB) {
7613       // Find Memory Operation Instruction.
7614       auto *GEP = getLoadStorePointerOperand(&Inst);
7615       if (!GEP)
7616         continue;
7617 
7618       auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
7619       // Do not infer from scalar type, eg."ElemSize = sizeof()".
7620       if (!ElemSize)
7621         continue;
7622 
7623       // Use a existing polynomial recurrence on the trip count.
7624       auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
7625       if (!AddRec)
7626         continue;
7627       auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
7628       auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
7629       if (!ArrBase || !Step)
7630         continue;
7631       assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
7632 
7633       // Only handle { %array + step },
7634       // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
7635       if (AddRec->getStart() != ArrBase)
7636         continue;
7637 
7638       // Memory operation pattern which have gaps.
7639       // Or repeat memory opreation.
7640       // And index of GEP wraps arround.
7641       if (Step->getAPInt().getActiveBits() > 32 ||
7642           Step->getAPInt().getZExtValue() !=
7643               ElemSize->getAPInt().getZExtValue() ||
7644           Step->isZero() || Step->getAPInt().isNegative())
7645         continue;
7646 
7647       // Only infer from stack array which has certain size.
7648       // Make sure alloca instruction is not excuted in loop.
7649       AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
7650       if (!AllocateInst || L->contains(AllocateInst->getParent()))
7651         continue;
7652 
7653       // Make sure only handle normal array.
7654       auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
7655       auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
7656       if (!Ty || !ArrSize || !ArrSize->isOne())
7657         continue;
7658 
7659       // FIXME: Since gep indices are silently zext to the indexing type,
7660       // we will have a narrow gep index which wraps around rather than
7661       // increasing strictly, we shoule ensure that step is increasing
7662       // strictly by the loop iteration.
7663       // Now we can infer a max execution time by MemLength/StepLength.
7664       const SCEV *MemSize =
7665           getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
7666       auto *MaxExeCount =
7667           dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
7668       if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
7669         continue;
7670 
7671       // If the loop reaches the maximum number of executions, we can not
7672       // access bytes starting outside the statically allocated size without
7673       // being immediate UB. But it is allowed to enter loop header one more
7674       // time.
7675       auto *InferCount = dyn_cast<SCEVConstant>(
7676           getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
7677       // Discard the maximum number of execution times under 32bits.
7678       if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
7679         continue;
7680 
7681       InferCountColl.push_back(InferCount);
7682     }
7683   }
7684 
7685   if (InferCountColl.size() == 0)
7686     return getCouldNotCompute();
7687 
7688   return getUMinFromMismatchedTypes(InferCountColl);
7689 }
7690 
7691 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7692   SmallVector<BasicBlock *, 8> ExitingBlocks;
7693   L->getExitingBlocks(ExitingBlocks);
7694 
7695   Optional<unsigned> Res = None;
7696   for (auto *ExitingBB : ExitingBlocks) {
7697     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7698     if (!Res)
7699       Res = Multiple;
7700     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7701   }
7702   return Res.getValueOr(1);
7703 }
7704 
7705 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7706                                                        const SCEV *ExitCount) {
7707   if (ExitCount == getCouldNotCompute())
7708     return 1;
7709 
7710   // Get the trip count
7711   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7712 
7713   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7714   if (!TC)
7715     // Attempt to factor more general cases. Returns the greatest power of
7716     // two divisor. If overflow happens, the trip count expression is still
7717     // divisible by the greatest power of 2 divisor returned.
7718     return 1U << std::min((uint32_t)31,
7719                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7720 
7721   ConstantInt *Result = TC->getValue();
7722 
7723   // Guard against huge trip counts (this requires checking
7724   // for zero to handle the case where the trip count == -1 and the
7725   // addition wraps).
7726   if (!Result || Result->getValue().getActiveBits() > 32 ||
7727       Result->getValue().getActiveBits() == 0)
7728     return 1;
7729 
7730   return (unsigned)Result->getZExtValue();
7731 }
7732 
7733 /// Returns the largest constant divisor of the trip count of this loop as a
7734 /// normal unsigned value, if possible. This means that the actual trip count is
7735 /// always a multiple of the returned value (don't forget the trip count could
7736 /// very well be zero as well!).
7737 ///
7738 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7739 /// multiple of a constant (which is also the case if the trip count is simply
7740 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7741 /// if the trip count is very large (>= 2^32).
7742 ///
7743 /// As explained in the comments for getSmallConstantTripCount, this assumes
7744 /// that control exits the loop via ExitingBlock.
7745 unsigned
7746 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7747                                               const BasicBlock *ExitingBlock) {
7748   assert(ExitingBlock && "Must pass a non-null exiting block!");
7749   assert(L->isLoopExiting(ExitingBlock) &&
7750          "Exiting block must actually branch out of the loop!");
7751   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7752   return getSmallConstantTripMultiple(L, ExitCount);
7753 }
7754 
7755 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7756                                           const BasicBlock *ExitingBlock,
7757                                           ExitCountKind Kind) {
7758   switch (Kind) {
7759   case Exact:
7760   case SymbolicMaximum:
7761     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7762   case ConstantMaximum:
7763     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7764   };
7765   llvm_unreachable("Invalid ExitCountKind!");
7766 }
7767 
7768 const SCEV *
7769 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7770                                                  SmallVector<const SCEVPredicate *, 4> &Preds) {
7771   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7772 }
7773 
7774 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7775                                                    ExitCountKind Kind) {
7776   switch (Kind) {
7777   case Exact:
7778     return getBackedgeTakenInfo(L).getExact(L, this);
7779   case ConstantMaximum:
7780     return getBackedgeTakenInfo(L).getConstantMax(this);
7781   case SymbolicMaximum:
7782     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7783   };
7784   llvm_unreachable("Invalid ExitCountKind!");
7785 }
7786 
7787 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7788   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7789 }
7790 
7791 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7792 static void PushLoopPHIs(const Loop *L,
7793                          SmallVectorImpl<Instruction *> &Worklist,
7794                          SmallPtrSetImpl<Instruction *> &Visited) {
7795   BasicBlock *Header = L->getHeader();
7796 
7797   // Push all Loop-header PHIs onto the Worklist stack.
7798   for (PHINode &PN : Header->phis())
7799     if (Visited.insert(&PN).second)
7800       Worklist.push_back(&PN);
7801 }
7802 
7803 const ScalarEvolution::BackedgeTakenInfo &
7804 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7805   auto &BTI = getBackedgeTakenInfo(L);
7806   if (BTI.hasFullInfo())
7807     return BTI;
7808 
7809   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7810 
7811   if (!Pair.second)
7812     return Pair.first->second;
7813 
7814   BackedgeTakenInfo Result =
7815       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7816 
7817   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7818 }
7819 
7820 ScalarEvolution::BackedgeTakenInfo &
7821 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7822   // Initially insert an invalid entry for this loop. If the insertion
7823   // succeeds, proceed to actually compute a backedge-taken count and
7824   // update the value. The temporary CouldNotCompute value tells SCEV
7825   // code elsewhere that it shouldn't attempt to request a new
7826   // backedge-taken count, which could result in infinite recursion.
7827   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7828       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7829   if (!Pair.second)
7830     return Pair.first->second;
7831 
7832   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7833   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7834   // must be cleared in this scope.
7835   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7836 
7837   // In product build, there are no usage of statistic.
7838   (void)NumTripCountsComputed;
7839   (void)NumTripCountsNotComputed;
7840 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7841   const SCEV *BEExact = Result.getExact(L, this);
7842   if (BEExact != getCouldNotCompute()) {
7843     assert(isLoopInvariant(BEExact, L) &&
7844            isLoopInvariant(Result.getConstantMax(this), L) &&
7845            "Computed backedge-taken count isn't loop invariant for loop!");
7846     ++NumTripCountsComputed;
7847   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7848              isa<PHINode>(L->getHeader()->begin())) {
7849     // Only count loops that have phi nodes as not being computable.
7850     ++NumTripCountsNotComputed;
7851   }
7852 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7853 
7854   // Now that we know more about the trip count for this loop, forget any
7855   // existing SCEV values for PHI nodes in this loop since they are only
7856   // conservative estimates made without the benefit of trip count
7857   // information. This invalidation is not necessary for correctness, and is
7858   // only done to produce more precise results.
7859   if (Result.hasAnyInfo()) {
7860     // Invalidate any expression using an addrec in this loop.
7861     SmallVector<const SCEV *, 8> ToForget;
7862     auto LoopUsersIt = LoopUsers.find(L);
7863     if (LoopUsersIt != LoopUsers.end())
7864       append_range(ToForget, LoopUsersIt->second);
7865     forgetMemoizedResults(ToForget);
7866 
7867     // Invalidate constant-evolved loop header phis.
7868     for (PHINode &PN : L->getHeader()->phis())
7869       ConstantEvolutionLoopExitValue.erase(&PN);
7870   }
7871 
7872   // Re-lookup the insert position, since the call to
7873   // computeBackedgeTakenCount above could result in a
7874   // recusive call to getBackedgeTakenInfo (on a different
7875   // loop), which would invalidate the iterator computed
7876   // earlier.
7877   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7878 }
7879 
7880 void ScalarEvolution::forgetAllLoops() {
7881   // This method is intended to forget all info about loops. It should
7882   // invalidate caches as if the following happened:
7883   // - The trip counts of all loops have changed arbitrarily
7884   // - Every llvm::Value has been updated in place to produce a different
7885   // result.
7886   BackedgeTakenCounts.clear();
7887   PredicatedBackedgeTakenCounts.clear();
7888   BECountUsers.clear();
7889   LoopPropertiesCache.clear();
7890   ConstantEvolutionLoopExitValue.clear();
7891   ValueExprMap.clear();
7892   ValuesAtScopes.clear();
7893   ValuesAtScopesUsers.clear();
7894   LoopDispositions.clear();
7895   BlockDispositions.clear();
7896   UnsignedRanges.clear();
7897   SignedRanges.clear();
7898   ExprValueMap.clear();
7899   HasRecMap.clear();
7900   MinTrailingZerosCache.clear();
7901   PredicatedSCEVRewrites.clear();
7902 }
7903 
7904 void ScalarEvolution::forgetLoop(const Loop *L) {
7905   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7906   SmallVector<Instruction *, 32> Worklist;
7907   SmallPtrSet<Instruction *, 16> Visited;
7908   SmallVector<const SCEV *, 16> ToForget;
7909 
7910   // Iterate over all the loops and sub-loops to drop SCEV information.
7911   while (!LoopWorklist.empty()) {
7912     auto *CurrL = LoopWorklist.pop_back_val();
7913 
7914     // Drop any stored trip count value.
7915     forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
7916     forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
7917 
7918     // Drop information about predicated SCEV rewrites for this loop.
7919     for (auto I = PredicatedSCEVRewrites.begin();
7920          I != PredicatedSCEVRewrites.end();) {
7921       std::pair<const SCEV *, const Loop *> Entry = I->first;
7922       if (Entry.second == CurrL)
7923         PredicatedSCEVRewrites.erase(I++);
7924       else
7925         ++I;
7926     }
7927 
7928     auto LoopUsersItr = LoopUsers.find(CurrL);
7929     if (LoopUsersItr != LoopUsers.end()) {
7930       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
7931                 LoopUsersItr->second.end());
7932     }
7933 
7934     // Drop information about expressions based on loop-header PHIs.
7935     PushLoopPHIs(CurrL, Worklist, Visited);
7936 
7937     while (!Worklist.empty()) {
7938       Instruction *I = Worklist.pop_back_val();
7939 
7940       ValueExprMapType::iterator It =
7941           ValueExprMap.find_as(static_cast<Value *>(I));
7942       if (It != ValueExprMap.end()) {
7943         eraseValueFromMap(It->first);
7944         ToForget.push_back(It->second);
7945         if (PHINode *PN = dyn_cast<PHINode>(I))
7946           ConstantEvolutionLoopExitValue.erase(PN);
7947       }
7948 
7949       PushDefUseChildren(I, Worklist, Visited);
7950     }
7951 
7952     LoopPropertiesCache.erase(CurrL);
7953     // Forget all contained loops too, to avoid dangling entries in the
7954     // ValuesAtScopes map.
7955     LoopWorklist.append(CurrL->begin(), CurrL->end());
7956   }
7957   forgetMemoizedResults(ToForget);
7958 }
7959 
7960 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7961   while (Loop *Parent = L->getParentLoop())
7962     L = Parent;
7963   forgetLoop(L);
7964 }
7965 
7966 void ScalarEvolution::forgetValue(Value *V) {
7967   Instruction *I = dyn_cast<Instruction>(V);
7968   if (!I) return;
7969 
7970   // Drop information about expressions based on loop-header PHIs.
7971   SmallVector<Instruction *, 16> Worklist;
7972   SmallPtrSet<Instruction *, 8> Visited;
7973   SmallVector<const SCEV *, 8> ToForget;
7974   Worklist.push_back(I);
7975   Visited.insert(I);
7976 
7977   while (!Worklist.empty()) {
7978     I = Worklist.pop_back_val();
7979     ValueExprMapType::iterator It =
7980       ValueExprMap.find_as(static_cast<Value *>(I));
7981     if (It != ValueExprMap.end()) {
7982       eraseValueFromMap(It->first);
7983       ToForget.push_back(It->second);
7984       if (PHINode *PN = dyn_cast<PHINode>(I))
7985         ConstantEvolutionLoopExitValue.erase(PN);
7986     }
7987 
7988     PushDefUseChildren(I, Worklist, Visited);
7989   }
7990   forgetMemoizedResults(ToForget);
7991 }
7992 
7993 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7994   LoopDispositions.clear();
7995 }
7996 
7997 /// Get the exact loop backedge taken count considering all loop exits. A
7998 /// computable result can only be returned for loops with all exiting blocks
7999 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8000 /// is never skipped. This is a valid assumption as long as the loop exits via
8001 /// that test. For precise results, it is the caller's responsibility to specify
8002 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8003 const SCEV *
8004 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8005                                              SmallVector<const SCEVPredicate *, 4> *Preds) const {
8006   // If any exits were not computable, the loop is not computable.
8007   if (!isComplete() || ExitNotTaken.empty())
8008     return SE->getCouldNotCompute();
8009 
8010   const BasicBlock *Latch = L->getLoopLatch();
8011   // All exiting blocks we have collected must dominate the only backedge.
8012   if (!Latch)
8013     return SE->getCouldNotCompute();
8014 
8015   // All exiting blocks we have gathered dominate loop's latch, so exact trip
8016   // count is simply a minimum out of all these calculated exit counts.
8017   SmallVector<const SCEV *, 2> Ops;
8018   for (auto &ENT : ExitNotTaken) {
8019     const SCEV *BECount = ENT.ExactNotTaken;
8020     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8021     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8022            "We should only have known counts for exiting blocks that dominate "
8023            "latch!");
8024 
8025     Ops.push_back(BECount);
8026 
8027     if (Preds)
8028       for (auto *P : ENT.Predicates)
8029         Preds->push_back(P);
8030 
8031     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8032            "Predicate should be always true!");
8033   }
8034 
8035   return SE->getUMinFromMismatchedTypes(Ops);
8036 }
8037 
8038 /// Get the exact not taken count for this loop exit.
8039 const SCEV *
8040 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8041                                              ScalarEvolution *SE) const {
8042   for (auto &ENT : ExitNotTaken)
8043     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8044       return ENT.ExactNotTaken;
8045 
8046   return SE->getCouldNotCompute();
8047 }
8048 
8049 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8050     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8051   for (auto &ENT : ExitNotTaken)
8052     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8053       return ENT.MaxNotTaken;
8054 
8055   return SE->getCouldNotCompute();
8056 }
8057 
8058 /// getConstantMax - Get the constant max backedge taken count for the loop.
8059 const SCEV *
8060 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8061   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8062     return !ENT.hasAlwaysTruePredicate();
8063   };
8064 
8065   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8066     return SE->getCouldNotCompute();
8067 
8068   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8069           isa<SCEVConstant>(getConstantMax())) &&
8070          "No point in having a non-constant max backedge taken count!");
8071   return getConstantMax();
8072 }
8073 
8074 const SCEV *
8075 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8076                                                    ScalarEvolution *SE) {
8077   if (!SymbolicMax)
8078     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8079   return SymbolicMax;
8080 }
8081 
8082 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8083     ScalarEvolution *SE) const {
8084   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8085     return !ENT.hasAlwaysTruePredicate();
8086   };
8087   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8088 }
8089 
8090 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8091     : ExitLimit(E, E, false, None) {
8092 }
8093 
8094 ScalarEvolution::ExitLimit::ExitLimit(
8095     const SCEV *E, const SCEV *M, bool MaxOrZero,
8096     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8097     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
8098   // If we prove the max count is zero, so is the symbolic bound.  This happens
8099   // in practice due to differences in a) how context sensitive we've chosen
8100   // to be and b) how we reason about bounds impied by UB.
8101   if (MaxNotTaken->isZero())
8102     ExactNotTaken = MaxNotTaken;
8103 
8104   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8105           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
8106          "Exact is not allowed to be less precise than Max");
8107   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
8108           isa<SCEVConstant>(MaxNotTaken)) &&
8109          "No point in having a non-constant max backedge taken count!");
8110   for (auto *PredSet : PredSetList)
8111     for (auto *P : *PredSet)
8112       addPredicate(P);
8113   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8114          "Backedge count should be int");
8115   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
8116          "Max backedge count should be int");
8117 }
8118 
8119 ScalarEvolution::ExitLimit::ExitLimit(
8120     const SCEV *E, const SCEV *M, bool MaxOrZero,
8121     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8122     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
8123 }
8124 
8125 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
8126                                       bool MaxOrZero)
8127     : ExitLimit(E, M, MaxOrZero, None) {
8128 }
8129 
8130 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8131 /// computable exit into a persistent ExitNotTakenInfo array.
8132 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8133     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8134     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8135     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8136   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8137 
8138   ExitNotTaken.reserve(ExitCounts.size());
8139   std::transform(
8140       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
8141       [&](const EdgeExitInfo &EEI) {
8142         BasicBlock *ExitBB = EEI.first;
8143         const ExitLimit &EL = EEI.second;
8144         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
8145                                 EL.Predicates);
8146       });
8147   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8148           isa<SCEVConstant>(ConstantMax)) &&
8149          "No point in having a non-constant max backedge taken count!");
8150 }
8151 
8152 /// Compute the number of times the backedge of the specified loop will execute.
8153 ScalarEvolution::BackedgeTakenInfo
8154 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8155                                            bool AllowPredicates) {
8156   SmallVector<BasicBlock *, 8> ExitingBlocks;
8157   L->getExitingBlocks(ExitingBlocks);
8158 
8159   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8160 
8161   SmallVector<EdgeExitInfo, 4> ExitCounts;
8162   bool CouldComputeBECount = true;
8163   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8164   const SCEV *MustExitMaxBECount = nullptr;
8165   const SCEV *MayExitMaxBECount = nullptr;
8166   bool MustExitMaxOrZero = false;
8167 
8168   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8169   // and compute maxBECount.
8170   // Do a union of all the predicates here.
8171   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8172     BasicBlock *ExitBB = ExitingBlocks[i];
8173 
8174     // We canonicalize untaken exits to br (constant), ignore them so that
8175     // proving an exit untaken doesn't negatively impact our ability to reason
8176     // about the loop as whole.
8177     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8178       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8179         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8180         if (ExitIfTrue == CI->isZero())
8181           continue;
8182       }
8183 
8184     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8185 
8186     assert((AllowPredicates || EL.Predicates.empty()) &&
8187            "Predicated exit limit when predicates are not allowed!");
8188 
8189     // 1. For each exit that can be computed, add an entry to ExitCounts.
8190     // CouldComputeBECount is true only if all exits can be computed.
8191     if (EL.ExactNotTaken == getCouldNotCompute())
8192       // We couldn't compute an exact value for this exit, so
8193       // we won't be able to compute an exact value for the loop.
8194       CouldComputeBECount = false;
8195     else
8196       ExitCounts.emplace_back(ExitBB, EL);
8197 
8198     // 2. Derive the loop's MaxBECount from each exit's max number of
8199     // non-exiting iterations. Partition the loop exits into two kinds:
8200     // LoopMustExits and LoopMayExits.
8201     //
8202     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8203     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8204     // MaxBECount is the minimum EL.MaxNotTaken of computable
8205     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8206     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
8207     // computable EL.MaxNotTaken.
8208     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
8209         DT.dominates(ExitBB, Latch)) {
8210       if (!MustExitMaxBECount) {
8211         MustExitMaxBECount = EL.MaxNotTaken;
8212         MustExitMaxOrZero = EL.MaxOrZero;
8213       } else {
8214         MustExitMaxBECount =
8215             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
8216       }
8217     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8218       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
8219         MayExitMaxBECount = EL.MaxNotTaken;
8220       else {
8221         MayExitMaxBECount =
8222             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
8223       }
8224     }
8225   }
8226   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8227     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8228   // The loop backedge will be taken the maximum or zero times if there's
8229   // a single exit that must be taken the maximum or zero times.
8230   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8231 
8232   // Remember which SCEVs are used in exit limits for invalidation purposes.
8233   // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken
8234   // and MaxBECount, which must be SCEVConstant.
8235   for (const auto &Pair : ExitCounts)
8236     if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8237       BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8238   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8239                            MaxBECount, MaxOrZero);
8240 }
8241 
8242 ScalarEvolution::ExitLimit
8243 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8244                                       bool AllowPredicates) {
8245   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8246   // If our exiting block does not dominate the latch, then its connection with
8247   // loop's exit limit may be far from trivial.
8248   const BasicBlock *Latch = L->getLoopLatch();
8249   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8250     return getCouldNotCompute();
8251 
8252   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8253   Instruction *Term = ExitingBlock->getTerminator();
8254   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8255     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8256     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8257     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8258            "It should have one successor in loop and one exit block!");
8259     // Proceed to the next level to examine the exit condition expression.
8260     return computeExitLimitFromCond(
8261         L, BI->getCondition(), ExitIfTrue,
8262         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8263   }
8264 
8265   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8266     // For switch, make sure that there is a single exit from the loop.
8267     BasicBlock *Exit = nullptr;
8268     for (auto *SBB : successors(ExitingBlock))
8269       if (!L->contains(SBB)) {
8270         if (Exit) // Multiple exit successors.
8271           return getCouldNotCompute();
8272         Exit = SBB;
8273       }
8274     assert(Exit && "Exiting block must have at least one exit");
8275     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8276                                                 /*ControlsExit=*/IsOnlyExit);
8277   }
8278 
8279   return getCouldNotCompute();
8280 }
8281 
8282 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8283     const Loop *L, Value *ExitCond, bool ExitIfTrue,
8284     bool ControlsExit, bool AllowPredicates) {
8285   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8286   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8287                                         ControlsExit, AllowPredicates);
8288 }
8289 
8290 Optional<ScalarEvolution::ExitLimit>
8291 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8292                                       bool ExitIfTrue, bool ControlsExit,
8293                                       bool AllowPredicates) {
8294   (void)this->L;
8295   (void)this->ExitIfTrue;
8296   (void)this->AllowPredicates;
8297 
8298   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8299          this->AllowPredicates == AllowPredicates &&
8300          "Variance in assumed invariant key components!");
8301   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8302   if (Itr == TripCountMap.end())
8303     return None;
8304   return Itr->second;
8305 }
8306 
8307 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8308                                              bool ExitIfTrue,
8309                                              bool ControlsExit,
8310                                              bool AllowPredicates,
8311                                              const ExitLimit &EL) {
8312   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8313          this->AllowPredicates == AllowPredicates &&
8314          "Variance in assumed invariant key components!");
8315 
8316   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8317   assert(InsertResult.second && "Expected successful insertion!");
8318   (void)InsertResult;
8319   (void)ExitIfTrue;
8320 }
8321 
8322 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8323     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8324     bool ControlsExit, bool AllowPredicates) {
8325 
8326   if (auto MaybeEL =
8327           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8328     return *MaybeEL;
8329 
8330   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8331                                               ControlsExit, AllowPredicates);
8332   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8333   return EL;
8334 }
8335 
8336 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8337     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8338     bool ControlsExit, bool AllowPredicates) {
8339   // Handle BinOp conditions (And, Or).
8340   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8341           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8342     return *LimitFromBinOp;
8343 
8344   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8345   // Proceed to the next level to examine the icmp.
8346   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8347     ExitLimit EL =
8348         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8349     if (EL.hasFullInfo() || !AllowPredicates)
8350       return EL;
8351 
8352     // Try again, but use SCEV predicates this time.
8353     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8354                                     /*AllowPredicates=*/true);
8355   }
8356 
8357   // Check for a constant condition. These are normally stripped out by
8358   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8359   // preserve the CFG and is temporarily leaving constant conditions
8360   // in place.
8361   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8362     if (ExitIfTrue == !CI->getZExtValue())
8363       // The backedge is always taken.
8364       return getCouldNotCompute();
8365     else
8366       // The backedge is never taken.
8367       return getZero(CI->getType());
8368   }
8369 
8370   // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8371   // with a constant step, we can form an equivalent icmp predicate and figure
8372   // out how many iterations will be taken before we exit.
8373   const WithOverflowInst *WO;
8374   const APInt *C;
8375   if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8376       match(WO->getRHS(), m_APInt(C))) {
8377     ConstantRange NWR =
8378       ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8379                                            WO->getNoWrapKind());
8380     CmpInst::Predicate Pred;
8381     APInt NewRHSC, Offset;
8382     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8383     if (!ExitIfTrue)
8384       Pred = ICmpInst::getInversePredicate(Pred);
8385     auto *LHS = getSCEV(WO->getLHS());
8386     if (Offset != 0)
8387       LHS = getAddExpr(LHS, getConstant(Offset));
8388     auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8389                                        ControlsExit, AllowPredicates);
8390     if (EL.hasAnyInfo()) return EL;
8391   }
8392 
8393   // If it's not an integer or pointer comparison then compute it the hard way.
8394   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8395 }
8396 
8397 Optional<ScalarEvolution::ExitLimit>
8398 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8399     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8400     bool ControlsExit, bool AllowPredicates) {
8401   // Check if the controlling expression for this loop is an And or Or.
8402   Value *Op0, *Op1;
8403   bool IsAnd = false;
8404   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8405     IsAnd = true;
8406   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8407     IsAnd = false;
8408   else
8409     return None;
8410 
8411   // EitherMayExit is true in these two cases:
8412   //   br (and Op0 Op1), loop, exit
8413   //   br (or  Op0 Op1), exit, loop
8414   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8415   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
8416                                                  ControlsExit && !EitherMayExit,
8417                                                  AllowPredicates);
8418   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
8419                                                  ControlsExit && !EitherMayExit,
8420                                                  AllowPredicates);
8421 
8422   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8423   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8424   if (isa<ConstantInt>(Op1))
8425     return Op1 == NeutralElement ? EL0 : EL1;
8426   if (isa<ConstantInt>(Op0))
8427     return Op0 == NeutralElement ? EL1 : EL0;
8428 
8429   const SCEV *BECount = getCouldNotCompute();
8430   const SCEV *MaxBECount = getCouldNotCompute();
8431   if (EitherMayExit) {
8432     // Both conditions must be same for the loop to continue executing.
8433     // Choose the less conservative count.
8434     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8435         EL1.ExactNotTaken != getCouldNotCompute()) {
8436       BECount = getUMinFromMismatchedTypes(
8437           EL0.ExactNotTaken, EL1.ExactNotTaken,
8438           /*Sequential=*/!isa<BinaryOperator>(ExitCond));
8439 
8440       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
8441       // it should have been simplified to zero (see the condition (3) above)
8442       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
8443              BECount->isZero());
8444     }
8445     if (EL0.MaxNotTaken == getCouldNotCompute())
8446       MaxBECount = EL1.MaxNotTaken;
8447     else if (EL1.MaxNotTaken == getCouldNotCompute())
8448       MaxBECount = EL0.MaxNotTaken;
8449     else
8450       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
8451   } else {
8452     // Both conditions must be same at the same time for the loop to exit.
8453     // For now, be conservative.
8454     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8455       BECount = EL0.ExactNotTaken;
8456   }
8457 
8458   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8459   // to be more aggressive when computing BECount than when computing
8460   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
8461   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
8462   // to not.
8463   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
8464       !isa<SCEVCouldNotCompute>(BECount))
8465     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
8466 
8467   return ExitLimit(BECount, MaxBECount, false,
8468                    { &EL0.Predicates, &EL1.Predicates });
8469 }
8470 
8471 ScalarEvolution::ExitLimit
8472 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8473                                           ICmpInst *ExitCond,
8474                                           bool ExitIfTrue,
8475                                           bool ControlsExit,
8476                                           bool AllowPredicates) {
8477   // If the condition was exit on true, convert the condition to exit on false
8478   ICmpInst::Predicate Pred;
8479   if (!ExitIfTrue)
8480     Pred = ExitCond->getPredicate();
8481   else
8482     Pred = ExitCond->getInversePredicate();
8483   const ICmpInst::Predicate OriginalPred = Pred;
8484 
8485   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8486   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8487 
8488   ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit,
8489                                           AllowPredicates);
8490   if (EL.hasAnyInfo()) return EL;
8491 
8492   auto *ExhaustiveCount =
8493       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8494 
8495   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8496     return ExhaustiveCount;
8497 
8498   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8499                                       ExitCond->getOperand(1), L, OriginalPred);
8500 }
8501 ScalarEvolution::ExitLimit
8502 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8503                                           ICmpInst::Predicate Pred,
8504                                           const SCEV *LHS, const SCEV *RHS,
8505                                           bool ControlsExit,
8506                                           bool AllowPredicates) {
8507 
8508   // Try to evaluate any dependencies out of the loop.
8509   LHS = getSCEVAtScope(LHS, L);
8510   RHS = getSCEVAtScope(RHS, L);
8511 
8512   // At this point, we would like to compute how many iterations of the
8513   // loop the predicate will return true for these inputs.
8514   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8515     // If there is a loop-invariant, force it into the RHS.
8516     std::swap(LHS, RHS);
8517     Pred = ICmpInst::getSwappedPredicate(Pred);
8518   }
8519 
8520   bool ControllingFiniteLoop =
8521       ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L);
8522   // Simplify the operands before analyzing them.
8523   (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0,
8524                              (EnableFiniteLoopControl ? ControllingFiniteLoop
8525                                                      : false));
8526 
8527   // If we have a comparison of a chrec against a constant, try to use value
8528   // ranges to answer this query.
8529   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8530     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8531       if (AddRec->getLoop() == L) {
8532         // Form the constant range.
8533         ConstantRange CompRange =
8534             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8535 
8536         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8537         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8538       }
8539 
8540   // If this loop must exit based on this condition (or execute undefined
8541   // behaviour), and we can prove the test sequence produced must repeat
8542   // the same values on self-wrap of the IV, then we can infer that IV
8543   // doesn't self wrap because if it did, we'd have an infinite (undefined)
8544   // loop.
8545   if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
8546     // TODO: We can peel off any functions which are invertible *in L*.  Loop
8547     // invariant terms are effectively constants for our purposes here.
8548     auto *InnerLHS = LHS;
8549     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
8550       InnerLHS = ZExt->getOperand();
8551     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
8552       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
8553       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
8554           StrideC && StrideC->getAPInt().isPowerOf2()) {
8555         auto Flags = AR->getNoWrapFlags();
8556         Flags = setFlags(Flags, SCEV::FlagNW);
8557         SmallVector<const SCEV*> Operands{AR->operands()};
8558         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
8559         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
8560       }
8561     }
8562   }
8563 
8564   switch (Pred) {
8565   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8566     // Convert to: while (X-Y != 0)
8567     if (LHS->getType()->isPointerTy()) {
8568       LHS = getLosslessPtrToIntExpr(LHS);
8569       if (isa<SCEVCouldNotCompute>(LHS))
8570         return LHS;
8571     }
8572     if (RHS->getType()->isPointerTy()) {
8573       RHS = getLosslessPtrToIntExpr(RHS);
8574       if (isa<SCEVCouldNotCompute>(RHS))
8575         return RHS;
8576     }
8577     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8578                                 AllowPredicates);
8579     if (EL.hasAnyInfo()) return EL;
8580     break;
8581   }
8582   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8583     // Convert to: while (X-Y == 0)
8584     if (LHS->getType()->isPointerTy()) {
8585       LHS = getLosslessPtrToIntExpr(LHS);
8586       if (isa<SCEVCouldNotCompute>(LHS))
8587         return LHS;
8588     }
8589     if (RHS->getType()->isPointerTy()) {
8590       RHS = getLosslessPtrToIntExpr(RHS);
8591       if (isa<SCEVCouldNotCompute>(RHS))
8592         return RHS;
8593     }
8594     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8595     if (EL.hasAnyInfo()) return EL;
8596     break;
8597   }
8598   case ICmpInst::ICMP_SLT:
8599   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8600     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8601     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8602                                     AllowPredicates);
8603     if (EL.hasAnyInfo()) return EL;
8604     break;
8605   }
8606   case ICmpInst::ICMP_SGT:
8607   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8608     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8609     ExitLimit EL =
8610         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8611                             AllowPredicates);
8612     if (EL.hasAnyInfo()) return EL;
8613     break;
8614   }
8615   default:
8616     break;
8617   }
8618 
8619   return getCouldNotCompute();
8620 }
8621 
8622 ScalarEvolution::ExitLimit
8623 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8624                                                       SwitchInst *Switch,
8625                                                       BasicBlock *ExitingBlock,
8626                                                       bool ControlsExit) {
8627   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8628 
8629   // Give up if the exit is the default dest of a switch.
8630   if (Switch->getDefaultDest() == ExitingBlock)
8631     return getCouldNotCompute();
8632 
8633   assert(L->contains(Switch->getDefaultDest()) &&
8634          "Default case must not exit the loop!");
8635   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8636   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8637 
8638   // while (X != Y) --> while (X-Y != 0)
8639   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8640   if (EL.hasAnyInfo())
8641     return EL;
8642 
8643   return getCouldNotCompute();
8644 }
8645 
8646 static ConstantInt *
8647 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8648                                 ScalarEvolution &SE) {
8649   const SCEV *InVal = SE.getConstant(C);
8650   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8651   assert(isa<SCEVConstant>(Val) &&
8652          "Evaluation of SCEV at constant didn't fold correctly?");
8653   return cast<SCEVConstant>(Val)->getValue();
8654 }
8655 
8656 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8657     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8658   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8659   if (!RHS)
8660     return getCouldNotCompute();
8661 
8662   const BasicBlock *Latch = L->getLoopLatch();
8663   if (!Latch)
8664     return getCouldNotCompute();
8665 
8666   const BasicBlock *Predecessor = L->getLoopPredecessor();
8667   if (!Predecessor)
8668     return getCouldNotCompute();
8669 
8670   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8671   // Return LHS in OutLHS and shift_opt in OutOpCode.
8672   auto MatchPositiveShift =
8673       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8674 
8675     using namespace PatternMatch;
8676 
8677     ConstantInt *ShiftAmt;
8678     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8679       OutOpCode = Instruction::LShr;
8680     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8681       OutOpCode = Instruction::AShr;
8682     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8683       OutOpCode = Instruction::Shl;
8684     else
8685       return false;
8686 
8687     return ShiftAmt->getValue().isStrictlyPositive();
8688   };
8689 
8690   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8691   //
8692   // loop:
8693   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8694   //   %iv.shifted = lshr i32 %iv, <positive constant>
8695   //
8696   // Return true on a successful match.  Return the corresponding PHI node (%iv
8697   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8698   auto MatchShiftRecurrence =
8699       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8700     Optional<Instruction::BinaryOps> PostShiftOpCode;
8701 
8702     {
8703       Instruction::BinaryOps OpC;
8704       Value *V;
8705 
8706       // If we encounter a shift instruction, "peel off" the shift operation,
8707       // and remember that we did so.  Later when we inspect %iv's backedge
8708       // value, we will make sure that the backedge value uses the same
8709       // operation.
8710       //
8711       // Note: the peeled shift operation does not have to be the same
8712       // instruction as the one feeding into the PHI's backedge value.  We only
8713       // really care about it being the same *kind* of shift instruction --
8714       // that's all that is required for our later inferences to hold.
8715       if (MatchPositiveShift(LHS, V, OpC)) {
8716         PostShiftOpCode = OpC;
8717         LHS = V;
8718       }
8719     }
8720 
8721     PNOut = dyn_cast<PHINode>(LHS);
8722     if (!PNOut || PNOut->getParent() != L->getHeader())
8723       return false;
8724 
8725     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8726     Value *OpLHS;
8727 
8728     return
8729         // The backedge value for the PHI node must be a shift by a positive
8730         // amount
8731         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8732 
8733         // of the PHI node itself
8734         OpLHS == PNOut &&
8735 
8736         // and the kind of shift should be match the kind of shift we peeled
8737         // off, if any.
8738         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8739   };
8740 
8741   PHINode *PN;
8742   Instruction::BinaryOps OpCode;
8743   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8744     return getCouldNotCompute();
8745 
8746   const DataLayout &DL = getDataLayout();
8747 
8748   // The key rationale for this optimization is that for some kinds of shift
8749   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8750   // within a finite number of iterations.  If the condition guarding the
8751   // backedge (in the sense that the backedge is taken if the condition is true)
8752   // is false for the value the shift recurrence stabilizes to, then we know
8753   // that the backedge is taken only a finite number of times.
8754 
8755   ConstantInt *StableValue = nullptr;
8756   switch (OpCode) {
8757   default:
8758     llvm_unreachable("Impossible case!");
8759 
8760   case Instruction::AShr: {
8761     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8762     // bitwidth(K) iterations.
8763     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8764     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8765                                        Predecessor->getTerminator(), &DT);
8766     auto *Ty = cast<IntegerType>(RHS->getType());
8767     if (Known.isNonNegative())
8768       StableValue = ConstantInt::get(Ty, 0);
8769     else if (Known.isNegative())
8770       StableValue = ConstantInt::get(Ty, -1, true);
8771     else
8772       return getCouldNotCompute();
8773 
8774     break;
8775   }
8776   case Instruction::LShr:
8777   case Instruction::Shl:
8778     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8779     // stabilize to 0 in at most bitwidth(K) iterations.
8780     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8781     break;
8782   }
8783 
8784   auto *Result =
8785       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8786   assert(Result->getType()->isIntegerTy(1) &&
8787          "Otherwise cannot be an operand to a branch instruction");
8788 
8789   if (Result->isZeroValue()) {
8790     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8791     const SCEV *UpperBound =
8792         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8793     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8794   }
8795 
8796   return getCouldNotCompute();
8797 }
8798 
8799 /// Return true if we can constant fold an instruction of the specified type,
8800 /// assuming that all operands were constants.
8801 static bool CanConstantFold(const Instruction *I) {
8802   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8803       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8804       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8805     return true;
8806 
8807   if (const CallInst *CI = dyn_cast<CallInst>(I))
8808     if (const Function *F = CI->getCalledFunction())
8809       return canConstantFoldCallTo(CI, F);
8810   return false;
8811 }
8812 
8813 /// Determine whether this instruction can constant evolve within this loop
8814 /// assuming its operands can all constant evolve.
8815 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8816   // An instruction outside of the loop can't be derived from a loop PHI.
8817   if (!L->contains(I)) return false;
8818 
8819   if (isa<PHINode>(I)) {
8820     // We don't currently keep track of the control flow needed to evaluate
8821     // PHIs, so we cannot handle PHIs inside of loops.
8822     return L->getHeader() == I->getParent();
8823   }
8824 
8825   // If we won't be able to constant fold this expression even if the operands
8826   // are constants, bail early.
8827   return CanConstantFold(I);
8828 }
8829 
8830 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8831 /// recursing through each instruction operand until reaching a loop header phi.
8832 static PHINode *
8833 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8834                                DenseMap<Instruction *, PHINode *> &PHIMap,
8835                                unsigned Depth) {
8836   if (Depth > MaxConstantEvolvingDepth)
8837     return nullptr;
8838 
8839   // Otherwise, we can evaluate this instruction if all of its operands are
8840   // constant or derived from a PHI node themselves.
8841   PHINode *PHI = nullptr;
8842   for (Value *Op : UseInst->operands()) {
8843     if (isa<Constant>(Op)) continue;
8844 
8845     Instruction *OpInst = dyn_cast<Instruction>(Op);
8846     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8847 
8848     PHINode *P = dyn_cast<PHINode>(OpInst);
8849     if (!P)
8850       // If this operand is already visited, reuse the prior result.
8851       // We may have P != PHI if this is the deepest point at which the
8852       // inconsistent paths meet.
8853       P = PHIMap.lookup(OpInst);
8854     if (!P) {
8855       // Recurse and memoize the results, whether a phi is found or not.
8856       // This recursive call invalidates pointers into PHIMap.
8857       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8858       PHIMap[OpInst] = P;
8859     }
8860     if (!P)
8861       return nullptr;  // Not evolving from PHI
8862     if (PHI && PHI != P)
8863       return nullptr;  // Evolving from multiple different PHIs.
8864     PHI = P;
8865   }
8866   // This is a expression evolving from a constant PHI!
8867   return PHI;
8868 }
8869 
8870 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8871 /// in the loop that V is derived from.  We allow arbitrary operations along the
8872 /// way, but the operands of an operation must either be constants or a value
8873 /// derived from a constant PHI.  If this expression does not fit with these
8874 /// constraints, return null.
8875 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8876   Instruction *I = dyn_cast<Instruction>(V);
8877   if (!I || !canConstantEvolve(I, L)) return nullptr;
8878 
8879   if (PHINode *PN = dyn_cast<PHINode>(I))
8880     return PN;
8881 
8882   // Record non-constant instructions contained by the loop.
8883   DenseMap<Instruction *, PHINode *> PHIMap;
8884   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8885 }
8886 
8887 /// EvaluateExpression - Given an expression that passes the
8888 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8889 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8890 /// reason, return null.
8891 static Constant *EvaluateExpression(Value *V, const Loop *L,
8892                                     DenseMap<Instruction *, Constant *> &Vals,
8893                                     const DataLayout &DL,
8894                                     const TargetLibraryInfo *TLI) {
8895   // Convenient constant check, but redundant for recursive calls.
8896   if (Constant *C = dyn_cast<Constant>(V)) return C;
8897   Instruction *I = dyn_cast<Instruction>(V);
8898   if (!I) return nullptr;
8899 
8900   if (Constant *C = Vals.lookup(I)) return C;
8901 
8902   // An instruction inside the loop depends on a value outside the loop that we
8903   // weren't given a mapping for, or a value such as a call inside the loop.
8904   if (!canConstantEvolve(I, L)) return nullptr;
8905 
8906   // An unmapped PHI can be due to a branch or another loop inside this loop,
8907   // or due to this not being the initial iteration through a loop where we
8908   // couldn't compute the evolution of this particular PHI last time.
8909   if (isa<PHINode>(I)) return nullptr;
8910 
8911   std::vector<Constant*> Operands(I->getNumOperands());
8912 
8913   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8914     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8915     if (!Operand) {
8916       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8917       if (!Operands[i]) return nullptr;
8918       continue;
8919     }
8920     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8921     Vals[Operand] = C;
8922     if (!C) return nullptr;
8923     Operands[i] = C;
8924   }
8925 
8926   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8927     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8928                                            Operands[1], DL, TLI);
8929   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8930     if (!LI->isVolatile())
8931       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8932   }
8933   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8934 }
8935 
8936 
8937 // If every incoming value to PN except the one for BB is a specific Constant,
8938 // return that, else return nullptr.
8939 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8940   Constant *IncomingVal = nullptr;
8941 
8942   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8943     if (PN->getIncomingBlock(i) == BB)
8944       continue;
8945 
8946     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8947     if (!CurrentVal)
8948       return nullptr;
8949 
8950     if (IncomingVal != CurrentVal) {
8951       if (IncomingVal)
8952         return nullptr;
8953       IncomingVal = CurrentVal;
8954     }
8955   }
8956 
8957   return IncomingVal;
8958 }
8959 
8960 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8961 /// in the header of its containing loop, we know the loop executes a
8962 /// constant number of times, and the PHI node is just a recurrence
8963 /// involving constants, fold it.
8964 Constant *
8965 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8966                                                    const APInt &BEs,
8967                                                    const Loop *L) {
8968   auto I = ConstantEvolutionLoopExitValue.find(PN);
8969   if (I != ConstantEvolutionLoopExitValue.end())
8970     return I->second;
8971 
8972   if (BEs.ugt(MaxBruteForceIterations))
8973     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8974 
8975   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8976 
8977   DenseMap<Instruction *, Constant *> CurrentIterVals;
8978   BasicBlock *Header = L->getHeader();
8979   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8980 
8981   BasicBlock *Latch = L->getLoopLatch();
8982   if (!Latch)
8983     return nullptr;
8984 
8985   for (PHINode &PHI : Header->phis()) {
8986     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8987       CurrentIterVals[&PHI] = StartCST;
8988   }
8989   if (!CurrentIterVals.count(PN))
8990     return RetVal = nullptr;
8991 
8992   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8993 
8994   // Execute the loop symbolically to determine the exit value.
8995   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8996          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8997 
8998   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8999   unsigned IterationNum = 0;
9000   const DataLayout &DL = getDataLayout();
9001   for (; ; ++IterationNum) {
9002     if (IterationNum == NumIterations)
9003       return RetVal = CurrentIterVals[PN];  // Got exit value!
9004 
9005     // Compute the value of the PHIs for the next iteration.
9006     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9007     DenseMap<Instruction *, Constant *> NextIterVals;
9008     Constant *NextPHI =
9009         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9010     if (!NextPHI)
9011       return nullptr;        // Couldn't evaluate!
9012     NextIterVals[PN] = NextPHI;
9013 
9014     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9015 
9016     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
9017     // cease to be able to evaluate one of them or if they stop evolving,
9018     // because that doesn't necessarily prevent us from computing PN.
9019     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9020     for (const auto &I : CurrentIterVals) {
9021       PHINode *PHI = dyn_cast<PHINode>(I.first);
9022       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9023       PHIsToCompute.emplace_back(PHI, I.second);
9024     }
9025     // We use two distinct loops because EvaluateExpression may invalidate any
9026     // iterators into CurrentIterVals.
9027     for (const auto &I : PHIsToCompute) {
9028       PHINode *PHI = I.first;
9029       Constant *&NextPHI = NextIterVals[PHI];
9030       if (!NextPHI) {   // Not already computed.
9031         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9032         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9033       }
9034       if (NextPHI != I.second)
9035         StoppedEvolving = false;
9036     }
9037 
9038     // If all entries in CurrentIterVals == NextIterVals then we can stop
9039     // iterating, the loop can't continue to change.
9040     if (StoppedEvolving)
9041       return RetVal = CurrentIterVals[PN];
9042 
9043     CurrentIterVals.swap(NextIterVals);
9044   }
9045 }
9046 
9047 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9048                                                           Value *Cond,
9049                                                           bool ExitWhen) {
9050   PHINode *PN = getConstantEvolvingPHI(Cond, L);
9051   if (!PN) return getCouldNotCompute();
9052 
9053   // If the loop is canonicalized, the PHI will have exactly two entries.
9054   // That's the only form we support here.
9055   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9056 
9057   DenseMap<Instruction *, Constant *> CurrentIterVals;
9058   BasicBlock *Header = L->getHeader();
9059   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9060 
9061   BasicBlock *Latch = L->getLoopLatch();
9062   assert(Latch && "Should follow from NumIncomingValues == 2!");
9063 
9064   for (PHINode &PHI : Header->phis()) {
9065     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9066       CurrentIterVals[&PHI] = StartCST;
9067   }
9068   if (!CurrentIterVals.count(PN))
9069     return getCouldNotCompute();
9070 
9071   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
9072   // the loop symbolically to determine when the condition gets a value of
9073   // "ExitWhen".
9074   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
9075   const DataLayout &DL = getDataLayout();
9076   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9077     auto *CondVal = dyn_cast_or_null<ConstantInt>(
9078         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9079 
9080     // Couldn't symbolically evaluate.
9081     if (!CondVal) return getCouldNotCompute();
9082 
9083     if (CondVal->getValue() == uint64_t(ExitWhen)) {
9084       ++NumBruteForceTripCountsComputed;
9085       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9086     }
9087 
9088     // Update all the PHI nodes for the next iteration.
9089     DenseMap<Instruction *, Constant *> NextIterVals;
9090 
9091     // Create a list of which PHIs we need to compute. We want to do this before
9092     // calling EvaluateExpression on them because that may invalidate iterators
9093     // into CurrentIterVals.
9094     SmallVector<PHINode *, 8> PHIsToCompute;
9095     for (const auto &I : CurrentIterVals) {
9096       PHINode *PHI = dyn_cast<PHINode>(I.first);
9097       if (!PHI || PHI->getParent() != Header) continue;
9098       PHIsToCompute.push_back(PHI);
9099     }
9100     for (PHINode *PHI : PHIsToCompute) {
9101       Constant *&NextPHI = NextIterVals[PHI];
9102       if (NextPHI) continue;    // Already computed!
9103 
9104       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9105       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9106     }
9107     CurrentIterVals.swap(NextIterVals);
9108   }
9109 
9110   // Too many iterations were needed to evaluate.
9111   return getCouldNotCompute();
9112 }
9113 
9114 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9115   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9116       ValuesAtScopes[V];
9117   // Check to see if we've folded this expression at this loop before.
9118   for (auto &LS : Values)
9119     if (LS.first == L)
9120       return LS.second ? LS.second : V;
9121 
9122   Values.emplace_back(L, nullptr);
9123 
9124   // Otherwise compute it.
9125   const SCEV *C = computeSCEVAtScope(V, L);
9126   for (auto &LS : reverse(ValuesAtScopes[V]))
9127     if (LS.first == L) {
9128       LS.second = C;
9129       if (!isa<SCEVConstant>(C))
9130         ValuesAtScopesUsers[C].push_back({L, V});
9131       break;
9132     }
9133   return C;
9134 }
9135 
9136 /// This builds up a Constant using the ConstantExpr interface.  That way, we
9137 /// will return Constants for objects which aren't represented by a
9138 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9139 /// Returns NULL if the SCEV isn't representable as a Constant.
9140 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9141   switch (V->getSCEVType()) {
9142   case scCouldNotCompute:
9143   case scAddRecExpr:
9144     return nullptr;
9145   case scConstant:
9146     return cast<SCEVConstant>(V)->getValue();
9147   case scUnknown:
9148     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9149   case scSignExtend: {
9150     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
9151     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
9152       return ConstantExpr::getSExt(CastOp, SS->getType());
9153     return nullptr;
9154   }
9155   case scZeroExtend: {
9156     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
9157     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
9158       return ConstantExpr::getZExt(CastOp, SZ->getType());
9159     return nullptr;
9160   }
9161   case scPtrToInt: {
9162     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9163     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9164       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9165 
9166     return nullptr;
9167   }
9168   case scTruncate: {
9169     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9170     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9171       return ConstantExpr::getTrunc(CastOp, ST->getType());
9172     return nullptr;
9173   }
9174   case scAddExpr: {
9175     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9176     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
9177       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
9178         unsigned AS = PTy->getAddressSpace();
9179         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9180         C = ConstantExpr::getBitCast(C, DestPtrTy);
9181       }
9182       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
9183         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
9184         if (!C2)
9185           return nullptr;
9186 
9187         // First pointer!
9188         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
9189           unsigned AS = C2->getType()->getPointerAddressSpace();
9190           std::swap(C, C2);
9191           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9192           // The offsets have been converted to bytes.  We can add bytes to an
9193           // i8* by GEP with the byte count in the first index.
9194           C = ConstantExpr::getBitCast(C, DestPtrTy);
9195         }
9196 
9197         // Don't bother trying to sum two pointers. We probably can't
9198         // statically compute a load that results from it anyway.
9199         if (C2->getType()->isPointerTy())
9200           return nullptr;
9201 
9202         if (C->getType()->isPointerTy()) {
9203           C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9204                                              C, C2);
9205         } else {
9206           C = ConstantExpr::getAdd(C, C2);
9207         }
9208       }
9209       return C;
9210     }
9211     return nullptr;
9212   }
9213   case scMulExpr: {
9214     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9215     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
9216       // Don't bother with pointers at all.
9217       if (C->getType()->isPointerTy())
9218         return nullptr;
9219       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
9220         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
9221         if (!C2 || C2->getType()->isPointerTy())
9222           return nullptr;
9223         C = ConstantExpr::getMul(C, C2);
9224       }
9225       return C;
9226     }
9227     return nullptr;
9228   }
9229   case scUDivExpr: {
9230     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
9231     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
9232       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
9233         if (LHS->getType() == RHS->getType())
9234           return ConstantExpr::getUDiv(LHS, RHS);
9235     return nullptr;
9236   }
9237   case scSMaxExpr:
9238   case scUMaxExpr:
9239   case scSMinExpr:
9240   case scUMinExpr:
9241   case scSequentialUMinExpr:
9242     return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
9243   }
9244   llvm_unreachable("Unknown SCEV kind!");
9245 }
9246 
9247 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9248   if (isa<SCEVConstant>(V)) return V;
9249 
9250   // If this instruction is evolved from a constant-evolving PHI, compute the
9251   // exit value from the loop without using SCEVs.
9252   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
9253     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
9254       if (PHINode *PN = dyn_cast<PHINode>(I)) {
9255         const Loop *CurrLoop = this->LI[I->getParent()];
9256         // Looking for loop exit value.
9257         if (CurrLoop && CurrLoop->getParentLoop() == L &&
9258             PN->getParent() == CurrLoop->getHeader()) {
9259           // Okay, there is no closed form solution for the PHI node.  Check
9260           // to see if the loop that contains it has a known backedge-taken
9261           // count.  If so, we may be able to force computation of the exit
9262           // value.
9263           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9264           // This trivial case can show up in some degenerate cases where
9265           // the incoming IR has not yet been fully simplified.
9266           if (BackedgeTakenCount->isZero()) {
9267             Value *InitValue = nullptr;
9268             bool MultipleInitValues = false;
9269             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9270               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9271                 if (!InitValue)
9272                   InitValue = PN->getIncomingValue(i);
9273                 else if (InitValue != PN->getIncomingValue(i)) {
9274                   MultipleInitValues = true;
9275                   break;
9276                 }
9277               }
9278             }
9279             if (!MultipleInitValues && InitValue)
9280               return getSCEV(InitValue);
9281           }
9282           // Do we have a loop invariant value flowing around the backedge
9283           // for a loop which must execute the backedge?
9284           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9285               isKnownPositive(BackedgeTakenCount) &&
9286               PN->getNumIncomingValues() == 2) {
9287 
9288             unsigned InLoopPred =
9289                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9290             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9291             if (CurrLoop->isLoopInvariant(BackedgeVal))
9292               return getSCEV(BackedgeVal);
9293           }
9294           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9295             // Okay, we know how many times the containing loop executes.  If
9296             // this is a constant evolving PHI node, get the final value at
9297             // the specified iteration number.
9298             Constant *RV = getConstantEvolutionLoopExitValue(
9299                 PN, BTCC->getAPInt(), CurrLoop);
9300             if (RV) return getSCEV(RV);
9301           }
9302         }
9303 
9304         // If there is a single-input Phi, evaluate it at our scope. If we can
9305         // prove that this replacement does not break LCSSA form, use new value.
9306         if (PN->getNumOperands() == 1) {
9307           const SCEV *Input = getSCEV(PN->getOperand(0));
9308           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
9309           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
9310           // for the simplest case just support constants.
9311           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
9312         }
9313       }
9314 
9315       // Okay, this is an expression that we cannot symbolically evaluate
9316       // into a SCEV.  Check to see if it's possible to symbolically evaluate
9317       // the arguments into constants, and if so, try to constant propagate the
9318       // result.  This is particularly useful for computing loop exit values.
9319       if (CanConstantFold(I)) {
9320         SmallVector<Constant *, 4> Operands;
9321         bool MadeImprovement = false;
9322         for (Value *Op : I->operands()) {
9323           if (Constant *C = dyn_cast<Constant>(Op)) {
9324             Operands.push_back(C);
9325             continue;
9326           }
9327 
9328           // If any of the operands is non-constant and if they are
9329           // non-integer and non-pointer, don't even try to analyze them
9330           // with scev techniques.
9331           if (!isSCEVable(Op->getType()))
9332             return V;
9333 
9334           const SCEV *OrigV = getSCEV(Op);
9335           const SCEV *OpV = getSCEVAtScope(OrigV, L);
9336           MadeImprovement |= OrigV != OpV;
9337 
9338           Constant *C = BuildConstantFromSCEV(OpV);
9339           if (!C) return V;
9340           if (C->getType() != Op->getType())
9341             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
9342                                                               Op->getType(),
9343                                                               false),
9344                                       C, Op->getType());
9345           Operands.push_back(C);
9346         }
9347 
9348         // Check to see if getSCEVAtScope actually made an improvement.
9349         if (MadeImprovement) {
9350           Constant *C = nullptr;
9351           const DataLayout &DL = getDataLayout();
9352           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
9353             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9354                                                 Operands[1], DL, &TLI);
9355           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
9356             if (!Load->isVolatile())
9357               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
9358                                                DL);
9359           } else
9360             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9361           if (!C) return V;
9362           return getSCEV(C);
9363         }
9364       }
9365     }
9366 
9367     // This is some other type of SCEVUnknown, just return it.
9368     return V;
9369   }
9370 
9371   if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) {
9372     const auto *Comm = cast<SCEVNAryExpr>(V);
9373     // Avoid performing the look-up in the common case where the specified
9374     // expression has no loop-variant portions.
9375     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
9376       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9377       if (OpAtScope != Comm->getOperand(i)) {
9378         // Okay, at least one of these operands is loop variant but might be
9379         // foldable.  Build a new instance of the folded commutative expression.
9380         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
9381                                             Comm->op_begin()+i);
9382         NewOps.push_back(OpAtScope);
9383 
9384         for (++i; i != e; ++i) {
9385           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9386           NewOps.push_back(OpAtScope);
9387         }
9388         if (isa<SCEVAddExpr>(Comm))
9389           return getAddExpr(NewOps, Comm->getNoWrapFlags());
9390         if (isa<SCEVMulExpr>(Comm))
9391           return getMulExpr(NewOps, Comm->getNoWrapFlags());
9392         if (isa<SCEVMinMaxExpr>(Comm))
9393           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
9394         if (isa<SCEVSequentialMinMaxExpr>(Comm))
9395           return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps);
9396         llvm_unreachable("Unknown commutative / sequential min/max SCEV type!");
9397       }
9398     }
9399     // If we got here, all operands are loop invariant.
9400     return Comm;
9401   }
9402 
9403   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
9404     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
9405     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
9406     if (LHS == Div->getLHS() && RHS == Div->getRHS())
9407       return Div;   // must be loop invariant
9408     return getUDivExpr(LHS, RHS);
9409   }
9410 
9411   // If this is a loop recurrence for a loop that does not contain L, then we
9412   // are dealing with the final value computed by the loop.
9413   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
9414     // First, attempt to evaluate each operand.
9415     // Avoid performing the look-up in the common case where the specified
9416     // expression has no loop-variant portions.
9417     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9418       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9419       if (OpAtScope == AddRec->getOperand(i))
9420         continue;
9421 
9422       // Okay, at least one of these operands is loop variant but might be
9423       // foldable.  Build a new instance of the folded commutative expression.
9424       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9425                                           AddRec->op_begin()+i);
9426       NewOps.push_back(OpAtScope);
9427       for (++i; i != e; ++i)
9428         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9429 
9430       const SCEV *FoldedRec =
9431         getAddRecExpr(NewOps, AddRec->getLoop(),
9432                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9433       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9434       // The addrec may be folded to a nonrecurrence, for example, if the
9435       // induction variable is multiplied by zero after constant folding. Go
9436       // ahead and return the folded value.
9437       if (!AddRec)
9438         return FoldedRec;
9439       break;
9440     }
9441 
9442     // If the scope is outside the addrec's loop, evaluate it by using the
9443     // loop exit value of the addrec.
9444     if (!AddRec->getLoop()->contains(L)) {
9445       // To evaluate this recurrence, we need to know how many times the AddRec
9446       // loop iterates.  Compute this now.
9447       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9448       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9449 
9450       // Then, evaluate the AddRec.
9451       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9452     }
9453 
9454     return AddRec;
9455   }
9456 
9457   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
9458     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9459     if (Op == Cast->getOperand())
9460       return Cast;  // must be loop invariant
9461     return getCastExpr(Cast->getSCEVType(), Op, Cast->getType());
9462   }
9463 
9464   llvm_unreachable("Unknown SCEV type!");
9465 }
9466 
9467 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9468   return getSCEVAtScope(getSCEV(V), L);
9469 }
9470 
9471 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9472   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9473     return stripInjectiveFunctions(ZExt->getOperand());
9474   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9475     return stripInjectiveFunctions(SExt->getOperand());
9476   return S;
9477 }
9478 
9479 /// Finds the minimum unsigned root of the following equation:
9480 ///
9481 ///     A * X = B (mod N)
9482 ///
9483 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9484 /// A and B isn't important.
9485 ///
9486 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9487 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9488                                                ScalarEvolution &SE) {
9489   uint32_t BW = A.getBitWidth();
9490   assert(BW == SE.getTypeSizeInBits(B->getType()));
9491   assert(A != 0 && "A must be non-zero.");
9492 
9493   // 1. D = gcd(A, N)
9494   //
9495   // The gcd of A and N may have only one prime factor: 2. The number of
9496   // trailing zeros in A is its multiplicity
9497   uint32_t Mult2 = A.countTrailingZeros();
9498   // D = 2^Mult2
9499 
9500   // 2. Check if B is divisible by D.
9501   //
9502   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9503   // is not less than multiplicity of this prime factor for D.
9504   if (SE.GetMinTrailingZeros(B) < Mult2)
9505     return SE.getCouldNotCompute();
9506 
9507   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9508   // modulo (N / D).
9509   //
9510   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9511   // (N / D) in general. The inverse itself always fits into BW bits, though,
9512   // so we immediately truncate it.
9513   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9514   APInt Mod(BW + 1, 0);
9515   Mod.setBit(BW - Mult2);  // Mod = N / D
9516   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9517 
9518   // 4. Compute the minimum unsigned root of the equation:
9519   // I * (B / D) mod (N / D)
9520   // To simplify the computation, we factor out the divide by D:
9521   // (I * B mod N) / D
9522   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9523   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9524 }
9525 
9526 /// For a given quadratic addrec, generate coefficients of the corresponding
9527 /// quadratic equation, multiplied by a common value to ensure that they are
9528 /// integers.
9529 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9530 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9531 /// were multiplied by, and BitWidth is the bit width of the original addrec
9532 /// coefficients.
9533 /// This function returns None if the addrec coefficients are not compile-
9534 /// time constants.
9535 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9536 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9537   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9538   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9539   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9540   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9541   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9542                     << *AddRec << '\n');
9543 
9544   // We currently can only solve this if the coefficients are constants.
9545   if (!LC || !MC || !NC) {
9546     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9547     return None;
9548   }
9549 
9550   APInt L = LC->getAPInt();
9551   APInt M = MC->getAPInt();
9552   APInt N = NC->getAPInt();
9553   assert(!N.isZero() && "This is not a quadratic addrec");
9554 
9555   unsigned BitWidth = LC->getAPInt().getBitWidth();
9556   unsigned NewWidth = BitWidth + 1;
9557   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9558                     << BitWidth << '\n');
9559   // The sign-extension (as opposed to a zero-extension) here matches the
9560   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9561   N = N.sext(NewWidth);
9562   M = M.sext(NewWidth);
9563   L = L.sext(NewWidth);
9564 
9565   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9566   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9567   //   L+M, L+2M+N, L+3M+3N, ...
9568   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9569   //
9570   // The equation Acc = 0 is then
9571   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9572   // In a quadratic form it becomes:
9573   //   N n^2 + (2M-N) n + 2L = 0.
9574 
9575   APInt A = N;
9576   APInt B = 2 * M - A;
9577   APInt C = 2 * L;
9578   APInt T = APInt(NewWidth, 2);
9579   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9580                     << "x + " << C << ", coeff bw: " << NewWidth
9581                     << ", multiplied by " << T << '\n');
9582   return std::make_tuple(A, B, C, T, BitWidth);
9583 }
9584 
9585 /// Helper function to compare optional APInts:
9586 /// (a) if X and Y both exist, return min(X, Y),
9587 /// (b) if neither X nor Y exist, return None,
9588 /// (c) if exactly one of X and Y exists, return that value.
9589 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9590   if (X.hasValue() && Y.hasValue()) {
9591     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9592     APInt XW = X->sextOrSelf(W);
9593     APInt YW = Y->sextOrSelf(W);
9594     return XW.slt(YW) ? *X : *Y;
9595   }
9596   if (!X.hasValue() && !Y.hasValue())
9597     return None;
9598   return X.hasValue() ? *X : *Y;
9599 }
9600 
9601 /// Helper function to truncate an optional APInt to a given BitWidth.
9602 /// When solving addrec-related equations, it is preferable to return a value
9603 /// that has the same bit width as the original addrec's coefficients. If the
9604 /// solution fits in the original bit width, truncate it (except for i1).
9605 /// Returning a value of a different bit width may inhibit some optimizations.
9606 ///
9607 /// In general, a solution to a quadratic equation generated from an addrec
9608 /// may require BW+1 bits, where BW is the bit width of the addrec's
9609 /// coefficients. The reason is that the coefficients of the quadratic
9610 /// equation are BW+1 bits wide (to avoid truncation when converting from
9611 /// the addrec to the equation).
9612 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9613   if (!X.hasValue())
9614     return None;
9615   unsigned W = X->getBitWidth();
9616   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9617     return X->trunc(BitWidth);
9618   return X;
9619 }
9620 
9621 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9622 /// iterations. The values L, M, N are assumed to be signed, and they
9623 /// should all have the same bit widths.
9624 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9625 /// where BW is the bit width of the addrec's coefficients.
9626 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9627 /// returned as such, otherwise the bit width of the returned value may
9628 /// be greater than BW.
9629 ///
9630 /// This function returns None if
9631 /// (a) the addrec coefficients are not constant, or
9632 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9633 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9634 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9635 static Optional<APInt>
9636 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9637   APInt A, B, C, M;
9638   unsigned BitWidth;
9639   auto T = GetQuadraticEquation(AddRec);
9640   if (!T.hasValue())
9641     return None;
9642 
9643   std::tie(A, B, C, M, BitWidth) = *T;
9644   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9645   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9646   if (!X.hasValue())
9647     return None;
9648 
9649   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9650   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9651   if (!V->isZero())
9652     return None;
9653 
9654   return TruncIfPossible(X, BitWidth);
9655 }
9656 
9657 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9658 /// iterations. The values M, N are assumed to be signed, and they
9659 /// should all have the same bit widths.
9660 /// Find the least n such that c(n) does not belong to the given range,
9661 /// while c(n-1) does.
9662 ///
9663 /// This function returns None if
9664 /// (a) the addrec coefficients are not constant, or
9665 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9666 ///     bounds of the range.
9667 static Optional<APInt>
9668 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9669                           const ConstantRange &Range, ScalarEvolution &SE) {
9670   assert(AddRec->getOperand(0)->isZero() &&
9671          "Starting value of addrec should be 0");
9672   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9673                     << Range << ", addrec " << *AddRec << '\n');
9674   // This case is handled in getNumIterationsInRange. Here we can assume that
9675   // we start in the range.
9676   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9677          "Addrec's initial value should be in range");
9678 
9679   APInt A, B, C, M;
9680   unsigned BitWidth;
9681   auto T = GetQuadraticEquation(AddRec);
9682   if (!T.hasValue())
9683     return None;
9684 
9685   // Be careful about the return value: there can be two reasons for not
9686   // returning an actual number. First, if no solutions to the equations
9687   // were found, and second, if the solutions don't leave the given range.
9688   // The first case means that the actual solution is "unknown", the second
9689   // means that it's known, but not valid. If the solution is unknown, we
9690   // cannot make any conclusions.
9691   // Return a pair: the optional solution and a flag indicating if the
9692   // solution was found.
9693   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9694     // Solve for signed overflow and unsigned overflow, pick the lower
9695     // solution.
9696     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9697                       << Bound << " (before multiplying by " << M << ")\n");
9698     Bound *= M; // The quadratic equation multiplier.
9699 
9700     Optional<APInt> SO = None;
9701     if (BitWidth > 1) {
9702       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9703                            "signed overflow\n");
9704       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9705     }
9706     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9707                          "unsigned overflow\n");
9708     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9709                                                               BitWidth+1);
9710 
9711     auto LeavesRange = [&] (const APInt &X) {
9712       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9713       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9714       if (Range.contains(V0->getValue()))
9715         return false;
9716       // X should be at least 1, so X-1 is non-negative.
9717       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9718       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9719       if (Range.contains(V1->getValue()))
9720         return true;
9721       return false;
9722     };
9723 
9724     // If SolveQuadraticEquationWrap returns None, it means that there can
9725     // be a solution, but the function failed to find it. We cannot treat it
9726     // as "no solution".
9727     if (!SO.hasValue() || !UO.hasValue())
9728       return { None, false };
9729 
9730     // Check the smaller value first to see if it leaves the range.
9731     // At this point, both SO and UO must have values.
9732     Optional<APInt> Min = MinOptional(SO, UO);
9733     if (LeavesRange(*Min))
9734       return { Min, true };
9735     Optional<APInt> Max = Min == SO ? UO : SO;
9736     if (LeavesRange(*Max))
9737       return { Max, true };
9738 
9739     // Solutions were found, but were eliminated, hence the "true".
9740     return { None, true };
9741   };
9742 
9743   std::tie(A, B, C, M, BitWidth) = *T;
9744   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9745   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9746   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9747   auto SL = SolveForBoundary(Lower);
9748   auto SU = SolveForBoundary(Upper);
9749   // If any of the solutions was unknown, no meaninigful conclusions can
9750   // be made.
9751   if (!SL.second || !SU.second)
9752     return None;
9753 
9754   // Claim: The correct solution is not some value between Min and Max.
9755   //
9756   // Justification: Assuming that Min and Max are different values, one of
9757   // them is when the first signed overflow happens, the other is when the
9758   // first unsigned overflow happens. Crossing the range boundary is only
9759   // possible via an overflow (treating 0 as a special case of it, modeling
9760   // an overflow as crossing k*2^W for some k).
9761   //
9762   // The interesting case here is when Min was eliminated as an invalid
9763   // solution, but Max was not. The argument is that if there was another
9764   // overflow between Min and Max, it would also have been eliminated if
9765   // it was considered.
9766   //
9767   // For a given boundary, it is possible to have two overflows of the same
9768   // type (signed/unsigned) without having the other type in between: this
9769   // can happen when the vertex of the parabola is between the iterations
9770   // corresponding to the overflows. This is only possible when the two
9771   // overflows cross k*2^W for the same k. In such case, if the second one
9772   // left the range (and was the first one to do so), the first overflow
9773   // would have to enter the range, which would mean that either we had left
9774   // the range before or that we started outside of it. Both of these cases
9775   // are contradictions.
9776   //
9777   // Claim: In the case where SolveForBoundary returns None, the correct
9778   // solution is not some value between the Max for this boundary and the
9779   // Min of the other boundary.
9780   //
9781   // Justification: Assume that we had such Max_A and Min_B corresponding
9782   // to range boundaries A and B and such that Max_A < Min_B. If there was
9783   // a solution between Max_A and Min_B, it would have to be caused by an
9784   // overflow corresponding to either A or B. It cannot correspond to B,
9785   // since Min_B is the first occurrence of such an overflow. If it
9786   // corresponded to A, it would have to be either a signed or an unsigned
9787   // overflow that is larger than both eliminated overflows for A. But
9788   // between the eliminated overflows and this overflow, the values would
9789   // cover the entire value space, thus crossing the other boundary, which
9790   // is a contradiction.
9791 
9792   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9793 }
9794 
9795 ScalarEvolution::ExitLimit
9796 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9797                               bool AllowPredicates) {
9798 
9799   // This is only used for loops with a "x != y" exit test. The exit condition
9800   // is now expressed as a single expression, V = x-y. So the exit test is
9801   // effectively V != 0.  We know and take advantage of the fact that this
9802   // expression only being used in a comparison by zero context.
9803 
9804   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9805   // If the value is a constant
9806   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9807     // If the value is already zero, the branch will execute zero times.
9808     if (C->getValue()->isZero()) return C;
9809     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9810   }
9811 
9812   const SCEVAddRecExpr *AddRec =
9813       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9814 
9815   if (!AddRec && AllowPredicates)
9816     // Try to make this an AddRec using runtime tests, in the first X
9817     // iterations of this loop, where X is the SCEV expression found by the
9818     // algorithm below.
9819     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9820 
9821   if (!AddRec || AddRec->getLoop() != L)
9822     return getCouldNotCompute();
9823 
9824   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9825   // the quadratic equation to solve it.
9826   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9827     // We can only use this value if the chrec ends up with an exact zero
9828     // value at this index.  When solving for "X*X != 5", for example, we
9829     // should not accept a root of 2.
9830     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9831       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9832       return ExitLimit(R, R, false, Predicates);
9833     }
9834     return getCouldNotCompute();
9835   }
9836 
9837   // Otherwise we can only handle this if it is affine.
9838   if (!AddRec->isAffine())
9839     return getCouldNotCompute();
9840 
9841   // If this is an affine expression, the execution count of this branch is
9842   // the minimum unsigned root of the following equation:
9843   //
9844   //     Start + Step*N = 0 (mod 2^BW)
9845   //
9846   // equivalent to:
9847   //
9848   //             Step*N = -Start (mod 2^BW)
9849   //
9850   // where BW is the common bit width of Start and Step.
9851 
9852   // Get the initial value for the loop.
9853   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9854   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9855 
9856   // For now we handle only constant steps.
9857   //
9858   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9859   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9860   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9861   // We have not yet seen any such cases.
9862   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9863   if (!StepC || StepC->getValue()->isZero())
9864     return getCouldNotCompute();
9865 
9866   // For positive steps (counting up until unsigned overflow):
9867   //   N = -Start/Step (as unsigned)
9868   // For negative steps (counting down to zero):
9869   //   N = Start/-Step
9870   // First compute the unsigned distance from zero in the direction of Step.
9871   bool CountDown = StepC->getAPInt().isNegative();
9872   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9873 
9874   // Handle unitary steps, which cannot wraparound.
9875   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9876   //   N = Distance (as unsigned)
9877   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9878     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9879     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
9880 
9881     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9882     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9883     // case, and see if we can improve the bound.
9884     //
9885     // Explicitly handling this here is necessary because getUnsignedRange
9886     // isn't context-sensitive; it doesn't know that we only care about the
9887     // range inside the loop.
9888     const SCEV *Zero = getZero(Distance->getType());
9889     const SCEV *One = getOne(Distance->getType());
9890     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9891     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9892       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9893       // as "unsigned_max(Distance + 1) - 1".
9894       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9895       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9896     }
9897     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9898   }
9899 
9900   // If the condition controls loop exit (the loop exits only if the expression
9901   // is true) and the addition is no-wrap we can use unsigned divide to
9902   // compute the backedge count.  In this case, the step may not divide the
9903   // distance, but we don't care because if the condition is "missed" the loop
9904   // will have undefined behavior due to wrapping.
9905   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9906       loopHasNoAbnormalExits(AddRec->getLoop())) {
9907     const SCEV *Exact =
9908         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9909     const SCEV *Max = getCouldNotCompute();
9910     if (Exact != getCouldNotCompute()) {
9911       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
9912       Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
9913     }
9914     return ExitLimit(Exact, Max, false, Predicates);
9915   }
9916 
9917   // Solve the general equation.
9918   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9919                                                getNegativeSCEV(Start), *this);
9920 
9921   const SCEV *M = E;
9922   if (E != getCouldNotCompute()) {
9923     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
9924     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
9925   }
9926   return ExitLimit(E, M, false, Predicates);
9927 }
9928 
9929 ScalarEvolution::ExitLimit
9930 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9931   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9932   // handle them yet except for the trivial case.  This could be expanded in the
9933   // future as needed.
9934 
9935   // If the value is a constant, check to see if it is known to be non-zero
9936   // already.  If so, the backedge will execute zero times.
9937   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9938     if (!C->getValue()->isZero())
9939       return getZero(C->getType());
9940     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9941   }
9942 
9943   // We could implement others, but I really doubt anyone writes loops like
9944   // this, and if they did, they would already be constant folded.
9945   return getCouldNotCompute();
9946 }
9947 
9948 std::pair<const BasicBlock *, const BasicBlock *>
9949 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9950     const {
9951   // If the block has a unique predecessor, then there is no path from the
9952   // predecessor to the block that does not go through the direct edge
9953   // from the predecessor to the block.
9954   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9955     return {Pred, BB};
9956 
9957   // A loop's header is defined to be a block that dominates the loop.
9958   // If the header has a unique predecessor outside the loop, it must be
9959   // a block that has exactly one successor that can reach the loop.
9960   if (const Loop *L = LI.getLoopFor(BB))
9961     return {L->getLoopPredecessor(), L->getHeader()};
9962 
9963   return {nullptr, nullptr};
9964 }
9965 
9966 /// SCEV structural equivalence is usually sufficient for testing whether two
9967 /// expressions are equal, however for the purposes of looking for a condition
9968 /// guarding a loop, it can be useful to be a little more general, since a
9969 /// front-end may have replicated the controlling expression.
9970 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9971   // Quick check to see if they are the same SCEV.
9972   if (A == B) return true;
9973 
9974   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9975     // Not all instructions that are "identical" compute the same value.  For
9976     // instance, two distinct alloca instructions allocating the same type are
9977     // identical and do not read memory; but compute distinct values.
9978     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9979   };
9980 
9981   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9982   // two different instructions with the same value. Check for this case.
9983   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9984     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9985       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9986         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9987           if (ComputesEqualValues(AI, BI))
9988             return true;
9989 
9990   // Otherwise assume they may have a different value.
9991   return false;
9992 }
9993 
9994 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9995                                            const SCEV *&LHS, const SCEV *&RHS,
9996                                            unsigned Depth,
9997                                            bool ControllingFiniteLoop) {
9998   bool Changed = false;
9999   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10000   // '0 != 0'.
10001   auto TrivialCase = [&](bool TriviallyTrue) {
10002     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10003     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10004     return true;
10005   };
10006   // If we hit the max recursion limit bail out.
10007   if (Depth >= 3)
10008     return false;
10009 
10010   // Canonicalize a constant to the right side.
10011   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10012     // Check for both operands constant.
10013     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10014       if (ConstantExpr::getICmp(Pred,
10015                                 LHSC->getValue(),
10016                                 RHSC->getValue())->isNullValue())
10017         return TrivialCase(false);
10018       else
10019         return TrivialCase(true);
10020     }
10021     // Otherwise swap the operands to put the constant on the right.
10022     std::swap(LHS, RHS);
10023     Pred = ICmpInst::getSwappedPredicate(Pred);
10024     Changed = true;
10025   }
10026 
10027   // If we're comparing an addrec with a value which is loop-invariant in the
10028   // addrec's loop, put the addrec on the left. Also make a dominance check,
10029   // as both operands could be addrecs loop-invariant in each other's loop.
10030   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10031     const Loop *L = AR->getLoop();
10032     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10033       std::swap(LHS, RHS);
10034       Pred = ICmpInst::getSwappedPredicate(Pred);
10035       Changed = true;
10036     }
10037   }
10038 
10039   // If there's a constant operand, canonicalize comparisons with boundary
10040   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10041   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10042     const APInt &RA = RC->getAPInt();
10043 
10044     bool SimplifiedByConstantRange = false;
10045 
10046     if (!ICmpInst::isEquality(Pred)) {
10047       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10048       if (ExactCR.isFullSet())
10049         return TrivialCase(true);
10050       else if (ExactCR.isEmptySet())
10051         return TrivialCase(false);
10052 
10053       APInt NewRHS;
10054       CmpInst::Predicate NewPred;
10055       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10056           ICmpInst::isEquality(NewPred)) {
10057         // We were able to convert an inequality to an equality.
10058         Pred = NewPred;
10059         RHS = getConstant(NewRHS);
10060         Changed = SimplifiedByConstantRange = true;
10061       }
10062     }
10063 
10064     if (!SimplifiedByConstantRange) {
10065       switch (Pred) {
10066       default:
10067         break;
10068       case ICmpInst::ICMP_EQ:
10069       case ICmpInst::ICMP_NE:
10070         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10071         if (!RA)
10072           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10073             if (const SCEVMulExpr *ME =
10074                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10075               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10076                   ME->getOperand(0)->isAllOnesValue()) {
10077                 RHS = AE->getOperand(1);
10078                 LHS = ME->getOperand(1);
10079                 Changed = true;
10080               }
10081         break;
10082 
10083 
10084         // The "Should have been caught earlier!" messages refer to the fact
10085         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10086         // should have fired on the corresponding cases, and canonicalized the
10087         // check to trivial case.
10088 
10089       case ICmpInst::ICMP_UGE:
10090         assert(!RA.isMinValue() && "Should have been caught earlier!");
10091         Pred = ICmpInst::ICMP_UGT;
10092         RHS = getConstant(RA - 1);
10093         Changed = true;
10094         break;
10095       case ICmpInst::ICMP_ULE:
10096         assert(!RA.isMaxValue() && "Should have been caught earlier!");
10097         Pred = ICmpInst::ICMP_ULT;
10098         RHS = getConstant(RA + 1);
10099         Changed = true;
10100         break;
10101       case ICmpInst::ICMP_SGE:
10102         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10103         Pred = ICmpInst::ICMP_SGT;
10104         RHS = getConstant(RA - 1);
10105         Changed = true;
10106         break;
10107       case ICmpInst::ICMP_SLE:
10108         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10109         Pred = ICmpInst::ICMP_SLT;
10110         RHS = getConstant(RA + 1);
10111         Changed = true;
10112         break;
10113       }
10114     }
10115   }
10116 
10117   // Check for obvious equality.
10118   if (HasSameValue(LHS, RHS)) {
10119     if (ICmpInst::isTrueWhenEqual(Pred))
10120       return TrivialCase(true);
10121     if (ICmpInst::isFalseWhenEqual(Pred))
10122       return TrivialCase(false);
10123   }
10124 
10125   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10126   // adding or subtracting 1 from one of the operands. This can be done for
10127   // one of two reasons:
10128   // 1) The range of the RHS does not include the (signed/unsigned) boundaries
10129   // 2) The loop is finite, with this comparison controlling the exit. Since the
10130   // loop is finite, the bound cannot include the corresponding boundary
10131   // (otherwise it would loop forever).
10132   switch (Pred) {
10133   case ICmpInst::ICMP_SLE:
10134     if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) {
10135       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10136                        SCEV::FlagNSW);
10137       Pred = ICmpInst::ICMP_SLT;
10138       Changed = true;
10139     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10140       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10141                        SCEV::FlagNSW);
10142       Pred = ICmpInst::ICMP_SLT;
10143       Changed = true;
10144     }
10145     break;
10146   case ICmpInst::ICMP_SGE:
10147     if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) {
10148       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10149                        SCEV::FlagNSW);
10150       Pred = ICmpInst::ICMP_SGT;
10151       Changed = true;
10152     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10153       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10154                        SCEV::FlagNSW);
10155       Pred = ICmpInst::ICMP_SGT;
10156       Changed = true;
10157     }
10158     break;
10159   case ICmpInst::ICMP_ULE:
10160     if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) {
10161       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10162                        SCEV::FlagNUW);
10163       Pred = ICmpInst::ICMP_ULT;
10164       Changed = true;
10165     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10166       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10167       Pred = ICmpInst::ICMP_ULT;
10168       Changed = true;
10169     }
10170     break;
10171   case ICmpInst::ICMP_UGE:
10172     if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) {
10173       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10174       Pred = ICmpInst::ICMP_UGT;
10175       Changed = true;
10176     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10177       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10178                        SCEV::FlagNUW);
10179       Pred = ICmpInst::ICMP_UGT;
10180       Changed = true;
10181     }
10182     break;
10183   default:
10184     break;
10185   }
10186 
10187   // TODO: More simplifications are possible here.
10188 
10189   // Recursively simplify until we either hit a recursion limit or nothing
10190   // changes.
10191   if (Changed)
10192     return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1,
10193                                 ControllingFiniteLoop);
10194 
10195   return Changed;
10196 }
10197 
10198 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10199   return getSignedRangeMax(S).isNegative();
10200 }
10201 
10202 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10203   return getSignedRangeMin(S).isStrictlyPositive();
10204 }
10205 
10206 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10207   return !getSignedRangeMin(S).isNegative();
10208 }
10209 
10210 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10211   return !getSignedRangeMax(S).isStrictlyPositive();
10212 }
10213 
10214 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10215   return getUnsignedRangeMin(S) != 0;
10216 }
10217 
10218 std::pair<const SCEV *, const SCEV *>
10219 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10220   // Compute SCEV on entry of loop L.
10221   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10222   if (Start == getCouldNotCompute())
10223     return { Start, Start };
10224   // Compute post increment SCEV for loop L.
10225   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10226   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10227   return { Start, PostInc };
10228 }
10229 
10230 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10231                                           const SCEV *LHS, const SCEV *RHS) {
10232   // First collect all loops.
10233   SmallPtrSet<const Loop *, 8> LoopsUsed;
10234   getUsedLoops(LHS, LoopsUsed);
10235   getUsedLoops(RHS, LoopsUsed);
10236 
10237   if (LoopsUsed.empty())
10238     return false;
10239 
10240   // Domination relationship must be a linear order on collected loops.
10241 #ifndef NDEBUG
10242   for (auto *L1 : LoopsUsed)
10243     for (auto *L2 : LoopsUsed)
10244       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10245               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10246              "Domination relationship is not a linear order");
10247 #endif
10248 
10249   const Loop *MDL =
10250       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10251                         [&](const Loop *L1, const Loop *L2) {
10252          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10253        });
10254 
10255   // Get init and post increment value for LHS.
10256   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10257   // if LHS contains unknown non-invariant SCEV then bail out.
10258   if (SplitLHS.first == getCouldNotCompute())
10259     return false;
10260   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10261   // Get init and post increment value for RHS.
10262   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10263   // if RHS contains unknown non-invariant SCEV then bail out.
10264   if (SplitRHS.first == getCouldNotCompute())
10265     return false;
10266   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10267   // It is possible that init SCEV contains an invariant load but it does
10268   // not dominate MDL and is not available at MDL loop entry, so we should
10269   // check it here.
10270   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10271       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10272     return false;
10273 
10274   // It seems backedge guard check is faster than entry one so in some cases
10275   // it can speed up whole estimation by short circuit
10276   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10277                                      SplitRHS.second) &&
10278          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10279 }
10280 
10281 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10282                                        const SCEV *LHS, const SCEV *RHS) {
10283   // Canonicalize the inputs first.
10284   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10285 
10286   if (isKnownViaInduction(Pred, LHS, RHS))
10287     return true;
10288 
10289   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10290     return true;
10291 
10292   // Otherwise see what can be done with some simple reasoning.
10293   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10294 }
10295 
10296 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10297                                                   const SCEV *LHS,
10298                                                   const SCEV *RHS) {
10299   if (isKnownPredicate(Pred, LHS, RHS))
10300     return true;
10301   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10302     return false;
10303   return None;
10304 }
10305 
10306 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10307                                          const SCEV *LHS, const SCEV *RHS,
10308                                          const Instruction *CtxI) {
10309   // TODO: Analyze guards and assumes from Context's block.
10310   return isKnownPredicate(Pred, LHS, RHS) ||
10311          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10312 }
10313 
10314 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred,
10315                                                     const SCEV *LHS,
10316                                                     const SCEV *RHS,
10317                                                     const Instruction *CtxI) {
10318   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10319   if (KnownWithoutContext)
10320     return KnownWithoutContext;
10321 
10322   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10323     return true;
10324   else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10325                                           ICmpInst::getInversePredicate(Pred),
10326                                           LHS, RHS))
10327     return false;
10328   return None;
10329 }
10330 
10331 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10332                                               const SCEVAddRecExpr *LHS,
10333                                               const SCEV *RHS) {
10334   const Loop *L = LHS->getLoop();
10335   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10336          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10337 }
10338 
10339 Optional<ScalarEvolution::MonotonicPredicateType>
10340 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10341                                            ICmpInst::Predicate Pred) {
10342   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10343 
10344 #ifndef NDEBUG
10345   // Verify an invariant: inverting the predicate should turn a monotonically
10346   // increasing change to a monotonically decreasing one, and vice versa.
10347   if (Result) {
10348     auto ResultSwapped =
10349         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10350 
10351     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
10352     assert(ResultSwapped.getValue() != Result.getValue() &&
10353            "monotonicity should flip as we flip the predicate");
10354   }
10355 #endif
10356 
10357   return Result;
10358 }
10359 
10360 Optional<ScalarEvolution::MonotonicPredicateType>
10361 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10362                                                ICmpInst::Predicate Pred) {
10363   // A zero step value for LHS means the induction variable is essentially a
10364   // loop invariant value. We don't really depend on the predicate actually
10365   // flipping from false to true (for increasing predicates, and the other way
10366   // around for decreasing predicates), all we care about is that *if* the
10367   // predicate changes then it only changes from false to true.
10368   //
10369   // A zero step value in itself is not very useful, but there may be places
10370   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10371   // as general as possible.
10372 
10373   // Only handle LE/LT/GE/GT predicates.
10374   if (!ICmpInst::isRelational(Pred))
10375     return None;
10376 
10377   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10378   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10379          "Should be greater or less!");
10380 
10381   // Check that AR does not wrap.
10382   if (ICmpInst::isUnsigned(Pred)) {
10383     if (!LHS->hasNoUnsignedWrap())
10384       return None;
10385     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10386   } else {
10387     assert(ICmpInst::isSigned(Pred) &&
10388            "Relational predicate is either signed or unsigned!");
10389     if (!LHS->hasNoSignedWrap())
10390       return None;
10391 
10392     const SCEV *Step = LHS->getStepRecurrence(*this);
10393 
10394     if (isKnownNonNegative(Step))
10395       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10396 
10397     if (isKnownNonPositive(Step))
10398       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10399 
10400     return None;
10401   }
10402 }
10403 
10404 Optional<ScalarEvolution::LoopInvariantPredicate>
10405 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10406                                            const SCEV *LHS, const SCEV *RHS,
10407                                            const Loop *L) {
10408 
10409   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10410   if (!isLoopInvariant(RHS, L)) {
10411     if (!isLoopInvariant(LHS, L))
10412       return None;
10413 
10414     std::swap(LHS, RHS);
10415     Pred = ICmpInst::getSwappedPredicate(Pred);
10416   }
10417 
10418   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10419   if (!ArLHS || ArLHS->getLoop() != L)
10420     return None;
10421 
10422   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10423   if (!MonotonicType)
10424     return None;
10425   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10426   // true as the loop iterates, and the backedge is control dependent on
10427   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10428   //
10429   //   * if the predicate was false in the first iteration then the predicate
10430   //     is never evaluated again, since the loop exits without taking the
10431   //     backedge.
10432   //   * if the predicate was true in the first iteration then it will
10433   //     continue to be true for all future iterations since it is
10434   //     monotonically increasing.
10435   //
10436   // For both the above possibilities, we can replace the loop varying
10437   // predicate with its value on the first iteration of the loop (which is
10438   // loop invariant).
10439   //
10440   // A similar reasoning applies for a monotonically decreasing predicate, by
10441   // replacing true with false and false with true in the above two bullets.
10442   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10443   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10444 
10445   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10446     return None;
10447 
10448   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10449 }
10450 
10451 Optional<ScalarEvolution::LoopInvariantPredicate>
10452 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10453     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10454     const Instruction *CtxI, const SCEV *MaxIter) {
10455   // Try to prove the following set of facts:
10456   // - The predicate is monotonic in the iteration space.
10457   // - If the check does not fail on the 1st iteration:
10458   //   - No overflow will happen during first MaxIter iterations;
10459   //   - It will not fail on the MaxIter'th iteration.
10460   // If the check does fail on the 1st iteration, we leave the loop and no
10461   // other checks matter.
10462 
10463   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10464   if (!isLoopInvariant(RHS, L)) {
10465     if (!isLoopInvariant(LHS, L))
10466       return None;
10467 
10468     std::swap(LHS, RHS);
10469     Pred = ICmpInst::getSwappedPredicate(Pred);
10470   }
10471 
10472   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10473   if (!AR || AR->getLoop() != L)
10474     return None;
10475 
10476   // The predicate must be relational (i.e. <, <=, >=, >).
10477   if (!ICmpInst::isRelational(Pred))
10478     return None;
10479 
10480   // TODO: Support steps other than +/- 1.
10481   const SCEV *Step = AR->getStepRecurrence(*this);
10482   auto *One = getOne(Step->getType());
10483   auto *MinusOne = getNegativeSCEV(One);
10484   if (Step != One && Step != MinusOne)
10485     return None;
10486 
10487   // Type mismatch here means that MaxIter is potentially larger than max
10488   // unsigned value in start type, which mean we cannot prove no wrap for the
10489   // indvar.
10490   if (AR->getType() != MaxIter->getType())
10491     return None;
10492 
10493   // Value of IV on suggested last iteration.
10494   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10495   // Does it still meet the requirement?
10496   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10497     return None;
10498   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10499   // not exceed max unsigned value of this type), this effectively proves
10500   // that there is no wrap during the iteration. To prove that there is no
10501   // signed/unsigned wrap, we need to check that
10502   // Start <= Last for step = 1 or Start >= Last for step = -1.
10503   ICmpInst::Predicate NoOverflowPred =
10504       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10505   if (Step == MinusOne)
10506     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10507   const SCEV *Start = AR->getStart();
10508   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
10509     return None;
10510 
10511   // Everything is fine.
10512   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10513 }
10514 
10515 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10516     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10517   if (HasSameValue(LHS, RHS))
10518     return ICmpInst::isTrueWhenEqual(Pred);
10519 
10520   // This code is split out from isKnownPredicate because it is called from
10521   // within isLoopEntryGuardedByCond.
10522 
10523   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10524                          const ConstantRange &RangeRHS) {
10525     return RangeLHS.icmp(Pred, RangeRHS);
10526   };
10527 
10528   // The check at the top of the function catches the case where the values are
10529   // known to be equal.
10530   if (Pred == CmpInst::ICMP_EQ)
10531     return false;
10532 
10533   if (Pred == CmpInst::ICMP_NE) {
10534     if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10535         CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)))
10536       return true;
10537     auto *Diff = getMinusSCEV(LHS, RHS);
10538     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10539   }
10540 
10541   if (CmpInst::isSigned(Pred))
10542     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10543 
10544   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10545 }
10546 
10547 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10548                                                     const SCEV *LHS,
10549                                                     const SCEV *RHS) {
10550   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10551   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10552   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10553   // OutC1 and OutC2.
10554   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10555                                       APInt &OutC1, APInt &OutC2,
10556                                       SCEV::NoWrapFlags ExpectedFlags) {
10557     const SCEV *XNonConstOp, *XConstOp;
10558     const SCEV *YNonConstOp, *YConstOp;
10559     SCEV::NoWrapFlags XFlagsPresent;
10560     SCEV::NoWrapFlags YFlagsPresent;
10561 
10562     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10563       XConstOp = getZero(X->getType());
10564       XNonConstOp = X;
10565       XFlagsPresent = ExpectedFlags;
10566     }
10567     if (!isa<SCEVConstant>(XConstOp) ||
10568         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10569       return false;
10570 
10571     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10572       YConstOp = getZero(Y->getType());
10573       YNonConstOp = Y;
10574       YFlagsPresent = ExpectedFlags;
10575     }
10576 
10577     if (!isa<SCEVConstant>(YConstOp) ||
10578         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10579       return false;
10580 
10581     if (YNonConstOp != XNonConstOp)
10582       return false;
10583 
10584     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10585     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10586 
10587     return true;
10588   };
10589 
10590   APInt C1;
10591   APInt C2;
10592 
10593   switch (Pred) {
10594   default:
10595     break;
10596 
10597   case ICmpInst::ICMP_SGE:
10598     std::swap(LHS, RHS);
10599     LLVM_FALLTHROUGH;
10600   case ICmpInst::ICMP_SLE:
10601     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10602     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10603       return true;
10604 
10605     break;
10606 
10607   case ICmpInst::ICMP_SGT:
10608     std::swap(LHS, RHS);
10609     LLVM_FALLTHROUGH;
10610   case ICmpInst::ICMP_SLT:
10611     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10612     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10613       return true;
10614 
10615     break;
10616 
10617   case ICmpInst::ICMP_UGE:
10618     std::swap(LHS, RHS);
10619     LLVM_FALLTHROUGH;
10620   case ICmpInst::ICMP_ULE:
10621     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10622     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10623       return true;
10624 
10625     break;
10626 
10627   case ICmpInst::ICMP_UGT:
10628     std::swap(LHS, RHS);
10629     LLVM_FALLTHROUGH;
10630   case ICmpInst::ICMP_ULT:
10631     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10632     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10633       return true;
10634     break;
10635   }
10636 
10637   return false;
10638 }
10639 
10640 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10641                                                    const SCEV *LHS,
10642                                                    const SCEV *RHS) {
10643   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10644     return false;
10645 
10646   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10647   // the stack can result in exponential time complexity.
10648   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10649 
10650   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10651   //
10652   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10653   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10654   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10655   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10656   // use isKnownPredicate later if needed.
10657   return isKnownNonNegative(RHS) &&
10658          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10659          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10660 }
10661 
10662 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10663                                         ICmpInst::Predicate Pred,
10664                                         const SCEV *LHS, const SCEV *RHS) {
10665   // No need to even try if we know the module has no guards.
10666   if (!HasGuards)
10667     return false;
10668 
10669   return any_of(*BB, [&](const Instruction &I) {
10670     using namespace llvm::PatternMatch;
10671 
10672     Value *Condition;
10673     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10674                          m_Value(Condition))) &&
10675            isImpliedCond(Pred, LHS, RHS, Condition, false);
10676   });
10677 }
10678 
10679 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10680 /// protected by a conditional between LHS and RHS.  This is used to
10681 /// to eliminate casts.
10682 bool
10683 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10684                                              ICmpInst::Predicate Pred,
10685                                              const SCEV *LHS, const SCEV *RHS) {
10686   // Interpret a null as meaning no loop, where there is obviously no guard
10687   // (interprocedural conditions notwithstanding).
10688   if (!L) return true;
10689 
10690   if (VerifyIR)
10691     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10692            "This cannot be done on broken IR!");
10693 
10694 
10695   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10696     return true;
10697 
10698   BasicBlock *Latch = L->getLoopLatch();
10699   if (!Latch)
10700     return false;
10701 
10702   BranchInst *LoopContinuePredicate =
10703     dyn_cast<BranchInst>(Latch->getTerminator());
10704   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10705       isImpliedCond(Pred, LHS, RHS,
10706                     LoopContinuePredicate->getCondition(),
10707                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10708     return true;
10709 
10710   // We don't want more than one activation of the following loops on the stack
10711   // -- that can lead to O(n!) time complexity.
10712   if (WalkingBEDominatingConds)
10713     return false;
10714 
10715   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10716 
10717   // See if we can exploit a trip count to prove the predicate.
10718   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10719   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10720   if (LatchBECount != getCouldNotCompute()) {
10721     // We know that Latch branches back to the loop header exactly
10722     // LatchBECount times.  This means the backdege condition at Latch is
10723     // equivalent to  "{0,+,1} u< LatchBECount".
10724     Type *Ty = LatchBECount->getType();
10725     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10726     const SCEV *LoopCounter =
10727       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10728     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10729                       LatchBECount))
10730       return true;
10731   }
10732 
10733   // Check conditions due to any @llvm.assume intrinsics.
10734   for (auto &AssumeVH : AC.assumptions()) {
10735     if (!AssumeVH)
10736       continue;
10737     auto *CI = cast<CallInst>(AssumeVH);
10738     if (!DT.dominates(CI, Latch->getTerminator()))
10739       continue;
10740 
10741     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10742       return true;
10743   }
10744 
10745   // If the loop is not reachable from the entry block, we risk running into an
10746   // infinite loop as we walk up into the dom tree.  These loops do not matter
10747   // anyway, so we just return a conservative answer when we see them.
10748   if (!DT.isReachableFromEntry(L->getHeader()))
10749     return false;
10750 
10751   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10752     return true;
10753 
10754   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10755        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10756     assert(DTN && "should reach the loop header before reaching the root!");
10757 
10758     BasicBlock *BB = DTN->getBlock();
10759     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10760       return true;
10761 
10762     BasicBlock *PBB = BB->getSinglePredecessor();
10763     if (!PBB)
10764       continue;
10765 
10766     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10767     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10768       continue;
10769 
10770     Value *Condition = ContinuePredicate->getCondition();
10771 
10772     // If we have an edge `E` within the loop body that dominates the only
10773     // latch, the condition guarding `E` also guards the backedge.  This
10774     // reasoning works only for loops with a single latch.
10775 
10776     BasicBlockEdge DominatingEdge(PBB, BB);
10777     if (DominatingEdge.isSingleEdge()) {
10778       // We're constructively (and conservatively) enumerating edges within the
10779       // loop body that dominate the latch.  The dominator tree better agree
10780       // with us on this:
10781       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10782 
10783       if (isImpliedCond(Pred, LHS, RHS, Condition,
10784                         BB != ContinuePredicate->getSuccessor(0)))
10785         return true;
10786     }
10787   }
10788 
10789   return false;
10790 }
10791 
10792 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10793                                                      ICmpInst::Predicate Pred,
10794                                                      const SCEV *LHS,
10795                                                      const SCEV *RHS) {
10796   if (VerifyIR)
10797     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10798            "This cannot be done on broken IR!");
10799 
10800   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10801   // the facts (a >= b && a != b) separately. A typical situation is when the
10802   // non-strict comparison is known from ranges and non-equality is known from
10803   // dominating predicates. If we are proving strict comparison, we always try
10804   // to prove non-equality and non-strict comparison separately.
10805   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10806   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10807   bool ProvedNonStrictComparison = false;
10808   bool ProvedNonEquality = false;
10809 
10810   auto SplitAndProve =
10811     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10812     if (!ProvedNonStrictComparison)
10813       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10814     if (!ProvedNonEquality)
10815       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10816     if (ProvedNonStrictComparison && ProvedNonEquality)
10817       return true;
10818     return false;
10819   };
10820 
10821   if (ProvingStrictComparison) {
10822     auto ProofFn = [&](ICmpInst::Predicate P) {
10823       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10824     };
10825     if (SplitAndProve(ProofFn))
10826       return true;
10827   }
10828 
10829   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10830   auto ProveViaGuard = [&](const BasicBlock *Block) {
10831     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10832       return true;
10833     if (ProvingStrictComparison) {
10834       auto ProofFn = [&](ICmpInst::Predicate P) {
10835         return isImpliedViaGuard(Block, P, LHS, RHS);
10836       };
10837       if (SplitAndProve(ProofFn))
10838         return true;
10839     }
10840     return false;
10841   };
10842 
10843   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10844   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10845     const Instruction *CtxI = &BB->front();
10846     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
10847       return true;
10848     if (ProvingStrictComparison) {
10849       auto ProofFn = [&](ICmpInst::Predicate P) {
10850         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
10851       };
10852       if (SplitAndProve(ProofFn))
10853         return true;
10854     }
10855     return false;
10856   };
10857 
10858   // Starting at the block's predecessor, climb up the predecessor chain, as long
10859   // as there are predecessors that can be found that have unique successors
10860   // leading to the original block.
10861   const Loop *ContainingLoop = LI.getLoopFor(BB);
10862   const BasicBlock *PredBB;
10863   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10864     PredBB = ContainingLoop->getLoopPredecessor();
10865   else
10866     PredBB = BB->getSinglePredecessor();
10867   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10868        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10869     if (ProveViaGuard(Pair.first))
10870       return true;
10871 
10872     const BranchInst *LoopEntryPredicate =
10873         dyn_cast<BranchInst>(Pair.first->getTerminator());
10874     if (!LoopEntryPredicate ||
10875         LoopEntryPredicate->isUnconditional())
10876       continue;
10877 
10878     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10879                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10880       return true;
10881   }
10882 
10883   // Check conditions due to any @llvm.assume intrinsics.
10884   for (auto &AssumeVH : AC.assumptions()) {
10885     if (!AssumeVH)
10886       continue;
10887     auto *CI = cast<CallInst>(AssumeVH);
10888     if (!DT.dominates(CI, BB))
10889       continue;
10890 
10891     if (ProveViaCond(CI->getArgOperand(0), false))
10892       return true;
10893   }
10894 
10895   return false;
10896 }
10897 
10898 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10899                                                ICmpInst::Predicate Pred,
10900                                                const SCEV *LHS,
10901                                                const SCEV *RHS) {
10902   // Interpret a null as meaning no loop, where there is obviously no guard
10903   // (interprocedural conditions notwithstanding).
10904   if (!L)
10905     return false;
10906 
10907   // Both LHS and RHS must be available at loop entry.
10908   assert(isAvailableAtLoopEntry(LHS, L) &&
10909          "LHS is not available at Loop Entry");
10910   assert(isAvailableAtLoopEntry(RHS, L) &&
10911          "RHS is not available at Loop Entry");
10912 
10913   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10914     return true;
10915 
10916   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10917 }
10918 
10919 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10920                                     const SCEV *RHS,
10921                                     const Value *FoundCondValue, bool Inverse,
10922                                     const Instruction *CtxI) {
10923   // False conditions implies anything. Do not bother analyzing it further.
10924   if (FoundCondValue ==
10925       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10926     return true;
10927 
10928   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10929     return false;
10930 
10931   auto ClearOnExit =
10932       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10933 
10934   // Recursively handle And and Or conditions.
10935   const Value *Op0, *Op1;
10936   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10937     if (!Inverse)
10938       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
10939              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
10940   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10941     if (Inverse)
10942       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
10943              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
10944   }
10945 
10946   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10947   if (!ICI) return false;
10948 
10949   // Now that we found a conditional branch that dominates the loop or controls
10950   // the loop latch. Check to see if it is the comparison we are looking for.
10951   ICmpInst::Predicate FoundPred;
10952   if (Inverse)
10953     FoundPred = ICI->getInversePredicate();
10954   else
10955     FoundPred = ICI->getPredicate();
10956 
10957   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10958   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10959 
10960   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
10961 }
10962 
10963 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10964                                     const SCEV *RHS,
10965                                     ICmpInst::Predicate FoundPred,
10966                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10967                                     const Instruction *CtxI) {
10968   // Balance the types.
10969   if (getTypeSizeInBits(LHS->getType()) <
10970       getTypeSizeInBits(FoundLHS->getType())) {
10971     // For unsigned and equality predicates, try to prove that both found
10972     // operands fit into narrow unsigned range. If so, try to prove facts in
10973     // narrow types.
10974     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
10975         !FoundRHS->getType()->isPointerTy()) {
10976       auto *NarrowType = LHS->getType();
10977       auto *WideType = FoundLHS->getType();
10978       auto BitWidth = getTypeSizeInBits(NarrowType);
10979       const SCEV *MaxValue = getZeroExtendExpr(
10980           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10981       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
10982                                           MaxValue) &&
10983           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
10984                                           MaxValue)) {
10985         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10986         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10987         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10988                                        TruncFoundRHS, CtxI))
10989           return true;
10990       }
10991     }
10992 
10993     if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
10994       return false;
10995     if (CmpInst::isSigned(Pred)) {
10996       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10997       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10998     } else {
10999       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11000       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11001     }
11002   } else if (getTypeSizeInBits(LHS->getType()) >
11003       getTypeSizeInBits(FoundLHS->getType())) {
11004     if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11005       return false;
11006     if (CmpInst::isSigned(FoundPred)) {
11007       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11008       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11009     } else {
11010       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11011       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11012     }
11013   }
11014   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11015                                     FoundRHS, CtxI);
11016 }
11017 
11018 bool ScalarEvolution::isImpliedCondBalancedTypes(
11019     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11020     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11021     const Instruction *CtxI) {
11022   assert(getTypeSizeInBits(LHS->getType()) ==
11023              getTypeSizeInBits(FoundLHS->getType()) &&
11024          "Types should be balanced!");
11025   // Canonicalize the query to match the way instcombine will have
11026   // canonicalized the comparison.
11027   if (SimplifyICmpOperands(Pred, LHS, RHS))
11028     if (LHS == RHS)
11029       return CmpInst::isTrueWhenEqual(Pred);
11030   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11031     if (FoundLHS == FoundRHS)
11032       return CmpInst::isFalseWhenEqual(FoundPred);
11033 
11034   // Check to see if we can make the LHS or RHS match.
11035   if (LHS == FoundRHS || RHS == FoundLHS) {
11036     if (isa<SCEVConstant>(RHS)) {
11037       std::swap(FoundLHS, FoundRHS);
11038       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11039     } else {
11040       std::swap(LHS, RHS);
11041       Pred = ICmpInst::getSwappedPredicate(Pred);
11042     }
11043   }
11044 
11045   // Check whether the found predicate is the same as the desired predicate.
11046   if (FoundPred == Pred)
11047     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11048 
11049   // Check whether swapping the found predicate makes it the same as the
11050   // desired predicate.
11051   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11052     // We can write the implication
11053     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
11054     // using one of the following ways:
11055     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
11056     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
11057     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
11058     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
11059     // Forms 1. and 2. require swapping the operands of one condition. Don't
11060     // do this if it would break canonical constant/addrec ordering.
11061     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11062       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11063                                    CtxI);
11064     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11065       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11066 
11067     // There's no clear preference between forms 3. and 4., try both.  Avoid
11068     // forming getNotSCEV of pointer values as the resulting subtract is
11069     // not legal.
11070     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11071         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11072                               FoundLHS, FoundRHS, CtxI))
11073       return true;
11074 
11075     if (!FoundLHS->getType()->isPointerTy() &&
11076         !FoundRHS->getType()->isPointerTy() &&
11077         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11078                               getNotSCEV(FoundRHS), CtxI))
11079       return true;
11080 
11081     return false;
11082   }
11083 
11084   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11085                                    CmpInst::Predicate P2) {
11086     assert(P1 != P2 && "Handled earlier!");
11087     return CmpInst::isRelational(P2) &&
11088            P1 == CmpInst::getFlippedSignednessPredicate(P2);
11089   };
11090   if (IsSignFlippedPredicate(Pred, FoundPred)) {
11091     // Unsigned comparison is the same as signed comparison when both the
11092     // operands are non-negative or negative.
11093     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11094         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11095       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11096     // Create local copies that we can freely swap and canonicalize our
11097     // conditions to "le/lt".
11098     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11099     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11100                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11101     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11102       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11103       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11104       std::swap(CanonicalLHS, CanonicalRHS);
11105       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11106     }
11107     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11108            "Must be!");
11109     assert((ICmpInst::isLT(CanonicalFoundPred) ||
11110             ICmpInst::isLE(CanonicalFoundPred)) &&
11111            "Must be!");
11112     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11113       // Use implication:
11114       // x <u y && y >=s 0 --> x <s y.
11115       // If we can prove the left part, the right part is also proven.
11116       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11117                                    CanonicalRHS, CanonicalFoundLHS,
11118                                    CanonicalFoundRHS);
11119     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11120       // Use implication:
11121       // x <s y && y <s 0 --> x <u y.
11122       // If we can prove the left part, the right part is also proven.
11123       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11124                                    CanonicalRHS, CanonicalFoundLHS,
11125                                    CanonicalFoundRHS);
11126   }
11127 
11128   // Check if we can make progress by sharpening ranges.
11129   if (FoundPred == ICmpInst::ICMP_NE &&
11130       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11131 
11132     const SCEVConstant *C = nullptr;
11133     const SCEV *V = nullptr;
11134 
11135     if (isa<SCEVConstant>(FoundLHS)) {
11136       C = cast<SCEVConstant>(FoundLHS);
11137       V = FoundRHS;
11138     } else {
11139       C = cast<SCEVConstant>(FoundRHS);
11140       V = FoundLHS;
11141     }
11142 
11143     // The guarding predicate tells us that C != V. If the known range
11144     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
11145     // range we consider has to correspond to same signedness as the
11146     // predicate we're interested in folding.
11147 
11148     APInt Min = ICmpInst::isSigned(Pred) ?
11149         getSignedRangeMin(V) : getUnsignedRangeMin(V);
11150 
11151     if (Min == C->getAPInt()) {
11152       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11153       // This is true even if (Min + 1) wraps around -- in case of
11154       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11155 
11156       APInt SharperMin = Min + 1;
11157 
11158       switch (Pred) {
11159         case ICmpInst::ICMP_SGE:
11160         case ICmpInst::ICMP_UGE:
11161           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
11162           // RHS, we're done.
11163           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11164                                     CtxI))
11165             return true;
11166           LLVM_FALLTHROUGH;
11167 
11168         case ICmpInst::ICMP_SGT:
11169         case ICmpInst::ICMP_UGT:
11170           // We know from the range information that (V `Pred` Min ||
11171           // V == Min).  We know from the guarding condition that !(V
11172           // == Min).  This gives us
11173           //
11174           //       V `Pred` Min || V == Min && !(V == Min)
11175           //   =>  V `Pred` Min
11176           //
11177           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11178 
11179           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11180             return true;
11181           break;
11182 
11183         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11184         case ICmpInst::ICMP_SLE:
11185         case ICmpInst::ICMP_ULE:
11186           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11187                                     LHS, V, getConstant(SharperMin), CtxI))
11188             return true;
11189           LLVM_FALLTHROUGH;
11190 
11191         case ICmpInst::ICMP_SLT:
11192         case ICmpInst::ICMP_ULT:
11193           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11194                                     LHS, V, getConstant(Min), CtxI))
11195             return true;
11196           break;
11197 
11198         default:
11199           // No change
11200           break;
11201       }
11202     }
11203   }
11204 
11205   // Check whether the actual condition is beyond sufficient.
11206   if (FoundPred == ICmpInst::ICMP_EQ)
11207     if (ICmpInst::isTrueWhenEqual(Pred))
11208       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11209         return true;
11210   if (Pred == ICmpInst::ICMP_NE)
11211     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11212       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11213         return true;
11214 
11215   // Otherwise assume the worst.
11216   return false;
11217 }
11218 
11219 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11220                                      const SCEV *&L, const SCEV *&R,
11221                                      SCEV::NoWrapFlags &Flags) {
11222   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11223   if (!AE || AE->getNumOperands() != 2)
11224     return false;
11225 
11226   L = AE->getOperand(0);
11227   R = AE->getOperand(1);
11228   Flags = AE->getNoWrapFlags();
11229   return true;
11230 }
11231 
11232 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
11233                                                            const SCEV *Less) {
11234   // We avoid subtracting expressions here because this function is usually
11235   // fairly deep in the call stack (i.e. is called many times).
11236 
11237   // X - X = 0.
11238   if (More == Less)
11239     return APInt(getTypeSizeInBits(More->getType()), 0);
11240 
11241   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11242     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11243     const auto *MAR = cast<SCEVAddRecExpr>(More);
11244 
11245     if (LAR->getLoop() != MAR->getLoop())
11246       return None;
11247 
11248     // We look at affine expressions only; not for correctness but to keep
11249     // getStepRecurrence cheap.
11250     if (!LAR->isAffine() || !MAR->isAffine())
11251       return None;
11252 
11253     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11254       return None;
11255 
11256     Less = LAR->getStart();
11257     More = MAR->getStart();
11258 
11259     // fall through
11260   }
11261 
11262   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11263     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11264     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11265     return M - L;
11266   }
11267 
11268   SCEV::NoWrapFlags Flags;
11269   const SCEV *LLess = nullptr, *RLess = nullptr;
11270   const SCEV *LMore = nullptr, *RMore = nullptr;
11271   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11272   // Compare (X + C1) vs X.
11273   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11274     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11275       if (RLess == More)
11276         return -(C1->getAPInt());
11277 
11278   // Compare X vs (X + C2).
11279   if (splitBinaryAdd(More, LMore, RMore, Flags))
11280     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11281       if (RMore == Less)
11282         return C2->getAPInt();
11283 
11284   // Compare (X + C1) vs (X + C2).
11285   if (C1 && C2 && RLess == RMore)
11286     return C2->getAPInt() - C1->getAPInt();
11287 
11288   return None;
11289 }
11290 
11291 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11292     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11293     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11294   // Try to recognize the following pattern:
11295   //
11296   //   FoundRHS = ...
11297   // ...
11298   // loop:
11299   //   FoundLHS = {Start,+,W}
11300   // context_bb: // Basic block from the same loop
11301   //   known(Pred, FoundLHS, FoundRHS)
11302   //
11303   // If some predicate is known in the context of a loop, it is also known on
11304   // each iteration of this loop, including the first iteration. Therefore, in
11305   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11306   // prove the original pred using this fact.
11307   if (!CtxI)
11308     return false;
11309   const BasicBlock *ContextBB = CtxI->getParent();
11310   // Make sure AR varies in the context block.
11311   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11312     const Loop *L = AR->getLoop();
11313     // Make sure that context belongs to the loop and executes on 1st iteration
11314     // (if it ever executes at all).
11315     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11316       return false;
11317     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11318       return false;
11319     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11320   }
11321 
11322   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11323     const Loop *L = AR->getLoop();
11324     // Make sure that context belongs to the loop and executes on 1st iteration
11325     // (if it ever executes at all).
11326     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11327       return false;
11328     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11329       return false;
11330     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11331   }
11332 
11333   return false;
11334 }
11335 
11336 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11337     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11338     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11339   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11340     return false;
11341 
11342   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11343   if (!AddRecLHS)
11344     return false;
11345 
11346   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11347   if (!AddRecFoundLHS)
11348     return false;
11349 
11350   // We'd like to let SCEV reason about control dependencies, so we constrain
11351   // both the inequalities to be about add recurrences on the same loop.  This
11352   // way we can use isLoopEntryGuardedByCond later.
11353 
11354   const Loop *L = AddRecFoundLHS->getLoop();
11355   if (L != AddRecLHS->getLoop())
11356     return false;
11357 
11358   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11359   //
11360   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11361   //                                                                  ... (2)
11362   //
11363   // Informal proof for (2), assuming (1) [*]:
11364   //
11365   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11366   //
11367   // Then
11368   //
11369   //       FoundLHS s< FoundRHS s< INT_MIN - C
11370   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11371   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11372   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11373   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11374   // <=>  FoundLHS + C s< FoundRHS + C
11375   //
11376   // [*]: (1) can be proved by ruling out overflow.
11377   //
11378   // [**]: This can be proved by analyzing all the four possibilities:
11379   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11380   //    (A s>= 0, B s>= 0).
11381   //
11382   // Note:
11383   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11384   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11385   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11386   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11387   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11388   // C)".
11389 
11390   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11391   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11392   if (!LDiff || !RDiff || *LDiff != *RDiff)
11393     return false;
11394 
11395   if (LDiff->isMinValue())
11396     return true;
11397 
11398   APInt FoundRHSLimit;
11399 
11400   if (Pred == CmpInst::ICMP_ULT) {
11401     FoundRHSLimit = -(*RDiff);
11402   } else {
11403     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11404     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11405   }
11406 
11407   // Try to prove (1) or (2), as needed.
11408   return isAvailableAtLoopEntry(FoundRHS, L) &&
11409          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11410                                   getConstant(FoundRHSLimit));
11411 }
11412 
11413 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11414                                         const SCEV *LHS, const SCEV *RHS,
11415                                         const SCEV *FoundLHS,
11416                                         const SCEV *FoundRHS, unsigned Depth) {
11417   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11418 
11419   auto ClearOnExit = make_scope_exit([&]() {
11420     if (LPhi) {
11421       bool Erased = PendingMerges.erase(LPhi);
11422       assert(Erased && "Failed to erase LPhi!");
11423       (void)Erased;
11424     }
11425     if (RPhi) {
11426       bool Erased = PendingMerges.erase(RPhi);
11427       assert(Erased && "Failed to erase RPhi!");
11428       (void)Erased;
11429     }
11430   });
11431 
11432   // Find respective Phis and check that they are not being pending.
11433   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11434     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11435       if (!PendingMerges.insert(Phi).second)
11436         return false;
11437       LPhi = Phi;
11438     }
11439   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11440     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11441       // If we detect a loop of Phi nodes being processed by this method, for
11442       // example:
11443       //
11444       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11445       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11446       //
11447       // we don't want to deal with a case that complex, so return conservative
11448       // answer false.
11449       if (!PendingMerges.insert(Phi).second)
11450         return false;
11451       RPhi = Phi;
11452     }
11453 
11454   // If none of LHS, RHS is a Phi, nothing to do here.
11455   if (!LPhi && !RPhi)
11456     return false;
11457 
11458   // If there is a SCEVUnknown Phi we are interested in, make it left.
11459   if (!LPhi) {
11460     std::swap(LHS, RHS);
11461     std::swap(FoundLHS, FoundRHS);
11462     std::swap(LPhi, RPhi);
11463     Pred = ICmpInst::getSwappedPredicate(Pred);
11464   }
11465 
11466   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11467   const BasicBlock *LBB = LPhi->getParent();
11468   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11469 
11470   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11471     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11472            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11473            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11474   };
11475 
11476   if (RPhi && RPhi->getParent() == LBB) {
11477     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11478     // If we compare two Phis from the same block, and for each entry block
11479     // the predicate is true for incoming values from this block, then the
11480     // predicate is also true for the Phis.
11481     for (const BasicBlock *IncBB : predecessors(LBB)) {
11482       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11483       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11484       if (!ProvedEasily(L, R))
11485         return false;
11486     }
11487   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11488     // Case two: RHS is also a Phi from the same basic block, and it is an
11489     // AddRec. It means that there is a loop which has both AddRec and Unknown
11490     // PHIs, for it we can compare incoming values of AddRec from above the loop
11491     // and latch with their respective incoming values of LPhi.
11492     // TODO: Generalize to handle loops with many inputs in a header.
11493     if (LPhi->getNumIncomingValues() != 2) return false;
11494 
11495     auto *RLoop = RAR->getLoop();
11496     auto *Predecessor = RLoop->getLoopPredecessor();
11497     assert(Predecessor && "Loop with AddRec with no predecessor?");
11498     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11499     if (!ProvedEasily(L1, RAR->getStart()))
11500       return false;
11501     auto *Latch = RLoop->getLoopLatch();
11502     assert(Latch && "Loop with AddRec with no latch?");
11503     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11504     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11505       return false;
11506   } else {
11507     // In all other cases go over inputs of LHS and compare each of them to RHS,
11508     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11509     // At this point RHS is either a non-Phi, or it is a Phi from some block
11510     // different from LBB.
11511     for (const BasicBlock *IncBB : predecessors(LBB)) {
11512       // Check that RHS is available in this block.
11513       if (!dominates(RHS, IncBB))
11514         return false;
11515       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11516       // Make sure L does not refer to a value from a potentially previous
11517       // iteration of a loop.
11518       if (!properlyDominates(L, IncBB))
11519         return false;
11520       if (!ProvedEasily(L, RHS))
11521         return false;
11522     }
11523   }
11524   return true;
11525 }
11526 
11527 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
11528                                                     const SCEV *LHS,
11529                                                     const SCEV *RHS,
11530                                                     const SCEV *FoundLHS,
11531                                                     const SCEV *FoundRHS) {
11532   // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue).  First, make
11533   // sure that we are dealing with same LHS.
11534   if (RHS == FoundRHS) {
11535     std::swap(LHS, RHS);
11536     std::swap(FoundLHS, FoundRHS);
11537     Pred = ICmpInst::getSwappedPredicate(Pred);
11538   }
11539   if (LHS != FoundLHS)
11540     return false;
11541 
11542   auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
11543   if (!SUFoundRHS)
11544     return false;
11545 
11546   Value *Shiftee, *ShiftValue;
11547 
11548   using namespace PatternMatch;
11549   if (match(SUFoundRHS->getValue(),
11550             m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
11551     auto *ShifteeS = getSCEV(Shiftee);
11552     // Prove one of the following:
11553     // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
11554     // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
11555     // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11556     //   ---> LHS <s RHS
11557     // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11558     //   ---> LHS <=s RHS
11559     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
11560       return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
11561     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
11562       if (isKnownNonNegative(ShifteeS))
11563         return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
11564   }
11565 
11566   return false;
11567 }
11568 
11569 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11570                                             const SCEV *LHS, const SCEV *RHS,
11571                                             const SCEV *FoundLHS,
11572                                             const SCEV *FoundRHS,
11573                                             const Instruction *CtxI) {
11574   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11575     return true;
11576 
11577   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11578     return true;
11579 
11580   if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
11581     return true;
11582 
11583   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11584                                           CtxI))
11585     return true;
11586 
11587   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11588                                      FoundLHS, FoundRHS);
11589 }
11590 
11591 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11592 template <typename MinMaxExprType>
11593 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11594                                  const SCEV *Candidate) {
11595   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11596   if (!MinMaxExpr)
11597     return false;
11598 
11599   return is_contained(MinMaxExpr->operands(), Candidate);
11600 }
11601 
11602 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11603                                            ICmpInst::Predicate Pred,
11604                                            const SCEV *LHS, const SCEV *RHS) {
11605   // If both sides are affine addrecs for the same loop, with equal
11606   // steps, and we know the recurrences don't wrap, then we only
11607   // need to check the predicate on the starting values.
11608 
11609   if (!ICmpInst::isRelational(Pred))
11610     return false;
11611 
11612   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11613   if (!LAR)
11614     return false;
11615   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11616   if (!RAR)
11617     return false;
11618   if (LAR->getLoop() != RAR->getLoop())
11619     return false;
11620   if (!LAR->isAffine() || !RAR->isAffine())
11621     return false;
11622 
11623   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11624     return false;
11625 
11626   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11627                          SCEV::FlagNSW : SCEV::FlagNUW;
11628   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11629     return false;
11630 
11631   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11632 }
11633 
11634 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11635 /// expression?
11636 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11637                                         ICmpInst::Predicate Pred,
11638                                         const SCEV *LHS, const SCEV *RHS) {
11639   switch (Pred) {
11640   default:
11641     return false;
11642 
11643   case ICmpInst::ICMP_SGE:
11644     std::swap(LHS, RHS);
11645     LLVM_FALLTHROUGH;
11646   case ICmpInst::ICMP_SLE:
11647     return
11648         // min(A, ...) <= A
11649         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11650         // A <= max(A, ...)
11651         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11652 
11653   case ICmpInst::ICMP_UGE:
11654     std::swap(LHS, RHS);
11655     LLVM_FALLTHROUGH;
11656   case ICmpInst::ICMP_ULE:
11657     return
11658         // min(A, ...) <= A
11659         // FIXME: what about umin_seq?
11660         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11661         // A <= max(A, ...)
11662         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11663   }
11664 
11665   llvm_unreachable("covered switch fell through?!");
11666 }
11667 
11668 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11669                                              const SCEV *LHS, const SCEV *RHS,
11670                                              const SCEV *FoundLHS,
11671                                              const SCEV *FoundRHS,
11672                                              unsigned Depth) {
11673   assert(getTypeSizeInBits(LHS->getType()) ==
11674              getTypeSizeInBits(RHS->getType()) &&
11675          "LHS and RHS have different sizes?");
11676   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11677              getTypeSizeInBits(FoundRHS->getType()) &&
11678          "FoundLHS and FoundRHS have different sizes?");
11679   // We want to avoid hurting the compile time with analysis of too big trees.
11680   if (Depth > MaxSCEVOperationsImplicationDepth)
11681     return false;
11682 
11683   // We only want to work with GT comparison so far.
11684   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11685     Pred = CmpInst::getSwappedPredicate(Pred);
11686     std::swap(LHS, RHS);
11687     std::swap(FoundLHS, FoundRHS);
11688   }
11689 
11690   // For unsigned, try to reduce it to corresponding signed comparison.
11691   if (Pred == ICmpInst::ICMP_UGT)
11692     // We can replace unsigned predicate with its signed counterpart if all
11693     // involved values are non-negative.
11694     // TODO: We could have better support for unsigned.
11695     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11696       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11697       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11698       // use this fact to prove that LHS and RHS are non-negative.
11699       const SCEV *MinusOne = getMinusOne(LHS->getType());
11700       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11701                                 FoundRHS) &&
11702           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11703                                 FoundRHS))
11704         Pred = ICmpInst::ICMP_SGT;
11705     }
11706 
11707   if (Pred != ICmpInst::ICMP_SGT)
11708     return false;
11709 
11710   auto GetOpFromSExt = [&](const SCEV *S) {
11711     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11712       return Ext->getOperand();
11713     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11714     // the constant in some cases.
11715     return S;
11716   };
11717 
11718   // Acquire values from extensions.
11719   auto *OrigLHS = LHS;
11720   auto *OrigFoundLHS = FoundLHS;
11721   LHS = GetOpFromSExt(LHS);
11722   FoundLHS = GetOpFromSExt(FoundLHS);
11723 
11724   // Is the SGT predicate can be proved trivially or using the found context.
11725   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11726     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11727            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11728                                   FoundRHS, Depth + 1);
11729   };
11730 
11731   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11732     // We want to avoid creation of any new non-constant SCEV. Since we are
11733     // going to compare the operands to RHS, we should be certain that we don't
11734     // need any size extensions for this. So let's decline all cases when the
11735     // sizes of types of LHS and RHS do not match.
11736     // TODO: Maybe try to get RHS from sext to catch more cases?
11737     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11738       return false;
11739 
11740     // Should not overflow.
11741     if (!LHSAddExpr->hasNoSignedWrap())
11742       return false;
11743 
11744     auto *LL = LHSAddExpr->getOperand(0);
11745     auto *LR = LHSAddExpr->getOperand(1);
11746     auto *MinusOne = getMinusOne(RHS->getType());
11747 
11748     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11749     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11750       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11751     };
11752     // Try to prove the following rule:
11753     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11754     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11755     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11756       return true;
11757   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11758     Value *LL, *LR;
11759     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11760 
11761     using namespace llvm::PatternMatch;
11762 
11763     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11764       // Rules for division.
11765       // We are going to perform some comparisons with Denominator and its
11766       // derivative expressions. In general case, creating a SCEV for it may
11767       // lead to a complex analysis of the entire graph, and in particular it
11768       // can request trip count recalculation for the same loop. This would
11769       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11770       // this, we only want to create SCEVs that are constants in this section.
11771       // So we bail if Denominator is not a constant.
11772       if (!isa<ConstantInt>(LR))
11773         return false;
11774 
11775       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11776 
11777       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11778       // then a SCEV for the numerator already exists and matches with FoundLHS.
11779       auto *Numerator = getExistingSCEV(LL);
11780       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11781         return false;
11782 
11783       // Make sure that the numerator matches with FoundLHS and the denominator
11784       // is positive.
11785       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11786         return false;
11787 
11788       auto *DTy = Denominator->getType();
11789       auto *FRHSTy = FoundRHS->getType();
11790       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11791         // One of types is a pointer and another one is not. We cannot extend
11792         // them properly to a wider type, so let us just reject this case.
11793         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11794         // to avoid this check.
11795         return false;
11796 
11797       // Given that:
11798       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11799       auto *WTy = getWiderType(DTy, FRHSTy);
11800       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11801       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11802 
11803       // Try to prove the following rule:
11804       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11805       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11806       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11807       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11808       if (isKnownNonPositive(RHS) &&
11809           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11810         return true;
11811 
11812       // Try to prove the following rule:
11813       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11814       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11815       // If we divide it by Denominator > 2, then:
11816       // 1. If FoundLHS is negative, then the result is 0.
11817       // 2. If FoundLHS is non-negative, then the result is non-negative.
11818       // Anyways, the result is non-negative.
11819       auto *MinusOne = getMinusOne(WTy);
11820       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11821       if (isKnownNegative(RHS) &&
11822           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11823         return true;
11824     }
11825   }
11826 
11827   // If our expression contained SCEVUnknown Phis, and we split it down and now
11828   // need to prove something for them, try to prove the predicate for every
11829   // possible incoming values of those Phis.
11830   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11831     return true;
11832 
11833   return false;
11834 }
11835 
11836 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11837                                         const SCEV *LHS, const SCEV *RHS) {
11838   // zext x u<= sext x, sext x s<= zext x
11839   switch (Pred) {
11840   case ICmpInst::ICMP_SGE:
11841     std::swap(LHS, RHS);
11842     LLVM_FALLTHROUGH;
11843   case ICmpInst::ICMP_SLE: {
11844     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11845     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11846     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11847     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11848       return true;
11849     break;
11850   }
11851   case ICmpInst::ICMP_UGE:
11852     std::swap(LHS, RHS);
11853     LLVM_FALLTHROUGH;
11854   case ICmpInst::ICMP_ULE: {
11855     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11856     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11857     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11858     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11859       return true;
11860     break;
11861   }
11862   default:
11863     break;
11864   };
11865   return false;
11866 }
11867 
11868 bool
11869 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11870                                            const SCEV *LHS, const SCEV *RHS) {
11871   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11872          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11873          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11874          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11875          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11876 }
11877 
11878 bool
11879 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11880                                              const SCEV *LHS, const SCEV *RHS,
11881                                              const SCEV *FoundLHS,
11882                                              const SCEV *FoundRHS) {
11883   switch (Pred) {
11884   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11885   case ICmpInst::ICMP_EQ:
11886   case ICmpInst::ICMP_NE:
11887     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11888       return true;
11889     break;
11890   case ICmpInst::ICMP_SLT:
11891   case ICmpInst::ICMP_SLE:
11892     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11893         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11894       return true;
11895     break;
11896   case ICmpInst::ICMP_SGT:
11897   case ICmpInst::ICMP_SGE:
11898     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11899         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11900       return true;
11901     break;
11902   case ICmpInst::ICMP_ULT:
11903   case ICmpInst::ICMP_ULE:
11904     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11905         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11906       return true;
11907     break;
11908   case ICmpInst::ICMP_UGT:
11909   case ICmpInst::ICMP_UGE:
11910     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11911         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11912       return true;
11913     break;
11914   }
11915 
11916   // Maybe it can be proved via operations?
11917   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11918     return true;
11919 
11920   return false;
11921 }
11922 
11923 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11924                                                      const SCEV *LHS,
11925                                                      const SCEV *RHS,
11926                                                      const SCEV *FoundLHS,
11927                                                      const SCEV *FoundRHS) {
11928   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11929     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11930     // reduce the compile time impact of this optimization.
11931     return false;
11932 
11933   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11934   if (!Addend)
11935     return false;
11936 
11937   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11938 
11939   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11940   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11941   ConstantRange FoundLHSRange =
11942       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
11943 
11944   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11945   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11946 
11947   // We can also compute the range of values for `LHS` that satisfy the
11948   // consequent, "`LHS` `Pred` `RHS`":
11949   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11950   // The antecedent implies the consequent if every value of `LHS` that
11951   // satisfies the antecedent also satisfies the consequent.
11952   return LHSRange.icmp(Pred, ConstRHS);
11953 }
11954 
11955 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11956                                         bool IsSigned) {
11957   assert(isKnownPositive(Stride) && "Positive stride expected!");
11958 
11959   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11960   const SCEV *One = getOne(Stride->getType());
11961 
11962   if (IsSigned) {
11963     APInt MaxRHS = getSignedRangeMax(RHS);
11964     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11965     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11966 
11967     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11968     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11969   }
11970 
11971   APInt MaxRHS = getUnsignedRangeMax(RHS);
11972   APInt MaxValue = APInt::getMaxValue(BitWidth);
11973   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11974 
11975   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11976   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11977 }
11978 
11979 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11980                                         bool IsSigned) {
11981 
11982   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11983   const SCEV *One = getOne(Stride->getType());
11984 
11985   if (IsSigned) {
11986     APInt MinRHS = getSignedRangeMin(RHS);
11987     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11988     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11989 
11990     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11991     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11992   }
11993 
11994   APInt MinRHS = getUnsignedRangeMin(RHS);
11995   APInt MinValue = APInt::getMinValue(BitWidth);
11996   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11997 
11998   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11999   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12000 }
12001 
12002 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12003   // umin(N, 1) + floor((N - umin(N, 1)) / D)
12004   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12005   // expression fixes the case of N=0.
12006   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12007   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12008   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12009 }
12010 
12011 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12012                                                     const SCEV *Stride,
12013                                                     const SCEV *End,
12014                                                     unsigned BitWidth,
12015                                                     bool IsSigned) {
12016   // The logic in this function assumes we can represent a positive stride.
12017   // If we can't, the backedge-taken count must be zero.
12018   if (IsSigned && BitWidth == 1)
12019     return getZero(Stride->getType());
12020 
12021   // This code has only been closely audited for negative strides in the
12022   // unsigned comparison case, it may be correct for signed comparison, but
12023   // that needs to be established.
12024   assert((!IsSigned || !isKnownNonPositive(Stride)) &&
12025          "Stride is expected strictly positive for signed case!");
12026 
12027   // Calculate the maximum backedge count based on the range of values
12028   // permitted by Start, End, and Stride.
12029   APInt MinStart =
12030       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12031 
12032   APInt MinStride =
12033       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12034 
12035   // We assume either the stride is positive, or the backedge-taken count
12036   // is zero. So force StrideForMaxBECount to be at least one.
12037   APInt One(BitWidth, 1);
12038   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12039                                        : APIntOps::umax(One, MinStride);
12040 
12041   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12042                             : APInt::getMaxValue(BitWidth);
12043   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12044 
12045   // Although End can be a MAX expression we estimate MaxEnd considering only
12046   // the case End = RHS of the loop termination condition. This is safe because
12047   // in the other case (End - Start) is zero, leading to a zero maximum backedge
12048   // taken count.
12049   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12050                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12051 
12052   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12053   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12054                     : APIntOps::umax(MaxEnd, MinStart);
12055 
12056   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12057                          getConstant(StrideForMaxBECount) /* Step */);
12058 }
12059 
12060 ScalarEvolution::ExitLimit
12061 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12062                                   const Loop *L, bool IsSigned,
12063                                   bool ControlsExit, bool AllowPredicates) {
12064   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12065 
12066   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12067   bool PredicatedIV = false;
12068 
12069   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12070     // Can we prove this loop *must* be UB if overflow of IV occurs?
12071     // Reasoning goes as follows:
12072     // * Suppose the IV did self wrap.
12073     // * If Stride evenly divides the iteration space, then once wrap
12074     //   occurs, the loop must revisit the same values.
12075     // * We know that RHS is invariant, and that none of those values
12076     //   caused this exit to be taken previously.  Thus, this exit is
12077     //   dynamically dead.
12078     // * If this is the sole exit, then a dead exit implies the loop
12079     //   must be infinite if there are no abnormal exits.
12080     // * If the loop were infinite, then it must either not be mustprogress
12081     //   or have side effects. Otherwise, it must be UB.
12082     // * It can't (by assumption), be UB so we have contradicted our
12083     //   premise and can conclude the IV did not in fact self-wrap.
12084     if (!isLoopInvariant(RHS, L))
12085       return false;
12086 
12087     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12088     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12089       return false;
12090 
12091     if (!ControlsExit || !loopHasNoAbnormalExits(L))
12092       return false;
12093 
12094     return loopIsFiniteByAssumption(L);
12095   };
12096 
12097   if (!IV) {
12098     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12099       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12100       if (AR && AR->getLoop() == L && AR->isAffine()) {
12101         auto canProveNUW = [&]() {
12102           if (!isLoopInvariant(RHS, L))
12103             return false;
12104 
12105           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12106             // We need the sequence defined by AR to strictly increase in the
12107             // unsigned integer domain for the logic below to hold.
12108             return false;
12109 
12110           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12111           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12112           // If RHS <=u Limit, then there must exist a value V in the sequence
12113           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12114           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
12115           // overflow occurs.  This limit also implies that a signed comparison
12116           // (in the wide bitwidth) is equivalent to an unsigned comparison as
12117           // the high bits on both sides must be zero.
12118           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12119           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12120           Limit = Limit.zext(OuterBitWidth);
12121           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12122         };
12123         auto Flags = AR->getNoWrapFlags();
12124         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12125           Flags = setFlags(Flags, SCEV::FlagNUW);
12126 
12127         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12128         if (AR->hasNoUnsignedWrap()) {
12129           // Emulate what getZeroExtendExpr would have done during construction
12130           // if we'd been able to infer the fact just above at that time.
12131           const SCEV *Step = AR->getStepRecurrence(*this);
12132           Type *Ty = ZExt->getType();
12133           auto *S = getAddRecExpr(
12134             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12135             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12136           IV = dyn_cast<SCEVAddRecExpr>(S);
12137         }
12138       }
12139     }
12140   }
12141 
12142 
12143   if (!IV && AllowPredicates) {
12144     // Try to make this an AddRec using runtime tests, in the first X
12145     // iterations of this loop, where X is the SCEV expression found by the
12146     // algorithm below.
12147     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12148     PredicatedIV = true;
12149   }
12150 
12151   // Avoid weird loops
12152   if (!IV || IV->getLoop() != L || !IV->isAffine())
12153     return getCouldNotCompute();
12154 
12155   // A precondition of this method is that the condition being analyzed
12156   // reaches an exiting branch which dominates the latch.  Given that, we can
12157   // assume that an increment which violates the nowrap specification and
12158   // produces poison must cause undefined behavior when the resulting poison
12159   // value is branched upon and thus we can conclude that the backedge is
12160   // taken no more often than would be required to produce that poison value.
12161   // Note that a well defined loop can exit on the iteration which violates
12162   // the nowrap specification if there is another exit (either explicit or
12163   // implicit/exceptional) which causes the loop to execute before the
12164   // exiting instruction we're analyzing would trigger UB.
12165   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12166   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12167   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12168 
12169   const SCEV *Stride = IV->getStepRecurrence(*this);
12170 
12171   bool PositiveStride = isKnownPositive(Stride);
12172 
12173   // Avoid negative or zero stride values.
12174   if (!PositiveStride) {
12175     // We can compute the correct backedge taken count for loops with unknown
12176     // strides if we can prove that the loop is not an infinite loop with side
12177     // effects. Here's the loop structure we are trying to handle -
12178     //
12179     // i = start
12180     // do {
12181     //   A[i] = i;
12182     //   i += s;
12183     // } while (i < end);
12184     //
12185     // The backedge taken count for such loops is evaluated as -
12186     // (max(end, start + stride) - start - 1) /u stride
12187     //
12188     // The additional preconditions that we need to check to prove correctness
12189     // of the above formula is as follows -
12190     //
12191     // a) IV is either nuw or nsw depending upon signedness (indicated by the
12192     //    NoWrap flag).
12193     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12194     //    no side effects within the loop)
12195     // c) loop has a single static exit (with no abnormal exits)
12196     //
12197     // Precondition a) implies that if the stride is negative, this is a single
12198     // trip loop. The backedge taken count formula reduces to zero in this case.
12199     //
12200     // Precondition b) and c) combine to imply that if rhs is invariant in L,
12201     // then a zero stride means the backedge can't be taken without executing
12202     // undefined behavior.
12203     //
12204     // The positive stride case is the same as isKnownPositive(Stride) returning
12205     // true (original behavior of the function).
12206     //
12207     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12208         !loopHasNoAbnormalExits(L))
12209       return getCouldNotCompute();
12210 
12211     // This bailout is protecting the logic in computeMaxBECountForLT which
12212     // has not yet been sufficiently auditted or tested with negative strides.
12213     // We used to filter out all known-non-positive cases here, we're in the
12214     // process of being less restrictive bit by bit.
12215     if (IsSigned && isKnownNonPositive(Stride))
12216       return getCouldNotCompute();
12217 
12218     if (!isKnownNonZero(Stride)) {
12219       // If we have a step of zero, and RHS isn't invariant in L, we don't know
12220       // if it might eventually be greater than start and if so, on which
12221       // iteration.  We can't even produce a useful upper bound.
12222       if (!isLoopInvariant(RHS, L))
12223         return getCouldNotCompute();
12224 
12225       // We allow a potentially zero stride, but we need to divide by stride
12226       // below.  Since the loop can't be infinite and this check must control
12227       // the sole exit, we can infer the exit must be taken on the first
12228       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
12229       // we know the numerator in the divides below must be zero, so we can
12230       // pick an arbitrary non-zero value for the denominator (e.g. stride)
12231       // and produce the right result.
12232       // FIXME: Handle the case where Stride is poison?
12233       auto wouldZeroStrideBeUB = [&]() {
12234         // Proof by contradiction.  Suppose the stride were zero.  If we can
12235         // prove that the backedge *is* taken on the first iteration, then since
12236         // we know this condition controls the sole exit, we must have an
12237         // infinite loop.  We can't have a (well defined) infinite loop per
12238         // check just above.
12239         // Note: The (Start - Stride) term is used to get the start' term from
12240         // (start' + stride,+,stride). Remember that we only care about the
12241         // result of this expression when stride == 0 at runtime.
12242         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12243         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12244       };
12245       if (!wouldZeroStrideBeUB()) {
12246         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12247       }
12248     }
12249   } else if (!Stride->isOne() && !NoWrap) {
12250     auto isUBOnWrap = [&]() {
12251       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12252       // follows trivially from the fact that every (un)signed-wrapped, but
12253       // not self-wrapped value must be LT than the last value before
12254       // (un)signed wrap.  Since we know that last value didn't exit, nor
12255       // will any smaller one.
12256       return canAssumeNoSelfWrap(IV);
12257     };
12258 
12259     // Avoid proven overflow cases: this will ensure that the backedge taken
12260     // count will not generate any unsigned overflow. Relaxed no-overflow
12261     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12262     // undefined behaviors like the case of C language.
12263     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12264       return getCouldNotCompute();
12265   }
12266 
12267   // On all paths just preceeding, we established the following invariant:
12268   //   IV can be assumed not to overflow up to and including the exiting
12269   //   iteration.  We proved this in one of two ways:
12270   //   1) We can show overflow doesn't occur before the exiting iteration
12271   //      1a) canIVOverflowOnLT, and b) step of one
12272   //   2) We can show that if overflow occurs, the loop must execute UB
12273   //      before any possible exit.
12274   // Note that we have not yet proved RHS invariant (in general).
12275 
12276   const SCEV *Start = IV->getStart();
12277 
12278   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12279   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12280   // Use integer-typed versions for actual computation; we can't subtract
12281   // pointers in general.
12282   const SCEV *OrigStart = Start;
12283   const SCEV *OrigRHS = RHS;
12284   if (Start->getType()->isPointerTy()) {
12285     Start = getLosslessPtrToIntExpr(Start);
12286     if (isa<SCEVCouldNotCompute>(Start))
12287       return Start;
12288   }
12289   if (RHS->getType()->isPointerTy()) {
12290     RHS = getLosslessPtrToIntExpr(RHS);
12291     if (isa<SCEVCouldNotCompute>(RHS))
12292       return RHS;
12293   }
12294 
12295   // When the RHS is not invariant, we do not know the end bound of the loop and
12296   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12297   // calculate the MaxBECount, given the start, stride and max value for the end
12298   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12299   // checked above).
12300   if (!isLoopInvariant(RHS, L)) {
12301     const SCEV *MaxBECount = computeMaxBECountForLT(
12302         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12303     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12304                      false /*MaxOrZero*/, Predicates);
12305   }
12306 
12307   // We use the expression (max(End,Start)-Start)/Stride to describe the
12308   // backedge count, as if the backedge is taken at least once max(End,Start)
12309   // is End and so the result is as above, and if not max(End,Start) is Start
12310   // so we get a backedge count of zero.
12311   const SCEV *BECount = nullptr;
12312   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12313   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12314   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12315   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12316   // Can we prove (max(RHS,Start) > Start - Stride?
12317   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12318       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12319     // In this case, we can use a refined formula for computing backedge taken
12320     // count.  The general formula remains:
12321     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12322     // We want to use the alternate formula:
12323     //   "((End - 1) - (Start - Stride)) /u Stride"
12324     // Let's do a quick case analysis to show these are equivalent under
12325     // our precondition that max(RHS,Start) > Start - Stride.
12326     // * For RHS <= Start, the backedge-taken count must be zero.
12327     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12328     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12329     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12330     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12331     //     this to the stride of 1 case.
12332     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12333     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12334     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12335     //   "((RHS - (Start - Stride) - 1) /u Stride".
12336     //   Our preconditions trivially imply no overflow in that form.
12337     const SCEV *MinusOne = getMinusOne(Stride->getType());
12338     const SCEV *Numerator =
12339         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12340     BECount = getUDivExpr(Numerator, Stride);
12341   }
12342 
12343   const SCEV *BECountIfBackedgeTaken = nullptr;
12344   if (!BECount) {
12345     auto canProveRHSGreaterThanEqualStart = [&]() {
12346       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12347       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12348         return true;
12349 
12350       // (RHS > Start - 1) implies RHS >= Start.
12351       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12352       //   "Start - 1" doesn't overflow.
12353       // * For signed comparison, if Start - 1 does overflow, it's equal
12354       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12355       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12356       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12357       //
12358       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12359       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12360       auto *StartMinusOne = getAddExpr(OrigStart,
12361                                        getMinusOne(OrigStart->getType()));
12362       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12363     };
12364 
12365     // If we know that RHS >= Start in the context of loop, then we know that
12366     // max(RHS, Start) = RHS at this point.
12367     const SCEV *End;
12368     if (canProveRHSGreaterThanEqualStart()) {
12369       End = RHS;
12370     } else {
12371       // If RHS < Start, the backedge will be taken zero times.  So in
12372       // general, we can write the backedge-taken count as:
12373       //
12374       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12375       //
12376       // We convert it to the following to make it more convenient for SCEV:
12377       //
12378       //     ceil(max(RHS, Start) - Start) / Stride
12379       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12380 
12381       // See what would happen if we assume the backedge is taken. This is
12382       // used to compute MaxBECount.
12383       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12384     }
12385 
12386     // At this point, we know:
12387     //
12388     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12389     // 2. The index variable doesn't overflow.
12390     //
12391     // Therefore, we know N exists such that
12392     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12393     // doesn't overflow.
12394     //
12395     // Using this information, try to prove whether the addition in
12396     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12397     const SCEV *One = getOne(Stride->getType());
12398     bool MayAddOverflow = [&] {
12399       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12400         if (StrideC->getAPInt().isPowerOf2()) {
12401           // Suppose Stride is a power of two, and Start/End are unsigned
12402           // integers.  Let UMAX be the largest representable unsigned
12403           // integer.
12404           //
12405           // By the preconditions of this function, we know
12406           // "(Start + Stride * N) >= End", and this doesn't overflow.
12407           // As a formula:
12408           //
12409           //   End <= (Start + Stride * N) <= UMAX
12410           //
12411           // Subtracting Start from all the terms:
12412           //
12413           //   End - Start <= Stride * N <= UMAX - Start
12414           //
12415           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12416           //
12417           //   End - Start <= Stride * N <= UMAX
12418           //
12419           // Stride * N is a multiple of Stride. Therefore,
12420           //
12421           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12422           //
12423           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12424           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12425           //
12426           //   End - Start <= Stride * N <= UMAX - Stride - 1
12427           //
12428           // Dropping the middle term:
12429           //
12430           //   End - Start <= UMAX - Stride - 1
12431           //
12432           // Adding Stride - 1 to both sides:
12433           //
12434           //   (End - Start) + (Stride - 1) <= UMAX
12435           //
12436           // In other words, the addition doesn't have unsigned overflow.
12437           //
12438           // A similar proof works if we treat Start/End as signed values.
12439           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12440           // use signed max instead of unsigned max. Note that we're trying
12441           // to prove a lack of unsigned overflow in either case.
12442           return false;
12443         }
12444       }
12445       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12446         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12447         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12448         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12449         //
12450         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12451         return false;
12452       }
12453       return true;
12454     }();
12455 
12456     const SCEV *Delta = getMinusSCEV(End, Start);
12457     if (!MayAddOverflow) {
12458       // floor((D + (S - 1)) / S)
12459       // We prefer this formulation if it's legal because it's fewer operations.
12460       BECount =
12461           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
12462     } else {
12463       BECount = getUDivCeilSCEV(Delta, Stride);
12464     }
12465   }
12466 
12467   const SCEV *MaxBECount;
12468   bool MaxOrZero = false;
12469   if (isa<SCEVConstant>(BECount)) {
12470     MaxBECount = BECount;
12471   } else if (BECountIfBackedgeTaken &&
12472              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
12473     // If we know exactly how many times the backedge will be taken if it's
12474     // taken at least once, then the backedge count will either be that or
12475     // zero.
12476     MaxBECount = BECountIfBackedgeTaken;
12477     MaxOrZero = true;
12478   } else {
12479     MaxBECount = computeMaxBECountForLT(
12480         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12481   }
12482 
12483   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
12484       !isa<SCEVCouldNotCompute>(BECount))
12485     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
12486 
12487   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
12488 }
12489 
12490 ScalarEvolution::ExitLimit
12491 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
12492                                      const Loop *L, bool IsSigned,
12493                                      bool ControlsExit, bool AllowPredicates) {
12494   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12495   // We handle only IV > Invariant
12496   if (!isLoopInvariant(RHS, L))
12497     return getCouldNotCompute();
12498 
12499   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12500   if (!IV && AllowPredicates)
12501     // Try to make this an AddRec using runtime tests, in the first X
12502     // iterations of this loop, where X is the SCEV expression found by the
12503     // algorithm below.
12504     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12505 
12506   // Avoid weird loops
12507   if (!IV || IV->getLoop() != L || !IV->isAffine())
12508     return getCouldNotCompute();
12509 
12510   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12511   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12512   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12513 
12514   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
12515 
12516   // Avoid negative or zero stride values
12517   if (!isKnownPositive(Stride))
12518     return getCouldNotCompute();
12519 
12520   // Avoid proven overflow cases: this will ensure that the backedge taken count
12521   // will not generate any unsigned overflow. Relaxed no-overflow conditions
12522   // exploit NoWrapFlags, allowing to optimize in presence of undefined
12523   // behaviors like the case of C language.
12524   if (!Stride->isOne() && !NoWrap)
12525     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
12526       return getCouldNotCompute();
12527 
12528   const SCEV *Start = IV->getStart();
12529   const SCEV *End = RHS;
12530   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
12531     // If we know that Start >= RHS in the context of loop, then we know that
12532     // min(RHS, Start) = RHS at this point.
12533     if (isLoopEntryGuardedByCond(
12534             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
12535       End = RHS;
12536     else
12537       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
12538   }
12539 
12540   if (Start->getType()->isPointerTy()) {
12541     Start = getLosslessPtrToIntExpr(Start);
12542     if (isa<SCEVCouldNotCompute>(Start))
12543       return Start;
12544   }
12545   if (End->getType()->isPointerTy()) {
12546     End = getLosslessPtrToIntExpr(End);
12547     if (isa<SCEVCouldNotCompute>(End))
12548       return End;
12549   }
12550 
12551   // Compute ((Start - End) + (Stride - 1)) / Stride.
12552   // FIXME: This can overflow. Holding off on fixing this for now;
12553   // howManyGreaterThans will hopefully be gone soon.
12554   const SCEV *One = getOne(Stride->getType());
12555   const SCEV *BECount = getUDivExpr(
12556       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
12557 
12558   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
12559                             : getUnsignedRangeMax(Start);
12560 
12561   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
12562                              : getUnsignedRangeMin(Stride);
12563 
12564   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
12565   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
12566                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
12567 
12568   // Although End can be a MIN expression we estimate MinEnd considering only
12569   // the case End = RHS. This is safe because in the other case (Start - End)
12570   // is zero, leading to a zero maximum backedge taken count.
12571   APInt MinEnd =
12572     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
12573              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
12574 
12575   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
12576                                ? BECount
12577                                : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
12578                                                  getConstant(MinStride));
12579 
12580   if (isa<SCEVCouldNotCompute>(MaxBECount))
12581     MaxBECount = BECount;
12582 
12583   return ExitLimit(BECount, MaxBECount, false, Predicates);
12584 }
12585 
12586 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
12587                                                     ScalarEvolution &SE) const {
12588   if (Range.isFullSet())  // Infinite loop.
12589     return SE.getCouldNotCompute();
12590 
12591   // If the start is a non-zero constant, shift the range to simplify things.
12592   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
12593     if (!SC->getValue()->isZero()) {
12594       SmallVector<const SCEV *, 4> Operands(operands());
12595       Operands[0] = SE.getZero(SC->getType());
12596       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
12597                                              getNoWrapFlags(FlagNW));
12598       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
12599         return ShiftedAddRec->getNumIterationsInRange(
12600             Range.subtract(SC->getAPInt()), SE);
12601       // This is strange and shouldn't happen.
12602       return SE.getCouldNotCompute();
12603     }
12604 
12605   // The only time we can solve this is when we have all constant indices.
12606   // Otherwise, we cannot determine the overflow conditions.
12607   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
12608     return SE.getCouldNotCompute();
12609 
12610   // Okay at this point we know that all elements of the chrec are constants and
12611   // that the start element is zero.
12612 
12613   // First check to see if the range contains zero.  If not, the first
12614   // iteration exits.
12615   unsigned BitWidth = SE.getTypeSizeInBits(getType());
12616   if (!Range.contains(APInt(BitWidth, 0)))
12617     return SE.getZero(getType());
12618 
12619   if (isAffine()) {
12620     // If this is an affine expression then we have this situation:
12621     //   Solve {0,+,A} in Range  ===  Ax in Range
12622 
12623     // We know that zero is in the range.  If A is positive then we know that
12624     // the upper value of the range must be the first possible exit value.
12625     // If A is negative then the lower of the range is the last possible loop
12626     // value.  Also note that we already checked for a full range.
12627     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
12628     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
12629 
12630     // The exit value should be (End+A)/A.
12631     APInt ExitVal = (End + A).udiv(A);
12632     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
12633 
12634     // Evaluate at the exit value.  If we really did fall out of the valid
12635     // range, then we computed our trip count, otherwise wrap around or other
12636     // things must have happened.
12637     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
12638     if (Range.contains(Val->getValue()))
12639       return SE.getCouldNotCompute();  // Something strange happened
12640 
12641     // Ensure that the previous value is in the range.
12642     assert(Range.contains(
12643            EvaluateConstantChrecAtConstant(this,
12644            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
12645            "Linear scev computation is off in a bad way!");
12646     return SE.getConstant(ExitValue);
12647   }
12648 
12649   if (isQuadratic()) {
12650     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
12651       return SE.getConstant(S.getValue());
12652   }
12653 
12654   return SE.getCouldNotCompute();
12655 }
12656 
12657 const SCEVAddRecExpr *
12658 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
12659   assert(getNumOperands() > 1 && "AddRec with zero step?");
12660   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
12661   // but in this case we cannot guarantee that the value returned will be an
12662   // AddRec because SCEV does not have a fixed point where it stops
12663   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
12664   // may happen if we reach arithmetic depth limit while simplifying. So we
12665   // construct the returned value explicitly.
12666   SmallVector<const SCEV *, 3> Ops;
12667   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
12668   // (this + Step) is {A+B,+,B+C,+...,+,N}.
12669   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
12670     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
12671   // We know that the last operand is not a constant zero (otherwise it would
12672   // have been popped out earlier). This guarantees us that if the result has
12673   // the same last operand, then it will also not be popped out, meaning that
12674   // the returned value will be an AddRec.
12675   const SCEV *Last = getOperand(getNumOperands() - 1);
12676   assert(!Last->isZero() && "Recurrency with zero step?");
12677   Ops.push_back(Last);
12678   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
12679                                                SCEV::FlagAnyWrap));
12680 }
12681 
12682 // Return true when S contains at least an undef value.
12683 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
12684   return SCEVExprContains(S, [](const SCEV *S) {
12685     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12686       return isa<UndefValue>(SU->getValue());
12687     return false;
12688   });
12689 }
12690 
12691 /// Return the size of an element read or written by Inst.
12692 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12693   Type *Ty;
12694   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12695     Ty = Store->getValueOperand()->getType();
12696   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12697     Ty = Load->getType();
12698   else
12699     return nullptr;
12700 
12701   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12702   return getSizeOfExpr(ETy, Ty);
12703 }
12704 
12705 //===----------------------------------------------------------------------===//
12706 //                   SCEVCallbackVH Class Implementation
12707 //===----------------------------------------------------------------------===//
12708 
12709 void ScalarEvolution::SCEVCallbackVH::deleted() {
12710   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12711   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12712     SE->ConstantEvolutionLoopExitValue.erase(PN);
12713   SE->eraseValueFromMap(getValPtr());
12714   // this now dangles!
12715 }
12716 
12717 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12718   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12719 
12720   // Forget all the expressions associated with users of the old value,
12721   // so that future queries will recompute the expressions using the new
12722   // value.
12723   Value *Old = getValPtr();
12724   SmallVector<User *, 16> Worklist(Old->users());
12725   SmallPtrSet<User *, 8> Visited;
12726   while (!Worklist.empty()) {
12727     User *U = Worklist.pop_back_val();
12728     // Deleting the Old value will cause this to dangle. Postpone
12729     // that until everything else is done.
12730     if (U == Old)
12731       continue;
12732     if (!Visited.insert(U).second)
12733       continue;
12734     if (PHINode *PN = dyn_cast<PHINode>(U))
12735       SE->ConstantEvolutionLoopExitValue.erase(PN);
12736     SE->eraseValueFromMap(U);
12737     llvm::append_range(Worklist, U->users());
12738   }
12739   // Delete the Old value.
12740   if (PHINode *PN = dyn_cast<PHINode>(Old))
12741     SE->ConstantEvolutionLoopExitValue.erase(PN);
12742   SE->eraseValueFromMap(Old);
12743   // this now dangles!
12744 }
12745 
12746 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12747   : CallbackVH(V), SE(se) {}
12748 
12749 //===----------------------------------------------------------------------===//
12750 //                   ScalarEvolution Class Implementation
12751 //===----------------------------------------------------------------------===//
12752 
12753 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12754                                  AssumptionCache &AC, DominatorTree &DT,
12755                                  LoopInfo &LI)
12756     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12757       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12758       LoopDispositions(64), BlockDispositions(64) {
12759   // To use guards for proving predicates, we need to scan every instruction in
12760   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12761   // time if the IR does not actually contain any calls to
12762   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12763   //
12764   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12765   // to _add_ guards to the module when there weren't any before, and wants
12766   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12767   // efficient in lieu of being smart in that rather obscure case.
12768 
12769   auto *GuardDecl = F.getParent()->getFunction(
12770       Intrinsic::getName(Intrinsic::experimental_guard));
12771   HasGuards = GuardDecl && !GuardDecl->use_empty();
12772 }
12773 
12774 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12775     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12776       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12777       ValueExprMap(std::move(Arg.ValueExprMap)),
12778       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12779       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12780       PendingMerges(std::move(Arg.PendingMerges)),
12781       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12782       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12783       PredicatedBackedgeTakenCounts(
12784           std::move(Arg.PredicatedBackedgeTakenCounts)),
12785       BECountUsers(std::move(Arg.BECountUsers)),
12786       ConstantEvolutionLoopExitValue(
12787           std::move(Arg.ConstantEvolutionLoopExitValue)),
12788       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12789       ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
12790       LoopDispositions(std::move(Arg.LoopDispositions)),
12791       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12792       BlockDispositions(std::move(Arg.BlockDispositions)),
12793       SCEVUsers(std::move(Arg.SCEVUsers)),
12794       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12795       SignedRanges(std::move(Arg.SignedRanges)),
12796       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12797       UniquePreds(std::move(Arg.UniquePreds)),
12798       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12799       LoopUsers(std::move(Arg.LoopUsers)),
12800       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12801       FirstUnknown(Arg.FirstUnknown) {
12802   Arg.FirstUnknown = nullptr;
12803 }
12804 
12805 ScalarEvolution::~ScalarEvolution() {
12806   // Iterate through all the SCEVUnknown instances and call their
12807   // destructors, so that they release their references to their values.
12808   for (SCEVUnknown *U = FirstUnknown; U;) {
12809     SCEVUnknown *Tmp = U;
12810     U = U->Next;
12811     Tmp->~SCEVUnknown();
12812   }
12813   FirstUnknown = nullptr;
12814 
12815   ExprValueMap.clear();
12816   ValueExprMap.clear();
12817   HasRecMap.clear();
12818   BackedgeTakenCounts.clear();
12819   PredicatedBackedgeTakenCounts.clear();
12820 
12821   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12822   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12823   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12824   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12825   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12826 }
12827 
12828 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12829   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12830 }
12831 
12832 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12833                           const Loop *L) {
12834   // Print all inner loops first
12835   for (Loop *I : *L)
12836     PrintLoopInfo(OS, SE, I);
12837 
12838   OS << "Loop ";
12839   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12840   OS << ": ";
12841 
12842   SmallVector<BasicBlock *, 8> ExitingBlocks;
12843   L->getExitingBlocks(ExitingBlocks);
12844   if (ExitingBlocks.size() != 1)
12845     OS << "<multiple exits> ";
12846 
12847   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12848     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12849   else
12850     OS << "Unpredictable backedge-taken count.\n";
12851 
12852   if (ExitingBlocks.size() > 1)
12853     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12854       OS << "  exit count for " << ExitingBlock->getName() << ": "
12855          << *SE->getExitCount(L, ExitingBlock) << "\n";
12856     }
12857 
12858   OS << "Loop ";
12859   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12860   OS << ": ";
12861 
12862   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12863     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12864     if (SE->isBackedgeTakenCountMaxOrZero(L))
12865       OS << ", actual taken count either this or zero.";
12866   } else {
12867     OS << "Unpredictable max backedge-taken count. ";
12868   }
12869 
12870   OS << "\n"
12871         "Loop ";
12872   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12873   OS << ": ";
12874 
12875   SmallVector<const SCEVPredicate *, 4> Preds;
12876   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
12877   if (!isa<SCEVCouldNotCompute>(PBT)) {
12878     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12879     OS << " Predicates:\n";
12880     for (auto *P : Preds)
12881       P->print(OS, 4);
12882   } else {
12883     OS << "Unpredictable predicated backedge-taken count. ";
12884   }
12885   OS << "\n";
12886 
12887   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12888     OS << "Loop ";
12889     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12890     OS << ": ";
12891     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12892   }
12893 }
12894 
12895 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12896   switch (LD) {
12897   case ScalarEvolution::LoopVariant:
12898     return "Variant";
12899   case ScalarEvolution::LoopInvariant:
12900     return "Invariant";
12901   case ScalarEvolution::LoopComputable:
12902     return "Computable";
12903   }
12904   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12905 }
12906 
12907 void ScalarEvolution::print(raw_ostream &OS) const {
12908   // ScalarEvolution's implementation of the print method is to print
12909   // out SCEV values of all instructions that are interesting. Doing
12910   // this potentially causes it to create new SCEV objects though,
12911   // which technically conflicts with the const qualifier. This isn't
12912   // observable from outside the class though, so casting away the
12913   // const isn't dangerous.
12914   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12915 
12916   if (ClassifyExpressions) {
12917     OS << "Classifying expressions for: ";
12918     F.printAsOperand(OS, /*PrintType=*/false);
12919     OS << "\n";
12920     for (Instruction &I : instructions(F))
12921       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12922         OS << I << '\n';
12923         OS << "  -->  ";
12924         const SCEV *SV = SE.getSCEV(&I);
12925         SV->print(OS);
12926         if (!isa<SCEVCouldNotCompute>(SV)) {
12927           OS << " U: ";
12928           SE.getUnsignedRange(SV).print(OS);
12929           OS << " S: ";
12930           SE.getSignedRange(SV).print(OS);
12931         }
12932 
12933         const Loop *L = LI.getLoopFor(I.getParent());
12934 
12935         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12936         if (AtUse != SV) {
12937           OS << "  -->  ";
12938           AtUse->print(OS);
12939           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12940             OS << " U: ";
12941             SE.getUnsignedRange(AtUse).print(OS);
12942             OS << " S: ";
12943             SE.getSignedRange(AtUse).print(OS);
12944           }
12945         }
12946 
12947         if (L) {
12948           OS << "\t\t" "Exits: ";
12949           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12950           if (!SE.isLoopInvariant(ExitValue, L)) {
12951             OS << "<<Unknown>>";
12952           } else {
12953             OS << *ExitValue;
12954           }
12955 
12956           bool First = true;
12957           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12958             if (First) {
12959               OS << "\t\t" "LoopDispositions: { ";
12960               First = false;
12961             } else {
12962               OS << ", ";
12963             }
12964 
12965             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12966             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12967           }
12968 
12969           for (auto *InnerL : depth_first(L)) {
12970             if (InnerL == L)
12971               continue;
12972             if (First) {
12973               OS << "\t\t" "LoopDispositions: { ";
12974               First = false;
12975             } else {
12976               OS << ", ";
12977             }
12978 
12979             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12980             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12981           }
12982 
12983           OS << " }";
12984         }
12985 
12986         OS << "\n";
12987       }
12988   }
12989 
12990   OS << "Determining loop execution counts for: ";
12991   F.printAsOperand(OS, /*PrintType=*/false);
12992   OS << "\n";
12993   for (Loop *I : LI)
12994     PrintLoopInfo(OS, &SE, I);
12995 }
12996 
12997 ScalarEvolution::LoopDisposition
12998 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12999   auto &Values = LoopDispositions[S];
13000   for (auto &V : Values) {
13001     if (V.getPointer() == L)
13002       return V.getInt();
13003   }
13004   Values.emplace_back(L, LoopVariant);
13005   LoopDisposition D = computeLoopDisposition(S, L);
13006   auto &Values2 = LoopDispositions[S];
13007   for (auto &V : llvm::reverse(Values2)) {
13008     if (V.getPointer() == L) {
13009       V.setInt(D);
13010       break;
13011     }
13012   }
13013   return D;
13014 }
13015 
13016 ScalarEvolution::LoopDisposition
13017 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13018   switch (S->getSCEVType()) {
13019   case scConstant:
13020     return LoopInvariant;
13021   case scPtrToInt:
13022   case scTruncate:
13023   case scZeroExtend:
13024   case scSignExtend:
13025     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
13026   case scAddRecExpr: {
13027     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13028 
13029     // If L is the addrec's loop, it's computable.
13030     if (AR->getLoop() == L)
13031       return LoopComputable;
13032 
13033     // Add recurrences are never invariant in the function-body (null loop).
13034     if (!L)
13035       return LoopVariant;
13036 
13037     // Everything that is not defined at loop entry is variant.
13038     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13039       return LoopVariant;
13040     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13041            " dominate the contained loop's header?");
13042 
13043     // This recurrence is invariant w.r.t. L if AR's loop contains L.
13044     if (AR->getLoop()->contains(L))
13045       return LoopInvariant;
13046 
13047     // This recurrence is variant w.r.t. L if any of its operands
13048     // are variant.
13049     for (auto *Op : AR->operands())
13050       if (!isLoopInvariant(Op, L))
13051         return LoopVariant;
13052 
13053     // Otherwise it's loop-invariant.
13054     return LoopInvariant;
13055   }
13056   case scAddExpr:
13057   case scMulExpr:
13058   case scUMaxExpr:
13059   case scSMaxExpr:
13060   case scUMinExpr:
13061   case scSMinExpr:
13062   case scSequentialUMinExpr: {
13063     bool HasVarying = false;
13064     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
13065       LoopDisposition D = getLoopDisposition(Op, L);
13066       if (D == LoopVariant)
13067         return LoopVariant;
13068       if (D == LoopComputable)
13069         HasVarying = true;
13070     }
13071     return HasVarying ? LoopComputable : LoopInvariant;
13072   }
13073   case scUDivExpr: {
13074     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13075     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
13076     if (LD == LoopVariant)
13077       return LoopVariant;
13078     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
13079     if (RD == LoopVariant)
13080       return LoopVariant;
13081     return (LD == LoopInvariant && RD == LoopInvariant) ?
13082            LoopInvariant : LoopComputable;
13083   }
13084   case scUnknown:
13085     // All non-instruction values are loop invariant.  All instructions are loop
13086     // invariant if they are not contained in the specified loop.
13087     // Instructions are never considered invariant in the function body
13088     // (null loop) because they are defined within the "loop".
13089     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13090       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13091     return LoopInvariant;
13092   case scCouldNotCompute:
13093     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13094   }
13095   llvm_unreachable("Unknown SCEV kind!");
13096 }
13097 
13098 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13099   return getLoopDisposition(S, L) == LoopInvariant;
13100 }
13101 
13102 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13103   return getLoopDisposition(S, L) == LoopComputable;
13104 }
13105 
13106 ScalarEvolution::BlockDisposition
13107 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13108   auto &Values = BlockDispositions[S];
13109   for (auto &V : Values) {
13110     if (V.getPointer() == BB)
13111       return V.getInt();
13112   }
13113   Values.emplace_back(BB, DoesNotDominateBlock);
13114   BlockDisposition D = computeBlockDisposition(S, BB);
13115   auto &Values2 = BlockDispositions[S];
13116   for (auto &V : llvm::reverse(Values2)) {
13117     if (V.getPointer() == BB) {
13118       V.setInt(D);
13119       break;
13120     }
13121   }
13122   return D;
13123 }
13124 
13125 ScalarEvolution::BlockDisposition
13126 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13127   switch (S->getSCEVType()) {
13128   case scConstant:
13129     return ProperlyDominatesBlock;
13130   case scPtrToInt:
13131   case scTruncate:
13132   case scZeroExtend:
13133   case scSignExtend:
13134     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
13135   case scAddRecExpr: {
13136     // This uses a "dominates" query instead of "properly dominates" query
13137     // to test for proper dominance too, because the instruction which
13138     // produces the addrec's value is a PHI, and a PHI effectively properly
13139     // dominates its entire containing block.
13140     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13141     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13142       return DoesNotDominateBlock;
13143 
13144     // Fall through into SCEVNAryExpr handling.
13145     LLVM_FALLTHROUGH;
13146   }
13147   case scAddExpr:
13148   case scMulExpr:
13149   case scUMaxExpr:
13150   case scSMaxExpr:
13151   case scUMinExpr:
13152   case scSMinExpr:
13153   case scSequentialUMinExpr: {
13154     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
13155     bool Proper = true;
13156     for (const SCEV *NAryOp : NAry->operands()) {
13157       BlockDisposition D = getBlockDisposition(NAryOp, BB);
13158       if (D == DoesNotDominateBlock)
13159         return DoesNotDominateBlock;
13160       if (D == DominatesBlock)
13161         Proper = false;
13162     }
13163     return Proper ? ProperlyDominatesBlock : DominatesBlock;
13164   }
13165   case scUDivExpr: {
13166     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13167     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
13168     BlockDisposition LD = getBlockDisposition(LHS, BB);
13169     if (LD == DoesNotDominateBlock)
13170       return DoesNotDominateBlock;
13171     BlockDisposition RD = getBlockDisposition(RHS, BB);
13172     if (RD == DoesNotDominateBlock)
13173       return DoesNotDominateBlock;
13174     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
13175       ProperlyDominatesBlock : DominatesBlock;
13176   }
13177   case scUnknown:
13178     if (Instruction *I =
13179           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13180       if (I->getParent() == BB)
13181         return DominatesBlock;
13182       if (DT.properlyDominates(I->getParent(), BB))
13183         return ProperlyDominatesBlock;
13184       return DoesNotDominateBlock;
13185     }
13186     return ProperlyDominatesBlock;
13187   case scCouldNotCompute:
13188     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13189   }
13190   llvm_unreachable("Unknown SCEV kind!");
13191 }
13192 
13193 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13194   return getBlockDisposition(S, BB) >= DominatesBlock;
13195 }
13196 
13197 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13198   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13199 }
13200 
13201 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13202   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13203 }
13204 
13205 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13206                                                 bool Predicated) {
13207   auto &BECounts =
13208       Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13209   auto It = BECounts.find(L);
13210   if (It != BECounts.end()) {
13211     for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13212       if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13213         auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13214         assert(UserIt != BECountUsers.end());
13215         UserIt->second.erase({L, Predicated});
13216       }
13217     }
13218     BECounts.erase(It);
13219   }
13220 }
13221 
13222 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13223   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13224   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13225 
13226   while (!Worklist.empty()) {
13227     const SCEV *Curr = Worklist.pop_back_val();
13228     auto Users = SCEVUsers.find(Curr);
13229     if (Users != SCEVUsers.end())
13230       for (auto *User : Users->second)
13231         if (ToForget.insert(User).second)
13232           Worklist.push_back(User);
13233   }
13234 
13235   for (auto *S : ToForget)
13236     forgetMemoizedResultsImpl(S);
13237 
13238   for (auto I = PredicatedSCEVRewrites.begin();
13239        I != PredicatedSCEVRewrites.end();) {
13240     std::pair<const SCEV *, const Loop *> Entry = I->first;
13241     if (ToForget.count(Entry.first))
13242       PredicatedSCEVRewrites.erase(I++);
13243     else
13244       ++I;
13245   }
13246 }
13247 
13248 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13249   LoopDispositions.erase(S);
13250   BlockDispositions.erase(S);
13251   UnsignedRanges.erase(S);
13252   SignedRanges.erase(S);
13253   HasRecMap.erase(S);
13254   MinTrailingZerosCache.erase(S);
13255 
13256   auto ExprIt = ExprValueMap.find(S);
13257   if (ExprIt != ExprValueMap.end()) {
13258     for (Value *V : ExprIt->second) {
13259       auto ValueIt = ValueExprMap.find_as(V);
13260       if (ValueIt != ValueExprMap.end())
13261         ValueExprMap.erase(ValueIt);
13262     }
13263     ExprValueMap.erase(ExprIt);
13264   }
13265 
13266   auto ScopeIt = ValuesAtScopes.find(S);
13267   if (ScopeIt != ValuesAtScopes.end()) {
13268     for (const auto &Pair : ScopeIt->second)
13269       if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13270         erase_value(ValuesAtScopesUsers[Pair.second],
13271                     std::make_pair(Pair.first, S));
13272     ValuesAtScopes.erase(ScopeIt);
13273   }
13274 
13275   auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13276   if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13277     for (const auto &Pair : ScopeUserIt->second)
13278       erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13279     ValuesAtScopesUsers.erase(ScopeUserIt);
13280   }
13281 
13282   auto BEUsersIt = BECountUsers.find(S);
13283   if (BEUsersIt != BECountUsers.end()) {
13284     // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13285     auto Copy = BEUsersIt->second;
13286     for (const auto &Pair : Copy)
13287       forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13288     BECountUsers.erase(BEUsersIt);
13289   }
13290 }
13291 
13292 void
13293 ScalarEvolution::getUsedLoops(const SCEV *S,
13294                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13295   struct FindUsedLoops {
13296     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13297         : LoopsUsed(LoopsUsed) {}
13298     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13299     bool follow(const SCEV *S) {
13300       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13301         LoopsUsed.insert(AR->getLoop());
13302       return true;
13303     }
13304 
13305     bool isDone() const { return false; }
13306   };
13307 
13308   FindUsedLoops F(LoopsUsed);
13309   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13310 }
13311 
13312 void ScalarEvolution::getReachableBlocks(
13313     SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13314   SmallVector<BasicBlock *> Worklist;
13315   Worklist.push_back(&F.getEntryBlock());
13316   while (!Worklist.empty()) {
13317     BasicBlock *BB = Worklist.pop_back_val();
13318     if (!Reachable.insert(BB).second)
13319       continue;
13320 
13321     Value *Cond;
13322     BasicBlock *TrueBB, *FalseBB;
13323     if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
13324                                         m_BasicBlock(FalseBB)))) {
13325       if (auto *C = dyn_cast<ConstantInt>(Cond)) {
13326         Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
13327         continue;
13328       }
13329 
13330       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13331         const SCEV *L = getSCEV(Cmp->getOperand(0));
13332         const SCEV *R = getSCEV(Cmp->getOperand(1));
13333         if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
13334           Worklist.push_back(TrueBB);
13335           continue;
13336         }
13337         if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
13338                                               R)) {
13339           Worklist.push_back(FalseBB);
13340           continue;
13341         }
13342       }
13343     }
13344 
13345     append_range(Worklist, successors(BB));
13346   }
13347 }
13348 
13349 void ScalarEvolution::verify() const {
13350   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13351   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13352 
13353   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13354 
13355   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13356   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13357     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13358 
13359     const SCEV *visitConstant(const SCEVConstant *Constant) {
13360       return SE.getConstant(Constant->getAPInt());
13361     }
13362 
13363     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13364       return SE.getUnknown(Expr->getValue());
13365     }
13366 
13367     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13368       return SE.getCouldNotCompute();
13369     }
13370   };
13371 
13372   SCEVMapper SCM(SE2);
13373   SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13374   SE2.getReachableBlocks(ReachableBlocks, F);
13375 
13376   auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
13377     if (containsUndefs(Old) || containsUndefs(New)) {
13378       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13379       // not propagate undef aggressively).  This means we can (and do) fail
13380       // verification in cases where a transform makes a value go from "undef"
13381       // to "undef+1" (say).  The transform is fine, since in both cases the
13382       // result is "undef", but SCEV thinks the value increased by 1.
13383       return nullptr;
13384     }
13385 
13386     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13387     const SCEV *Delta = SE2.getMinusSCEV(Old, New);
13388     if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
13389       return nullptr;
13390 
13391     return Delta;
13392   };
13393 
13394   while (!LoopStack.empty()) {
13395     auto *L = LoopStack.pop_back_val();
13396     llvm::append_range(LoopStack, *L);
13397 
13398     // Only verify BECounts in reachable loops. For an unreachable loop,
13399     // any BECount is legal.
13400     if (!ReachableBlocks.contains(L->getHeader()))
13401       continue;
13402 
13403     // Only verify cached BECounts. Computing new BECounts may change the
13404     // results of subsequent SCEV uses.
13405     auto It = BackedgeTakenCounts.find(L);
13406     if (It == BackedgeTakenCounts.end())
13407       continue;
13408 
13409     auto *CurBECount =
13410         SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
13411     auto *NewBECount = SE2.getBackedgeTakenCount(L);
13412 
13413     if (CurBECount == SE2.getCouldNotCompute() ||
13414         NewBECount == SE2.getCouldNotCompute()) {
13415       // NB! This situation is legal, but is very suspicious -- whatever pass
13416       // change the loop to make a trip count go from could not compute to
13417       // computable or vice-versa *should have* invalidated SCEV.  However, we
13418       // choose not to assert here (for now) since we don't want false
13419       // positives.
13420       continue;
13421     }
13422 
13423     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13424         SE.getTypeSizeInBits(NewBECount->getType()))
13425       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13426     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13427              SE.getTypeSizeInBits(NewBECount->getType()))
13428       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13429 
13430     const SCEV *Delta = GetDelta(CurBECount, NewBECount);
13431     if (Delta && !Delta->isZero()) {
13432       dbgs() << "Trip Count for " << *L << " Changed!\n";
13433       dbgs() << "Old: " << *CurBECount << "\n";
13434       dbgs() << "New: " << *NewBECount << "\n";
13435       dbgs() << "Delta: " << *Delta << "\n";
13436       std::abort();
13437     }
13438   }
13439 
13440   // Collect all valid loops currently in LoopInfo.
13441   SmallPtrSet<Loop *, 32> ValidLoops;
13442   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13443   while (!Worklist.empty()) {
13444     Loop *L = Worklist.pop_back_val();
13445     if (ValidLoops.insert(L).second)
13446       Worklist.append(L->begin(), L->end());
13447   }
13448   for (auto &KV : ValueExprMap) {
13449 #ifndef NDEBUG
13450     // Check for SCEV expressions referencing invalid/deleted loops.
13451     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
13452       assert(ValidLoops.contains(AR->getLoop()) &&
13453              "AddRec references invalid loop");
13454     }
13455 #endif
13456 
13457     // Check that the value is also part of the reverse map.
13458     auto It = ExprValueMap.find(KV.second);
13459     if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
13460       dbgs() << "Value " << *KV.first
13461              << " is in ValueExprMap but not in ExprValueMap\n";
13462       std::abort();
13463     }
13464 
13465     if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
13466       if (!ReachableBlocks.contains(I->getParent()))
13467         continue;
13468       const SCEV *OldSCEV = SCM.visit(KV.second);
13469       const SCEV *NewSCEV = SE2.getSCEV(I);
13470       const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
13471       if (Delta && !Delta->isZero()) {
13472         dbgs() << "SCEV for value " << *I << " changed!\n"
13473                << "Old: " << *OldSCEV << "\n"
13474                << "New: " << *NewSCEV << "\n"
13475                << "Delta: " << *Delta << "\n";
13476         std::abort();
13477       }
13478     }
13479   }
13480 
13481   for (const auto &KV : ExprValueMap) {
13482     for (Value *V : KV.second) {
13483       auto It = ValueExprMap.find_as(V);
13484       if (It == ValueExprMap.end()) {
13485         dbgs() << "Value " << *V
13486                << " is in ExprValueMap but not in ValueExprMap\n";
13487         std::abort();
13488       }
13489       if (It->second != KV.first) {
13490         dbgs() << "Value " << *V << " mapped to " << *It->second
13491                << " rather than " << *KV.first << "\n";
13492         std::abort();
13493       }
13494     }
13495   }
13496 
13497   // Verify integrity of SCEV users.
13498   for (const auto &S : UniqueSCEVs) {
13499     SmallVector<const SCEV *, 4> Ops;
13500     collectUniqueOps(&S, Ops);
13501     for (const auto *Op : Ops) {
13502       // We do not store dependencies of constants.
13503       if (isa<SCEVConstant>(Op))
13504         continue;
13505       auto It = SCEVUsers.find(Op);
13506       if (It != SCEVUsers.end() && It->second.count(&S))
13507         continue;
13508       dbgs() << "Use of operand  " << *Op << " by user " << S
13509              << " is not being tracked!\n";
13510       std::abort();
13511     }
13512   }
13513 
13514   // Verify integrity of ValuesAtScopes users.
13515   for (const auto &ValueAndVec : ValuesAtScopes) {
13516     const SCEV *Value = ValueAndVec.first;
13517     for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
13518       const Loop *L = LoopAndValueAtScope.first;
13519       const SCEV *ValueAtScope = LoopAndValueAtScope.second;
13520       if (!isa<SCEVConstant>(ValueAtScope)) {
13521         auto It = ValuesAtScopesUsers.find(ValueAtScope);
13522         if (It != ValuesAtScopesUsers.end() &&
13523             is_contained(It->second, std::make_pair(L, Value)))
13524           continue;
13525         dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13526                << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
13527         std::abort();
13528       }
13529     }
13530   }
13531 
13532   for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
13533     const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
13534     for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
13535       const Loop *L = LoopAndValue.first;
13536       const SCEV *Value = LoopAndValue.second;
13537       assert(!isa<SCEVConstant>(Value));
13538       auto It = ValuesAtScopes.find(Value);
13539       if (It != ValuesAtScopes.end() &&
13540           is_contained(It->second, std::make_pair(L, ValueAtScope)))
13541         continue;
13542       dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13543              << *ValueAtScope << " missing in ValuesAtScopes\n";
13544       std::abort();
13545     }
13546   }
13547 
13548   // Verify integrity of BECountUsers.
13549   auto VerifyBECountUsers = [&](bool Predicated) {
13550     auto &BECounts =
13551         Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13552     for (const auto &LoopAndBEInfo : BECounts) {
13553       for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
13554         if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13555           auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13556           if (UserIt != BECountUsers.end() &&
13557               UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
13558             continue;
13559           dbgs() << "Value " << *ENT.ExactNotTaken << " for loop "
13560                  << *LoopAndBEInfo.first << " missing from BECountUsers\n";
13561           std::abort();
13562         }
13563       }
13564     }
13565   };
13566   VerifyBECountUsers(/* Predicated */ false);
13567   VerifyBECountUsers(/* Predicated */ true);
13568 }
13569 
13570 bool ScalarEvolution::invalidate(
13571     Function &F, const PreservedAnalyses &PA,
13572     FunctionAnalysisManager::Invalidator &Inv) {
13573   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13574   // of its dependencies is invalidated.
13575   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13576   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13577          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13578          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13579          Inv.invalidate<LoopAnalysis>(F, PA);
13580 }
13581 
13582 AnalysisKey ScalarEvolutionAnalysis::Key;
13583 
13584 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13585                                              FunctionAnalysisManager &AM) {
13586   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13587                          AM.getResult<AssumptionAnalysis>(F),
13588                          AM.getResult<DominatorTreeAnalysis>(F),
13589                          AM.getResult<LoopAnalysis>(F));
13590 }
13591 
13592 PreservedAnalyses
13593 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13594   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13595   return PreservedAnalyses::all();
13596 }
13597 
13598 PreservedAnalyses
13599 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13600   // For compatibility with opt's -analyze feature under legacy pass manager
13601   // which was not ported to NPM. This keeps tests using
13602   // update_analyze_test_checks.py working.
13603   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13604      << F.getName() << "':\n";
13605   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13606   return PreservedAnalyses::all();
13607 }
13608 
13609 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13610                       "Scalar Evolution Analysis", false, true)
13611 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13612 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13613 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13614 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13615 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13616                     "Scalar Evolution Analysis", false, true)
13617 
13618 char ScalarEvolutionWrapperPass::ID = 0;
13619 
13620 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13621   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13622 }
13623 
13624 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13625   SE.reset(new ScalarEvolution(
13626       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13627       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13628       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13629       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13630   return false;
13631 }
13632 
13633 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13634 
13635 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13636   SE->print(OS);
13637 }
13638 
13639 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13640   if (!VerifySCEV)
13641     return;
13642 
13643   SE->verify();
13644 }
13645 
13646 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13647   AU.setPreservesAll();
13648   AU.addRequiredTransitive<AssumptionCacheTracker>();
13649   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13650   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13651   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13652 }
13653 
13654 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13655                                                         const SCEV *RHS) {
13656   return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
13657 }
13658 
13659 const SCEVPredicate *
13660 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
13661                                      const SCEV *LHS, const SCEV *RHS) {
13662   FoldingSetNodeID ID;
13663   assert(LHS->getType() == RHS->getType() &&
13664          "Type mismatch between LHS and RHS");
13665   // Unique this node based on the arguments
13666   ID.AddInteger(SCEVPredicate::P_Compare);
13667   ID.AddInteger(Pred);
13668   ID.AddPointer(LHS);
13669   ID.AddPointer(RHS);
13670   void *IP = nullptr;
13671   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13672     return S;
13673   SCEVComparePredicate *Eq = new (SCEVAllocator)
13674     SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
13675   UniquePreds.InsertNode(Eq, IP);
13676   return Eq;
13677 }
13678 
13679 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13680     const SCEVAddRecExpr *AR,
13681     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13682   FoldingSetNodeID ID;
13683   // Unique this node based on the arguments
13684   ID.AddInteger(SCEVPredicate::P_Wrap);
13685   ID.AddPointer(AR);
13686   ID.AddInteger(AddedFlags);
13687   void *IP = nullptr;
13688   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13689     return S;
13690   auto *OF = new (SCEVAllocator)
13691       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13692   UniquePreds.InsertNode(OF, IP);
13693   return OF;
13694 }
13695 
13696 namespace {
13697 
13698 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13699 public:
13700 
13701   /// Rewrites \p S in the context of a loop L and the SCEV predication
13702   /// infrastructure.
13703   ///
13704   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13705   /// equivalences present in \p Pred.
13706   ///
13707   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13708   /// \p NewPreds such that the result will be an AddRecExpr.
13709   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13710                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13711                              const SCEVPredicate *Pred) {
13712     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13713     return Rewriter.visit(S);
13714   }
13715 
13716   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13717     if (Pred) {
13718       if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
13719         for (auto *Pred : U->getPredicates())
13720           if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
13721             if (IPred->getLHS() == Expr &&
13722                 IPred->getPredicate() == ICmpInst::ICMP_EQ)
13723               return IPred->getRHS();
13724       } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
13725         if (IPred->getLHS() == Expr &&
13726             IPred->getPredicate() == ICmpInst::ICMP_EQ)
13727           return IPred->getRHS();
13728       }
13729     }
13730     return convertToAddRecWithPreds(Expr);
13731   }
13732 
13733   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13734     const SCEV *Operand = visit(Expr->getOperand());
13735     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13736     if (AR && AR->getLoop() == L && AR->isAffine()) {
13737       // This couldn't be folded because the operand didn't have the nuw
13738       // flag. Add the nusw flag as an assumption that we could make.
13739       const SCEV *Step = AR->getStepRecurrence(SE);
13740       Type *Ty = Expr->getType();
13741       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13742         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13743                                 SE.getSignExtendExpr(Step, Ty), L,
13744                                 AR->getNoWrapFlags());
13745     }
13746     return SE.getZeroExtendExpr(Operand, Expr->getType());
13747   }
13748 
13749   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13750     const SCEV *Operand = visit(Expr->getOperand());
13751     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13752     if (AR && AR->getLoop() == L && AR->isAffine()) {
13753       // This couldn't be folded because the operand didn't have the nsw
13754       // flag. Add the nssw flag as an assumption that we could make.
13755       const SCEV *Step = AR->getStepRecurrence(SE);
13756       Type *Ty = Expr->getType();
13757       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13758         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13759                                 SE.getSignExtendExpr(Step, Ty), L,
13760                                 AR->getNoWrapFlags());
13761     }
13762     return SE.getSignExtendExpr(Operand, Expr->getType());
13763   }
13764 
13765 private:
13766   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13767                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13768                         const SCEVPredicate *Pred)
13769       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13770 
13771   bool addOverflowAssumption(const SCEVPredicate *P) {
13772     if (!NewPreds) {
13773       // Check if we've already made this assumption.
13774       return Pred && Pred->implies(P);
13775     }
13776     NewPreds->insert(P);
13777     return true;
13778   }
13779 
13780   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13781                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13782     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13783     return addOverflowAssumption(A);
13784   }
13785 
13786   // If \p Expr represents a PHINode, we try to see if it can be represented
13787   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13788   // to add this predicate as a runtime overflow check, we return the AddRec.
13789   // If \p Expr does not meet these conditions (is not a PHI node, or we
13790   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13791   // return \p Expr.
13792   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13793     if (!isa<PHINode>(Expr->getValue()))
13794       return Expr;
13795     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13796     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13797     if (!PredicatedRewrite)
13798       return Expr;
13799     for (auto *P : PredicatedRewrite->second){
13800       // Wrap predicates from outer loops are not supported.
13801       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13802         if (L != WP->getExpr()->getLoop())
13803           return Expr;
13804       }
13805       if (!addOverflowAssumption(P))
13806         return Expr;
13807     }
13808     return PredicatedRewrite->first;
13809   }
13810 
13811   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13812   const SCEVPredicate *Pred;
13813   const Loop *L;
13814 };
13815 
13816 } // end anonymous namespace
13817 
13818 const SCEV *
13819 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13820                                        const SCEVPredicate &Preds) {
13821   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13822 }
13823 
13824 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13825     const SCEV *S, const Loop *L,
13826     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13827   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13828   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13829   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13830 
13831   if (!AddRec)
13832     return nullptr;
13833 
13834   // Since the transformation was successful, we can now transfer the SCEV
13835   // predicates.
13836   for (auto *P : TransformPreds)
13837     Preds.insert(P);
13838 
13839   return AddRec;
13840 }
13841 
13842 /// SCEV predicates
13843 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13844                              SCEVPredicateKind Kind)
13845     : FastID(ID), Kind(Kind) {}
13846 
13847 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
13848                                    const ICmpInst::Predicate Pred,
13849                                    const SCEV *LHS, const SCEV *RHS)
13850   : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
13851   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13852   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13853 }
13854 
13855 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
13856   const auto *Op = dyn_cast<SCEVComparePredicate>(N);
13857 
13858   if (!Op)
13859     return false;
13860 
13861   if (Pred != ICmpInst::ICMP_EQ)
13862     return false;
13863 
13864   return Op->LHS == LHS && Op->RHS == RHS;
13865 }
13866 
13867 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
13868 
13869 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
13870   if (Pred == ICmpInst::ICMP_EQ)
13871     OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13872   else
13873     OS.indent(Depth) << "Compare predicate: " << *LHS
13874                      << " " << CmpInst::getPredicateName(Pred) << ") "
13875                      << *RHS << "\n";
13876 
13877 }
13878 
13879 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13880                                      const SCEVAddRecExpr *AR,
13881                                      IncrementWrapFlags Flags)
13882     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13883 
13884 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
13885 
13886 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13887   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13888 
13889   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13890 }
13891 
13892 bool SCEVWrapPredicate::isAlwaysTrue() const {
13893   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13894   IncrementWrapFlags IFlags = Flags;
13895 
13896   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13897     IFlags = clearFlags(IFlags, IncrementNSSW);
13898 
13899   return IFlags == IncrementAnyWrap;
13900 }
13901 
13902 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13903   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13904   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13905     OS << "<nusw>";
13906   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13907     OS << "<nssw>";
13908   OS << "\n";
13909 }
13910 
13911 SCEVWrapPredicate::IncrementWrapFlags
13912 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13913                                    ScalarEvolution &SE) {
13914   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13915   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13916 
13917   // We can safely transfer the NSW flag as NSSW.
13918   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13919     ImpliedFlags = IncrementNSSW;
13920 
13921   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13922     // If the increment is positive, the SCEV NUW flag will also imply the
13923     // WrapPredicate NUSW flag.
13924     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13925       if (Step->getValue()->getValue().isNonNegative())
13926         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13927   }
13928 
13929   return ImpliedFlags;
13930 }
13931 
13932 /// Union predicates don't get cached so create a dummy set ID for it.
13933 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
13934   : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
13935   for (auto *P : Preds)
13936     add(P);
13937 }
13938 
13939 bool SCEVUnionPredicate::isAlwaysTrue() const {
13940   return all_of(Preds,
13941                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13942 }
13943 
13944 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13945   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13946     return all_of(Set->Preds,
13947                   [this](const SCEVPredicate *I) { return this->implies(I); });
13948 
13949   return any_of(Preds,
13950                 [N](const SCEVPredicate *I) { return I->implies(N); });
13951 }
13952 
13953 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13954   for (auto Pred : Preds)
13955     Pred->print(OS, Depth);
13956 }
13957 
13958 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13959   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13960     for (auto Pred : Set->Preds)
13961       add(Pred);
13962     return;
13963   }
13964 
13965   Preds.push_back(N);
13966 }
13967 
13968 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13969                                                      Loop &L)
13970     : SE(SE), L(L) {
13971   SmallVector<const SCEVPredicate*, 4> Empty;
13972   Preds = std::make_unique<SCEVUnionPredicate>(Empty);
13973 }
13974 
13975 void ScalarEvolution::registerUser(const SCEV *User,
13976                                    ArrayRef<const SCEV *> Ops) {
13977   for (auto *Op : Ops)
13978     // We do not expect that forgetting cached data for SCEVConstants will ever
13979     // open any prospects for sharpening or introduce any correctness issues,
13980     // so we don't bother storing their dependencies.
13981     if (!isa<SCEVConstant>(Op))
13982       SCEVUsers[Op].insert(User);
13983 }
13984 
13985 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13986   const SCEV *Expr = SE.getSCEV(V);
13987   RewriteEntry &Entry = RewriteMap[Expr];
13988 
13989   // If we already have an entry and the version matches, return it.
13990   if (Entry.second && Generation == Entry.first)
13991     return Entry.second;
13992 
13993   // We found an entry but it's stale. Rewrite the stale entry
13994   // according to the current predicate.
13995   if (Entry.second)
13996     Expr = Entry.second;
13997 
13998   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
13999   Entry = {Generation, NewSCEV};
14000 
14001   return NewSCEV;
14002 }
14003 
14004 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14005   if (!BackedgeCount) {
14006     SmallVector<const SCEVPredicate *, 4> Preds;
14007     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14008     for (auto *P : Preds)
14009       addPredicate(*P);
14010   }
14011   return BackedgeCount;
14012 }
14013 
14014 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14015   if (Preds->implies(&Pred))
14016     return;
14017 
14018   auto &OldPreds = Preds->getPredicates();
14019   SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14020   NewPreds.push_back(&Pred);
14021   Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14022   updateGeneration();
14023 }
14024 
14025 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14026   return *Preds;
14027 }
14028 
14029 void PredicatedScalarEvolution::updateGeneration() {
14030   // If the generation number wrapped recompute everything.
14031   if (++Generation == 0) {
14032     for (auto &II : RewriteMap) {
14033       const SCEV *Rewritten = II.second.second;
14034       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14035     }
14036   }
14037 }
14038 
14039 void PredicatedScalarEvolution::setNoOverflow(
14040     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14041   const SCEV *Expr = getSCEV(V);
14042   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14043 
14044   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14045 
14046   // Clear the statically implied flags.
14047   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14048   addPredicate(*SE.getWrapPredicate(AR, Flags));
14049 
14050   auto II = FlagsMap.insert({V, Flags});
14051   if (!II.second)
14052     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14053 }
14054 
14055 bool PredicatedScalarEvolution::hasNoOverflow(
14056     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14057   const SCEV *Expr = getSCEV(V);
14058   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14059 
14060   Flags = SCEVWrapPredicate::clearFlags(
14061       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14062 
14063   auto II = FlagsMap.find(V);
14064 
14065   if (II != FlagsMap.end())
14066     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14067 
14068   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14069 }
14070 
14071 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14072   const SCEV *Expr = this->getSCEV(V);
14073   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14074   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14075 
14076   if (!New)
14077     return nullptr;
14078 
14079   for (auto *P : NewPreds)
14080     addPredicate(*P);
14081 
14082   RewriteMap[SE.getSCEV(V)] = {Generation, New};
14083   return New;
14084 }
14085 
14086 PredicatedScalarEvolution::PredicatedScalarEvolution(
14087     const PredicatedScalarEvolution &Init)
14088   : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14089     Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14090     Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14091   for (auto I : Init.FlagsMap)
14092     FlagsMap.insert(I);
14093 }
14094 
14095 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14096   // For each block.
14097   for (auto *BB : L.getBlocks())
14098     for (auto &I : *BB) {
14099       if (!SE.isSCEVable(I.getType()))
14100         continue;
14101 
14102       auto *Expr = SE.getSCEV(&I);
14103       auto II = RewriteMap.find(Expr);
14104 
14105       if (II == RewriteMap.end())
14106         continue;
14107 
14108       // Don't print things that are not interesting.
14109       if (II->second.second == Expr)
14110         continue;
14111 
14112       OS.indent(Depth) << "[PSE]" << I << ":\n";
14113       OS.indent(Depth + 2) << *Expr << "\n";
14114       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14115     }
14116 }
14117 
14118 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14119 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14120 // for URem with constant power-of-2 second operands.
14121 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14122 // 4, A / B becomes X / 8).
14123 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14124                                 const SCEV *&RHS) {
14125   // Try to match 'zext (trunc A to iB) to iY', which is used
14126   // for URem with constant power-of-2 second operands. Make sure the size of
14127   // the operand A matches the size of the whole expressions.
14128   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14129     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14130       LHS = Trunc->getOperand();
14131       // Bail out if the type of the LHS is larger than the type of the
14132       // expression for now.
14133       if (getTypeSizeInBits(LHS->getType()) >
14134           getTypeSizeInBits(Expr->getType()))
14135         return false;
14136       if (LHS->getType() != Expr->getType())
14137         LHS = getZeroExtendExpr(LHS, Expr->getType());
14138       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14139                         << getTypeSizeInBits(Trunc->getType()));
14140       return true;
14141     }
14142   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14143   if (Add == nullptr || Add->getNumOperands() != 2)
14144     return false;
14145 
14146   const SCEV *A = Add->getOperand(1);
14147   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14148 
14149   if (Mul == nullptr)
14150     return false;
14151 
14152   const auto MatchURemWithDivisor = [&](const SCEV *B) {
14153     // (SomeExpr + (-(SomeExpr / B) * B)).
14154     if (Expr == getURemExpr(A, B)) {
14155       LHS = A;
14156       RHS = B;
14157       return true;
14158     }
14159     return false;
14160   };
14161 
14162   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14163   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14164     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14165            MatchURemWithDivisor(Mul->getOperand(2));
14166 
14167   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14168   if (Mul->getNumOperands() == 2)
14169     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14170            MatchURemWithDivisor(Mul->getOperand(0)) ||
14171            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14172            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14173   return false;
14174 }
14175 
14176 const SCEV *
14177 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14178   SmallVector<BasicBlock*, 16> ExitingBlocks;
14179   L->getExitingBlocks(ExitingBlocks);
14180 
14181   // Form an expression for the maximum exit count possible for this loop. We
14182   // merge the max and exact information to approximate a version of
14183   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14184   SmallVector<const SCEV*, 4> ExitCounts;
14185   for (BasicBlock *ExitingBB : ExitingBlocks) {
14186     const SCEV *ExitCount = getExitCount(L, ExitingBB);
14187     if (isa<SCEVCouldNotCompute>(ExitCount))
14188       ExitCount = getExitCount(L, ExitingBB,
14189                                   ScalarEvolution::ConstantMaximum);
14190     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14191       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14192              "We should only have known counts for exiting blocks that "
14193              "dominate latch!");
14194       ExitCounts.push_back(ExitCount);
14195     }
14196   }
14197   if (ExitCounts.empty())
14198     return getCouldNotCompute();
14199   return getUMinFromMismatchedTypes(ExitCounts);
14200 }
14201 
14202 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14203 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14204 /// replacement is loop invariant in the loop of the AddRec.
14205 ///
14206 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
14207 /// supported.
14208 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14209   const DenseMap<const SCEV *, const SCEV *> &Map;
14210 
14211 public:
14212   SCEVLoopGuardRewriter(ScalarEvolution &SE,
14213                         DenseMap<const SCEV *, const SCEV *> &M)
14214       : SCEVRewriteVisitor(SE), Map(M) {}
14215 
14216   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14217 
14218   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14219     auto I = Map.find(Expr);
14220     if (I == Map.end())
14221       return Expr;
14222     return I->second;
14223   }
14224 
14225   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14226     auto I = Map.find(Expr);
14227     if (I == Map.end())
14228       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14229           Expr);
14230     return I->second;
14231   }
14232 };
14233 
14234 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14235   SmallVector<const SCEV *> ExprsToRewrite;
14236   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14237                               const SCEV *RHS,
14238                               DenseMap<const SCEV *, const SCEV *>
14239                                   &RewriteMap) {
14240     // WARNING: It is generally unsound to apply any wrap flags to the proposed
14241     // replacement SCEV which isn't directly implied by the structure of that
14242     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
14243     // legal.  See the scoping rules for flags in the header to understand why.
14244 
14245     // If LHS is a constant, apply information to the other expression.
14246     if (isa<SCEVConstant>(LHS)) {
14247       std::swap(LHS, RHS);
14248       Predicate = CmpInst::getSwappedPredicate(Predicate);
14249     }
14250 
14251     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
14252     // create this form when combining two checks of the form (X u< C2 + C1) and
14253     // (X >=u C1).
14254     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14255                                  &ExprsToRewrite]() {
14256       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14257       if (!AddExpr || AddExpr->getNumOperands() != 2)
14258         return false;
14259 
14260       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14261       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14262       auto *C2 = dyn_cast<SCEVConstant>(RHS);
14263       if (!C1 || !C2 || !LHSUnknown)
14264         return false;
14265 
14266       auto ExactRegion =
14267           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14268               .sub(C1->getAPInt());
14269 
14270       // Bail out, unless we have a non-wrapping, monotonic range.
14271       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14272         return false;
14273       auto I = RewriteMap.find(LHSUnknown);
14274       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14275       RewriteMap[LHSUnknown] = getUMaxExpr(
14276           getConstant(ExactRegion.getUnsignedMin()),
14277           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14278       ExprsToRewrite.push_back(LHSUnknown);
14279       return true;
14280     };
14281     if (MatchRangeCheckIdiom())
14282       return;
14283 
14284     // If we have LHS == 0, check if LHS is computing a property of some unknown
14285     // SCEV %v which we can rewrite %v to express explicitly.
14286     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
14287     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
14288         RHSC->getValue()->isNullValue()) {
14289       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
14290       // explicitly express that.
14291       const SCEV *URemLHS = nullptr;
14292       const SCEV *URemRHS = nullptr;
14293       if (matchURem(LHS, URemLHS, URemRHS)) {
14294         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
14295           auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
14296           RewriteMap[LHSUnknown] = Multiple;
14297           ExprsToRewrite.push_back(LHSUnknown);
14298           return;
14299         }
14300       }
14301     }
14302 
14303     // Do not apply information for constants or if RHS contains an AddRec.
14304     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
14305       return;
14306 
14307     // If RHS is SCEVUnknown, make sure the information is applied to it.
14308     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
14309       std::swap(LHS, RHS);
14310       Predicate = CmpInst::getSwappedPredicate(Predicate);
14311     }
14312 
14313     // Limit to expressions that can be rewritten.
14314     if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
14315       return;
14316 
14317     // Check whether LHS has already been rewritten. In that case we want to
14318     // chain further rewrites onto the already rewritten value.
14319     auto I = RewriteMap.find(LHS);
14320     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
14321 
14322     const SCEV *RewrittenRHS = nullptr;
14323     switch (Predicate) {
14324     case CmpInst::ICMP_ULT:
14325       RewrittenRHS =
14326           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14327       break;
14328     case CmpInst::ICMP_SLT:
14329       RewrittenRHS =
14330           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14331       break;
14332     case CmpInst::ICMP_ULE:
14333       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
14334       break;
14335     case CmpInst::ICMP_SLE:
14336       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
14337       break;
14338     case CmpInst::ICMP_UGT:
14339       RewrittenRHS =
14340           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14341       break;
14342     case CmpInst::ICMP_SGT:
14343       RewrittenRHS =
14344           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14345       break;
14346     case CmpInst::ICMP_UGE:
14347       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
14348       break;
14349     case CmpInst::ICMP_SGE:
14350       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
14351       break;
14352     case CmpInst::ICMP_EQ:
14353       if (isa<SCEVConstant>(RHS))
14354         RewrittenRHS = RHS;
14355       break;
14356     case CmpInst::ICMP_NE:
14357       if (isa<SCEVConstant>(RHS) &&
14358           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
14359         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
14360       break;
14361     default:
14362       break;
14363     }
14364 
14365     if (RewrittenRHS) {
14366       RewriteMap[LHS] = RewrittenRHS;
14367       if (LHS == RewrittenLHS)
14368         ExprsToRewrite.push_back(LHS);
14369     }
14370   };
14371   // First, collect conditions from dominating branches. Starting at the loop
14372   // predecessor, climb up the predecessor chain, as long as there are
14373   // predecessors that can be found that have unique successors leading to the
14374   // original header.
14375   // TODO: share this logic with isLoopEntryGuardedByCond.
14376   SmallVector<std::pair<Value *, bool>> Terms;
14377   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
14378            L->getLoopPredecessor(), L->getHeader());
14379        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
14380 
14381     const BranchInst *LoopEntryPredicate =
14382         dyn_cast<BranchInst>(Pair.first->getTerminator());
14383     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
14384       continue;
14385 
14386     Terms.emplace_back(LoopEntryPredicate->getCondition(),
14387                        LoopEntryPredicate->getSuccessor(0) == Pair.second);
14388   }
14389 
14390   // Now apply the information from the collected conditions to RewriteMap.
14391   // Conditions are processed in reverse order, so the earliest conditions is
14392   // processed first. This ensures the SCEVs with the shortest dependency chains
14393   // are constructed first.
14394   DenseMap<const SCEV *, const SCEV *> RewriteMap;
14395   for (auto &E : reverse(Terms)) {
14396     bool EnterIfTrue = E.second;
14397     SmallVector<Value *, 8> Worklist;
14398     SmallPtrSet<Value *, 8> Visited;
14399     Worklist.push_back(E.first);
14400     while (!Worklist.empty()) {
14401       Value *Cond = Worklist.pop_back_val();
14402       if (!Visited.insert(Cond).second)
14403         continue;
14404 
14405       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14406         auto Predicate =
14407             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
14408         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
14409                          getSCEV(Cmp->getOperand(1)), RewriteMap);
14410         continue;
14411       }
14412 
14413       Value *L, *R;
14414       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
14415                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
14416         Worklist.push_back(L);
14417         Worklist.push_back(R);
14418       }
14419     }
14420   }
14421 
14422   // Also collect information from assumptions dominating the loop.
14423   for (auto &AssumeVH : AC.assumptions()) {
14424     if (!AssumeVH)
14425       continue;
14426     auto *AssumeI = cast<CallInst>(AssumeVH);
14427     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
14428     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
14429       continue;
14430     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
14431                      getSCEV(Cmp->getOperand(1)), RewriteMap);
14432   }
14433 
14434   if (RewriteMap.empty())
14435     return Expr;
14436 
14437   // Now that all rewrite information is collect, rewrite the collected
14438   // expressions with the information in the map. This applies information to
14439   // sub-expressions.
14440   if (ExprsToRewrite.size() > 1) {
14441     for (const SCEV *Expr : ExprsToRewrite) {
14442       const SCEV *RewriteTo = RewriteMap[Expr];
14443       RewriteMap.erase(Expr);
14444       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14445       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
14446     }
14447   }
14448 
14449   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14450   return Rewriter.visit(Expr);
14451 }
14452