xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision a3113df21994fafd87d623e13364321659f4585c)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionDivision.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/InitializePasses.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/KnownBits.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <climits>
128 #include <cstddef>
129 #include <cstdint>
130 #include <cstdlib>
131 #include <map>
132 #include <memory>
133 #include <tuple>
134 #include <utility>
135 #include <vector>
136 
137 using namespace llvm;
138 using namespace PatternMatch;
139 
140 #define DEBUG_TYPE "scalar-evolution"
141 
142 STATISTIC(NumArrayLenItCounts,
143           "Number of trip counts computed with array length");
144 STATISTIC(NumTripCountsComputed,
145           "Number of loops with predictable loop counts");
146 STATISTIC(NumTripCountsNotComputed,
147           "Number of loops without predictable loop counts");
148 STATISTIC(NumBruteForceTripCountsComputed,
149           "Number of loops with trip counts computed by force");
150 
151 static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153                         cl::ZeroOrMore,
154                         cl::desc("Maximum number of iterations SCEV will "
155                                  "symbolically execute a constant "
156                                  "derived loop"),
157                         cl::init(100));
158 
159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
160 static cl::opt<bool> VerifySCEV(
161     "verify-scev", cl::Hidden,
162     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 static cl::opt<bool> VerifySCEVStrict(
164     "verify-scev-strict", cl::Hidden,
165     cl::desc("Enable stricter verification with -verify-scev is passed"));
166 static cl::opt<bool>
167     VerifySCEVMap("verify-scev-maps", cl::Hidden,
168                   cl::desc("Verify no dangling value in ScalarEvolution's "
169                            "ExprValueMap (slow)"));
170 
171 static cl::opt<bool> VerifyIR(
172     "scev-verify-ir", cl::Hidden,
173     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
174     cl::init(false));
175 
176 static cl::opt<unsigned> MulOpsInlineThreshold(
177     "scev-mulops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
179     cl::init(32));
180 
181 static cl::opt<unsigned> AddOpsInlineThreshold(
182     "scev-addops-inline-threshold", cl::Hidden,
183     cl::desc("Threshold for inlining addition operands into a SCEV"),
184     cl::init(500));
185 
186 static cl::opt<unsigned> MaxSCEVCompareDepth(
187     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
189     cl::init(32));
190 
191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
192     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
194     cl::init(2));
195 
196 static cl::opt<unsigned> MaxValueCompareDepth(
197     "scalar-evolution-max-value-compare-depth", cl::Hidden,
198     cl::desc("Maximum depth of recursive value complexity comparisons"),
199     cl::init(2));
200 
201 static cl::opt<unsigned>
202     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
203                   cl::desc("Maximum depth of recursive arithmetics"),
204                   cl::init(32));
205 
206 static cl::opt<unsigned> MaxConstantEvolvingDepth(
207     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
208     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
209 
210 static cl::opt<unsigned>
211     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
212                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
213                  cl::init(8));
214 
215 static cl::opt<unsigned>
216     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
217                   cl::desc("Max coefficients in AddRec during evolving"),
218                   cl::init(8));
219 
220 static cl::opt<unsigned>
221     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
222                   cl::desc("Size of the expression which is considered huge"),
223                   cl::init(4096));
224 
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227     cl::Hidden, cl::init(true),
228     cl::desc("When printing analysis, include information on every instruction"));
229 
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232     cl::init(false),
233     cl::desc("Use more powerful methods of sharpening expression ranges. May "
234              "be costly in terms of compile time"));
235 
236 //===----------------------------------------------------------------------===//
237 //                           SCEV class definitions
238 //===----------------------------------------------------------------------===//
239 
240 //===----------------------------------------------------------------------===//
241 // Implementation of the SCEV class.
242 //
243 
244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
245 LLVM_DUMP_METHOD void SCEV::dump() const {
246   print(dbgs());
247   dbgs() << '\n';
248 }
249 #endif
250 
251 void SCEV::print(raw_ostream &OS) const {
252   switch (getSCEVType()) {
253   case scConstant:
254     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
255     return;
256   case scPtrToInt: {
257     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
258     const SCEV *Op = PtrToInt->getOperand();
259     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
260        << *PtrToInt->getType() << ")";
261     return;
262   }
263   case scTruncate: {
264     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
265     const SCEV *Op = Trunc->getOperand();
266     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
267        << *Trunc->getType() << ")";
268     return;
269   }
270   case scZeroExtend: {
271     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
272     const SCEV *Op = ZExt->getOperand();
273     OS << "(zext " << *Op->getType() << " " << *Op << " to "
274        << *ZExt->getType() << ")";
275     return;
276   }
277   case scSignExtend: {
278     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
279     const SCEV *Op = SExt->getOperand();
280     OS << "(sext " << *Op->getType() << " " << *Op << " to "
281        << *SExt->getType() << ")";
282     return;
283   }
284   case scAddRecExpr: {
285     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
286     OS << "{" << *AR->getOperand(0);
287     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
288       OS << ",+," << *AR->getOperand(i);
289     OS << "}<";
290     if (AR->hasNoUnsignedWrap())
291       OS << "nuw><";
292     if (AR->hasNoSignedWrap())
293       OS << "nsw><";
294     if (AR->hasNoSelfWrap() &&
295         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
296       OS << "nw><";
297     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
298     OS << ">";
299     return;
300   }
301   case scAddExpr:
302   case scMulExpr:
303   case scUMaxExpr:
304   case scSMaxExpr:
305   case scUMinExpr:
306   case scSMinExpr: {
307     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
308     const char *OpStr = nullptr;
309     switch (NAry->getSCEVType()) {
310     case scAddExpr: OpStr = " + "; break;
311     case scMulExpr: OpStr = " * "; break;
312     case scUMaxExpr: OpStr = " umax "; break;
313     case scSMaxExpr: OpStr = " smax "; break;
314     case scUMinExpr:
315       OpStr = " umin ";
316       break;
317     case scSMinExpr:
318       OpStr = " smin ";
319       break;
320     default:
321       llvm_unreachable("There are no other nary expression types.");
322     }
323     OS << "(";
324     ListSeparator LS(OpStr);
325     for (const SCEV *Op : NAry->operands())
326       OS << LS << *Op;
327     OS << ")";
328     switch (NAry->getSCEVType()) {
329     case scAddExpr:
330     case scMulExpr:
331       if (NAry->hasNoUnsignedWrap())
332         OS << "<nuw>";
333       if (NAry->hasNoSignedWrap())
334         OS << "<nsw>";
335       break;
336     default:
337       // Nothing to print for other nary expressions.
338       break;
339     }
340     return;
341   }
342   case scUDivExpr: {
343     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
344     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
345     return;
346   }
347   case scUnknown: {
348     const SCEVUnknown *U = cast<SCEVUnknown>(this);
349     Type *AllocTy;
350     if (U->isSizeOf(AllocTy)) {
351       OS << "sizeof(" << *AllocTy << ")";
352       return;
353     }
354     if (U->isAlignOf(AllocTy)) {
355       OS << "alignof(" << *AllocTy << ")";
356       return;
357     }
358 
359     Type *CTy;
360     Constant *FieldNo;
361     if (U->isOffsetOf(CTy, FieldNo)) {
362       OS << "offsetof(" << *CTy << ", ";
363       FieldNo->printAsOperand(OS, false);
364       OS << ")";
365       return;
366     }
367 
368     // Otherwise just print it normally.
369     U->getValue()->printAsOperand(OS, false);
370     return;
371   }
372   case scCouldNotCompute:
373     OS << "***COULDNOTCOMPUTE***";
374     return;
375   }
376   llvm_unreachable("Unknown SCEV kind!");
377 }
378 
379 Type *SCEV::getType() const {
380   switch (getSCEVType()) {
381   case scConstant:
382     return cast<SCEVConstant>(this)->getType();
383   case scPtrToInt:
384   case scTruncate:
385   case scZeroExtend:
386   case scSignExtend:
387     return cast<SCEVCastExpr>(this)->getType();
388   case scAddRecExpr:
389   case scMulExpr:
390   case scUMaxExpr:
391   case scSMaxExpr:
392   case scUMinExpr:
393   case scSMinExpr:
394     return cast<SCEVNAryExpr>(this)->getType();
395   case scAddExpr:
396     return cast<SCEVAddExpr>(this)->getType();
397   case scUDivExpr:
398     return cast<SCEVUDivExpr>(this)->getType();
399   case scUnknown:
400     return cast<SCEVUnknown>(this)->getType();
401   case scCouldNotCompute:
402     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
403   }
404   llvm_unreachable("Unknown SCEV kind!");
405 }
406 
407 bool SCEV::isZero() const {
408   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
409     return SC->getValue()->isZero();
410   return false;
411 }
412 
413 bool SCEV::isOne() const {
414   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
415     return SC->getValue()->isOne();
416   return false;
417 }
418 
419 bool SCEV::isAllOnesValue() const {
420   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
421     return SC->getValue()->isMinusOne();
422   return false;
423 }
424 
425 bool SCEV::isNonConstantNegative() const {
426   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
427   if (!Mul) return false;
428 
429   // If there is a constant factor, it will be first.
430   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
431   if (!SC) return false;
432 
433   // Return true if the value is negative, this matches things like (-42 * V).
434   return SC->getAPInt().isNegative();
435 }
436 
437 SCEVCouldNotCompute::SCEVCouldNotCompute() :
438   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
439 
440 bool SCEVCouldNotCompute::classof(const SCEV *S) {
441   return S->getSCEVType() == scCouldNotCompute;
442 }
443 
444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
445   FoldingSetNodeID ID;
446   ID.AddInteger(scConstant);
447   ID.AddPointer(V);
448   void *IP = nullptr;
449   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
450   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
451   UniqueSCEVs.InsertNode(S, IP);
452   return S;
453 }
454 
455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
456   return getConstant(ConstantInt::get(getContext(), Val));
457 }
458 
459 const SCEV *
460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
461   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
462   return getConstant(ConstantInt::get(ITy, V, isSigned));
463 }
464 
465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
466                            const SCEV *op, Type *ty)
467     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
468   Operands[0] = op;
469 }
470 
471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
472                                    Type *ITy)
473     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
474   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
475          "Must be a non-bit-width-changing pointer-to-integer cast!");
476 }
477 
478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
479                                            SCEVTypes SCEVTy, const SCEV *op,
480                                            Type *ty)
481     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
482 
483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
484                                    Type *ty)
485     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
486   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
487          "Cannot truncate non-integer value!");
488 }
489 
490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
491                                        const SCEV *op, Type *ty)
492     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
493   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
494          "Cannot zero extend non-integer value!");
495 }
496 
497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
498                                        const SCEV *op, Type *ty)
499     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
500   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
501          "Cannot sign extend non-integer value!");
502 }
503 
504 void SCEVUnknown::deleted() {
505   // Clear this SCEVUnknown from various maps.
506   SE->forgetMemoizedResults(this);
507 
508   // Remove this SCEVUnknown from the uniquing map.
509   SE->UniqueSCEVs.RemoveNode(this);
510 
511   // Release the value.
512   setValPtr(nullptr);
513 }
514 
515 void SCEVUnknown::allUsesReplacedWith(Value *New) {
516   // Remove this SCEVUnknown from the uniquing map.
517   SE->UniqueSCEVs.RemoveNode(this);
518 
519   // Update this SCEVUnknown to point to the new value. This is needed
520   // because there may still be outstanding SCEVs which still point to
521   // this SCEVUnknown.
522   setValPtr(New);
523 }
524 
525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
526   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
527     if (VCE->getOpcode() == Instruction::PtrToInt)
528       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
529         if (CE->getOpcode() == Instruction::GetElementPtr &&
530             CE->getOperand(0)->isNullValue() &&
531             CE->getNumOperands() == 2)
532           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
533             if (CI->isOne()) {
534               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
535                                  ->getElementType();
536               return true;
537             }
538 
539   return false;
540 }
541 
542 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
543   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
544     if (VCE->getOpcode() == Instruction::PtrToInt)
545       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
546         if (CE->getOpcode() == Instruction::GetElementPtr &&
547             CE->getOperand(0)->isNullValue()) {
548           Type *Ty =
549             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
550           if (StructType *STy = dyn_cast<StructType>(Ty))
551             if (!STy->isPacked() &&
552                 CE->getNumOperands() == 3 &&
553                 CE->getOperand(1)->isNullValue()) {
554               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
555                 if (CI->isOne() &&
556                     STy->getNumElements() == 2 &&
557                     STy->getElementType(0)->isIntegerTy(1)) {
558                   AllocTy = STy->getElementType(1);
559                   return true;
560                 }
561             }
562         }
563 
564   return false;
565 }
566 
567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
568   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
569     if (VCE->getOpcode() == Instruction::PtrToInt)
570       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
571         if (CE->getOpcode() == Instruction::GetElementPtr &&
572             CE->getNumOperands() == 3 &&
573             CE->getOperand(0)->isNullValue() &&
574             CE->getOperand(1)->isNullValue()) {
575           Type *Ty =
576             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
577           // Ignore vector types here so that ScalarEvolutionExpander doesn't
578           // emit getelementptrs that index into vectors.
579           if (Ty->isStructTy() || Ty->isArrayTy()) {
580             CTy = Ty;
581             FieldNo = CE->getOperand(2);
582             return true;
583           }
584         }
585 
586   return false;
587 }
588 
589 //===----------------------------------------------------------------------===//
590 //                               SCEV Utilities
591 //===----------------------------------------------------------------------===//
592 
593 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
594 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
595 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
596 /// have been previously deemed to be "equally complex" by this routine.  It is
597 /// intended to avoid exponential time complexity in cases like:
598 ///
599 ///   %a = f(%x, %y)
600 ///   %b = f(%a, %a)
601 ///   %c = f(%b, %b)
602 ///
603 ///   %d = f(%x, %y)
604 ///   %e = f(%d, %d)
605 ///   %f = f(%e, %e)
606 ///
607 ///   CompareValueComplexity(%f, %c)
608 ///
609 /// Since we do not continue running this routine on expression trees once we
610 /// have seen unequal values, there is no need to track them in the cache.
611 static int
612 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
613                        const LoopInfo *const LI, Value *LV, Value *RV,
614                        unsigned Depth) {
615   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
616     return 0;
617 
618   // Order pointer values after integer values. This helps SCEVExpander form
619   // GEPs.
620   bool LIsPointer = LV->getType()->isPointerTy(),
621        RIsPointer = RV->getType()->isPointerTy();
622   if (LIsPointer != RIsPointer)
623     return (int)LIsPointer - (int)RIsPointer;
624 
625   // Compare getValueID values.
626   unsigned LID = LV->getValueID(), RID = RV->getValueID();
627   if (LID != RID)
628     return (int)LID - (int)RID;
629 
630   // Sort arguments by their position.
631   if (const auto *LA = dyn_cast<Argument>(LV)) {
632     const auto *RA = cast<Argument>(RV);
633     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
634     return (int)LArgNo - (int)RArgNo;
635   }
636 
637   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
638     const auto *RGV = cast<GlobalValue>(RV);
639 
640     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
641       auto LT = GV->getLinkage();
642       return !(GlobalValue::isPrivateLinkage(LT) ||
643                GlobalValue::isInternalLinkage(LT));
644     };
645 
646     // Use the names to distinguish the two values, but only if the
647     // names are semantically important.
648     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
649       return LGV->getName().compare(RGV->getName());
650   }
651 
652   // For instructions, compare their loop depth, and their operand count.  This
653   // is pretty loose.
654   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
655     const auto *RInst = cast<Instruction>(RV);
656 
657     // Compare loop depths.
658     const BasicBlock *LParent = LInst->getParent(),
659                      *RParent = RInst->getParent();
660     if (LParent != RParent) {
661       unsigned LDepth = LI->getLoopDepth(LParent),
662                RDepth = LI->getLoopDepth(RParent);
663       if (LDepth != RDepth)
664         return (int)LDepth - (int)RDepth;
665     }
666 
667     // Compare the number of operands.
668     unsigned LNumOps = LInst->getNumOperands(),
669              RNumOps = RInst->getNumOperands();
670     if (LNumOps != RNumOps)
671       return (int)LNumOps - (int)RNumOps;
672 
673     for (unsigned Idx : seq(0u, LNumOps)) {
674       int Result =
675           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
676                                  RInst->getOperand(Idx), Depth + 1);
677       if (Result != 0)
678         return Result;
679     }
680   }
681 
682   EqCacheValue.unionSets(LV, RV);
683   return 0;
684 }
685 
686 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
687 // than RHS, respectively. A three-way result allows recursive comparisons to be
688 // more efficient.
689 // If the max analysis depth was reached, return None, assuming we do not know
690 // if they are equivalent for sure.
691 static Optional<int>
692 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
693                       EquivalenceClasses<const Value *> &EqCacheValue,
694                       const LoopInfo *const LI, const SCEV *LHS,
695                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
696   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
697   if (LHS == RHS)
698     return 0;
699 
700   // Primarily, sort the SCEVs by their getSCEVType().
701   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
702   if (LType != RType)
703     return (int)LType - (int)RType;
704 
705   if (EqCacheSCEV.isEquivalent(LHS, RHS))
706     return 0;
707 
708   if (Depth > MaxSCEVCompareDepth)
709     return None;
710 
711   // Aside from the getSCEVType() ordering, the particular ordering
712   // isn't very important except that it's beneficial to be consistent,
713   // so that (a + b) and (b + a) don't end up as different expressions.
714   switch (LType) {
715   case scUnknown: {
716     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
717     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
718 
719     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
720                                    RU->getValue(), Depth + 1);
721     if (X == 0)
722       EqCacheSCEV.unionSets(LHS, RHS);
723     return X;
724   }
725 
726   case scConstant: {
727     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
728     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
729 
730     // Compare constant values.
731     const APInt &LA = LC->getAPInt();
732     const APInt &RA = RC->getAPInt();
733     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
734     if (LBitWidth != RBitWidth)
735       return (int)LBitWidth - (int)RBitWidth;
736     return LA.ult(RA) ? -1 : 1;
737   }
738 
739   case scAddRecExpr: {
740     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
741     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
742 
743     // There is always a dominance between two recs that are used by one SCEV,
744     // so we can safely sort recs by loop header dominance. We require such
745     // order in getAddExpr.
746     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
747     if (LLoop != RLoop) {
748       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
749       assert(LHead != RHead && "Two loops share the same header?");
750       if (DT.dominates(LHead, RHead))
751         return 1;
752       else
753         assert(DT.dominates(RHead, LHead) &&
754                "No dominance between recurrences used by one SCEV?");
755       return -1;
756     }
757 
758     // Addrec complexity grows with operand count.
759     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
760     if (LNumOps != RNumOps)
761       return (int)LNumOps - (int)RNumOps;
762 
763     // Lexicographically compare.
764     for (unsigned i = 0; i != LNumOps; ++i) {
765       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
766                                      LA->getOperand(i), RA->getOperand(i), DT,
767                                      Depth + 1);
768       if (X != 0)
769         return X;
770     }
771     EqCacheSCEV.unionSets(LHS, RHS);
772     return 0;
773   }
774 
775   case scAddExpr:
776   case scMulExpr:
777   case scSMaxExpr:
778   case scUMaxExpr:
779   case scSMinExpr:
780   case scUMinExpr: {
781     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
782     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
783 
784     // Lexicographically compare n-ary expressions.
785     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
786     if (LNumOps != RNumOps)
787       return (int)LNumOps - (int)RNumOps;
788 
789     for (unsigned i = 0; i != LNumOps; ++i) {
790       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
791                                      LC->getOperand(i), RC->getOperand(i), DT,
792                                      Depth + 1);
793       if (X != 0)
794         return X;
795     }
796     EqCacheSCEV.unionSets(LHS, RHS);
797     return 0;
798   }
799 
800   case scUDivExpr: {
801     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
802     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
803 
804     // Lexicographically compare udiv expressions.
805     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
806                                    RC->getLHS(), DT, Depth + 1);
807     if (X != 0)
808       return X;
809     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
810                               RC->getRHS(), DT, Depth + 1);
811     if (X == 0)
812       EqCacheSCEV.unionSets(LHS, RHS);
813     return X;
814   }
815 
816   case scPtrToInt:
817   case scTruncate:
818   case scZeroExtend:
819   case scSignExtend: {
820     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
821     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
822 
823     // Compare cast expressions by operand.
824     auto X =
825         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
826                               RC->getOperand(), DT, Depth + 1);
827     if (X == 0)
828       EqCacheSCEV.unionSets(LHS, RHS);
829     return X;
830   }
831 
832   case scCouldNotCompute:
833     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
834   }
835   llvm_unreachable("Unknown SCEV kind!");
836 }
837 
838 /// Given a list of SCEV objects, order them by their complexity, and group
839 /// objects of the same complexity together by value.  When this routine is
840 /// finished, we know that any duplicates in the vector are consecutive and that
841 /// complexity is monotonically increasing.
842 ///
843 /// Note that we go take special precautions to ensure that we get deterministic
844 /// results from this routine.  In other words, we don't want the results of
845 /// this to depend on where the addresses of various SCEV objects happened to
846 /// land in memory.
847 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
848                               LoopInfo *LI, DominatorTree &DT) {
849   if (Ops.size() < 2) return;  // Noop
850 
851   EquivalenceClasses<const SCEV *> EqCacheSCEV;
852   EquivalenceClasses<const Value *> EqCacheValue;
853 
854   // Whether LHS has provably less complexity than RHS.
855   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
856     auto Complexity =
857         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
858     return Complexity && *Complexity < 0;
859   };
860   if (Ops.size() == 2) {
861     // This is the common case, which also happens to be trivially simple.
862     // Special case it.
863     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
864     if (IsLessComplex(RHS, LHS))
865       std::swap(LHS, RHS);
866     return;
867   }
868 
869   // Do the rough sort by complexity.
870   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
871     return IsLessComplex(LHS, RHS);
872   });
873 
874   // Now that we are sorted by complexity, group elements of the same
875   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
876   // be extremely short in practice.  Note that we take this approach because we
877   // do not want to depend on the addresses of the objects we are grouping.
878   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
879     const SCEV *S = Ops[i];
880     unsigned Complexity = S->getSCEVType();
881 
882     // If there are any objects of the same complexity and same value as this
883     // one, group them.
884     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
885       if (Ops[j] == S) { // Found a duplicate.
886         // Move it to immediately after i'th element.
887         std::swap(Ops[i+1], Ops[j]);
888         ++i;   // no need to rescan it.
889         if (i == e-2) return;  // Done!
890       }
891     }
892   }
893 }
894 
895 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
896 /// least HugeExprThreshold nodes).
897 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
898   return any_of(Ops, [](const SCEV *S) {
899     return S->getExpressionSize() >= HugeExprThreshold;
900   });
901 }
902 
903 //===----------------------------------------------------------------------===//
904 //                      Simple SCEV method implementations
905 //===----------------------------------------------------------------------===//
906 
907 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
908 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
909                                        ScalarEvolution &SE,
910                                        Type *ResultTy) {
911   // Handle the simplest case efficiently.
912   if (K == 1)
913     return SE.getTruncateOrZeroExtend(It, ResultTy);
914 
915   // We are using the following formula for BC(It, K):
916   //
917   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
918   //
919   // Suppose, W is the bitwidth of the return value.  We must be prepared for
920   // overflow.  Hence, we must assure that the result of our computation is
921   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
922   // safe in modular arithmetic.
923   //
924   // However, this code doesn't use exactly that formula; the formula it uses
925   // is something like the following, where T is the number of factors of 2 in
926   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
927   // exponentiation:
928   //
929   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
930   //
931   // This formula is trivially equivalent to the previous formula.  However,
932   // this formula can be implemented much more efficiently.  The trick is that
933   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
934   // arithmetic.  To do exact division in modular arithmetic, all we have
935   // to do is multiply by the inverse.  Therefore, this step can be done at
936   // width W.
937   //
938   // The next issue is how to safely do the division by 2^T.  The way this
939   // is done is by doing the multiplication step at a width of at least W + T
940   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
941   // when we perform the division by 2^T (which is equivalent to a right shift
942   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
943   // truncated out after the division by 2^T.
944   //
945   // In comparison to just directly using the first formula, this technique
946   // is much more efficient; using the first formula requires W * K bits,
947   // but this formula less than W + K bits. Also, the first formula requires
948   // a division step, whereas this formula only requires multiplies and shifts.
949   //
950   // It doesn't matter whether the subtraction step is done in the calculation
951   // width or the input iteration count's width; if the subtraction overflows,
952   // the result must be zero anyway.  We prefer here to do it in the width of
953   // the induction variable because it helps a lot for certain cases; CodeGen
954   // isn't smart enough to ignore the overflow, which leads to much less
955   // efficient code if the width of the subtraction is wider than the native
956   // register width.
957   //
958   // (It's possible to not widen at all by pulling out factors of 2 before
959   // the multiplication; for example, K=2 can be calculated as
960   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
961   // extra arithmetic, so it's not an obvious win, and it gets
962   // much more complicated for K > 3.)
963 
964   // Protection from insane SCEVs; this bound is conservative,
965   // but it probably doesn't matter.
966   if (K > 1000)
967     return SE.getCouldNotCompute();
968 
969   unsigned W = SE.getTypeSizeInBits(ResultTy);
970 
971   // Calculate K! / 2^T and T; we divide out the factors of two before
972   // multiplying for calculating K! / 2^T to avoid overflow.
973   // Other overflow doesn't matter because we only care about the bottom
974   // W bits of the result.
975   APInt OddFactorial(W, 1);
976   unsigned T = 1;
977   for (unsigned i = 3; i <= K; ++i) {
978     APInt Mult(W, i);
979     unsigned TwoFactors = Mult.countTrailingZeros();
980     T += TwoFactors;
981     Mult.lshrInPlace(TwoFactors);
982     OddFactorial *= Mult;
983   }
984 
985   // We need at least W + T bits for the multiplication step
986   unsigned CalculationBits = W + T;
987 
988   // Calculate 2^T, at width T+W.
989   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
990 
991   // Calculate the multiplicative inverse of K! / 2^T;
992   // this multiplication factor will perform the exact division by
993   // K! / 2^T.
994   APInt Mod = APInt::getSignedMinValue(W+1);
995   APInt MultiplyFactor = OddFactorial.zext(W+1);
996   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
997   MultiplyFactor = MultiplyFactor.trunc(W);
998 
999   // Calculate the product, at width T+W
1000   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1001                                                       CalculationBits);
1002   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1003   for (unsigned i = 1; i != K; ++i) {
1004     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1005     Dividend = SE.getMulExpr(Dividend,
1006                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1007   }
1008 
1009   // Divide by 2^T
1010   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1011 
1012   // Truncate the result, and divide by K! / 2^T.
1013 
1014   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1015                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1016 }
1017 
1018 /// Return the value of this chain of recurrences at the specified iteration
1019 /// number.  We can evaluate this recurrence by multiplying each element in the
1020 /// chain by the binomial coefficient corresponding to it.  In other words, we
1021 /// can evaluate {A,+,B,+,C,+,D} as:
1022 ///
1023 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1024 ///
1025 /// where BC(It, k) stands for binomial coefficient.
1026 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1027                                                 ScalarEvolution &SE) const {
1028   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1029 }
1030 
1031 const SCEV *
1032 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1033                                     const SCEV *It, ScalarEvolution &SE) {
1034   assert(Operands.size() > 0);
1035   const SCEV *Result = Operands[0];
1036   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1037     // The computation is correct in the face of overflow provided that the
1038     // multiplication is performed _after_ the evaluation of the binomial
1039     // coefficient.
1040     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1041     if (isa<SCEVCouldNotCompute>(Coeff))
1042       return Coeff;
1043 
1044     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1045   }
1046   return Result;
1047 }
1048 
1049 //===----------------------------------------------------------------------===//
1050 //                    SCEV Expression folder implementations
1051 //===----------------------------------------------------------------------===//
1052 
1053 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1054                                                      unsigned Depth) {
1055   assert(Depth <= 1 &&
1056          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1057 
1058   // We could be called with an integer-typed operands during SCEV rewrites.
1059   // Since the operand is an integer already, just perform zext/trunc/self cast.
1060   if (!Op->getType()->isPointerTy())
1061     return Op;
1062 
1063   // What would be an ID for such a SCEV cast expression?
1064   FoldingSetNodeID ID;
1065   ID.AddInteger(scPtrToInt);
1066   ID.AddPointer(Op);
1067 
1068   void *IP = nullptr;
1069 
1070   // Is there already an expression for such a cast?
1071   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1072     return S;
1073 
1074   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1075 
1076   // We can only model ptrtoint if SCEV's effective (integer) type
1077   // is sufficiently wide to represent all possible pointer values.
1078   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1079       getDataLayout().getTypeSizeInBits(IntPtrTy))
1080     return getCouldNotCompute();
1081 
1082   // If not, is this expression something we can't reduce any further?
1083   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1084     // Perform some basic constant folding. If the operand of the ptr2int cast
1085     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1086     // left as-is), but produce a zero constant.
1087     // NOTE: We could handle a more general case, but lack motivational cases.
1088     if (isa<ConstantPointerNull>(U->getValue()))
1089       return getZero(IntPtrTy);
1090 
1091     // Create an explicit cast node.
1092     // We can reuse the existing insert position since if we get here,
1093     // we won't have made any changes which would invalidate it.
1094     SCEV *S = new (SCEVAllocator)
1095         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1096     UniqueSCEVs.InsertNode(S, IP);
1097     addToLoopUseLists(S);
1098     return S;
1099   }
1100 
1101   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1102                        "non-SCEVUnknown's.");
1103 
1104   // Otherwise, we've got some expression that is more complex than just a
1105   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1106   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1107   // only, and the expressions must otherwise be integer-typed.
1108   // So sink the cast down to the SCEVUnknown's.
1109 
1110   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1111   /// which computes a pointer-typed value, and rewrites the whole expression
1112   /// tree so that *all* the computations are done on integers, and the only
1113   /// pointer-typed operands in the expression are SCEVUnknown.
1114   class SCEVPtrToIntSinkingRewriter
1115       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1116     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1117 
1118   public:
1119     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1120 
1121     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1122       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1123       return Rewriter.visit(Scev);
1124     }
1125 
1126     const SCEV *visit(const SCEV *S) {
1127       Type *STy = S->getType();
1128       // If the expression is not pointer-typed, just keep it as-is.
1129       if (!STy->isPointerTy())
1130         return S;
1131       // Else, recursively sink the cast down into it.
1132       return Base::visit(S);
1133     }
1134 
1135     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1136       SmallVector<const SCEV *, 2> Operands;
1137       bool Changed = false;
1138       for (auto *Op : Expr->operands()) {
1139         Operands.push_back(visit(Op));
1140         Changed |= Op != Operands.back();
1141       }
1142       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1143     }
1144 
1145     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1146       SmallVector<const SCEV *, 2> Operands;
1147       bool Changed = false;
1148       for (auto *Op : Expr->operands()) {
1149         Operands.push_back(visit(Op));
1150         Changed |= Op != Operands.back();
1151       }
1152       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1153     }
1154 
1155     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1156       assert(Expr->getType()->isPointerTy() &&
1157              "Should only reach pointer-typed SCEVUnknown's.");
1158       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1159     }
1160   };
1161 
1162   // And actually perform the cast sinking.
1163   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1164   assert(IntOp->getType()->isIntegerTy() &&
1165          "We must have succeeded in sinking the cast, "
1166          "and ending up with an integer-typed expression!");
1167   return IntOp;
1168 }
1169 
1170 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1171   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1172 
1173   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1174   if (isa<SCEVCouldNotCompute>(IntOp))
1175     return IntOp;
1176 
1177   return getTruncateOrZeroExtend(IntOp, Ty);
1178 }
1179 
1180 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1181                                              unsigned Depth) {
1182   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1183          "This is not a truncating conversion!");
1184   assert(isSCEVable(Ty) &&
1185          "This is not a conversion to a SCEVable type!");
1186   Ty = getEffectiveSCEVType(Ty);
1187 
1188   FoldingSetNodeID ID;
1189   ID.AddInteger(scTruncate);
1190   ID.AddPointer(Op);
1191   ID.AddPointer(Ty);
1192   void *IP = nullptr;
1193   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1194 
1195   // Fold if the operand is constant.
1196   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1197     return getConstant(
1198       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1199 
1200   // trunc(trunc(x)) --> trunc(x)
1201   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1202     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1203 
1204   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1205   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1206     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1207 
1208   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1209   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1210     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1211 
1212   if (Depth > MaxCastDepth) {
1213     SCEV *S =
1214         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1215     UniqueSCEVs.InsertNode(S, IP);
1216     addToLoopUseLists(S);
1217     return S;
1218   }
1219 
1220   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1221   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1222   // if after transforming we have at most one truncate, not counting truncates
1223   // that replace other casts.
1224   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1225     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1226     SmallVector<const SCEV *, 4> Operands;
1227     unsigned numTruncs = 0;
1228     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1229          ++i) {
1230       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1231       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1232           isa<SCEVTruncateExpr>(S))
1233         numTruncs++;
1234       Operands.push_back(S);
1235     }
1236     if (numTruncs < 2) {
1237       if (isa<SCEVAddExpr>(Op))
1238         return getAddExpr(Operands);
1239       else if (isa<SCEVMulExpr>(Op))
1240         return getMulExpr(Operands);
1241       else
1242         llvm_unreachable("Unexpected SCEV type for Op.");
1243     }
1244     // Although we checked in the beginning that ID is not in the cache, it is
1245     // possible that during recursion and different modification ID was inserted
1246     // into the cache. So if we find it, just return it.
1247     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1248       return S;
1249   }
1250 
1251   // If the input value is a chrec scev, truncate the chrec's operands.
1252   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1253     SmallVector<const SCEV *, 4> Operands;
1254     for (const SCEV *Op : AddRec->operands())
1255       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1256     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1257   }
1258 
1259   // Return zero if truncating to known zeros.
1260   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1261   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1262     return getZero(Ty);
1263 
1264   // The cast wasn't folded; create an explicit cast node. We can reuse
1265   // the existing insert position since if we get here, we won't have
1266   // made any changes which would invalidate it.
1267   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1268                                                  Op, Ty);
1269   UniqueSCEVs.InsertNode(S, IP);
1270   addToLoopUseLists(S);
1271   return S;
1272 }
1273 
1274 // Get the limit of a recurrence such that incrementing by Step cannot cause
1275 // signed overflow as long as the value of the recurrence within the
1276 // loop does not exceed this limit before incrementing.
1277 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1278                                                  ICmpInst::Predicate *Pred,
1279                                                  ScalarEvolution *SE) {
1280   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1281   if (SE->isKnownPositive(Step)) {
1282     *Pred = ICmpInst::ICMP_SLT;
1283     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1284                            SE->getSignedRangeMax(Step));
1285   }
1286   if (SE->isKnownNegative(Step)) {
1287     *Pred = ICmpInst::ICMP_SGT;
1288     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1289                            SE->getSignedRangeMin(Step));
1290   }
1291   return nullptr;
1292 }
1293 
1294 // Get the limit of a recurrence such that incrementing by Step cannot cause
1295 // unsigned overflow as long as the value of the recurrence within the loop does
1296 // not exceed this limit before incrementing.
1297 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1298                                                    ICmpInst::Predicate *Pred,
1299                                                    ScalarEvolution *SE) {
1300   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1301   *Pred = ICmpInst::ICMP_ULT;
1302 
1303   return SE->getConstant(APInt::getMinValue(BitWidth) -
1304                          SE->getUnsignedRangeMax(Step));
1305 }
1306 
1307 namespace {
1308 
1309 struct ExtendOpTraitsBase {
1310   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1311                                                           unsigned);
1312 };
1313 
1314 // Used to make code generic over signed and unsigned overflow.
1315 template <typename ExtendOp> struct ExtendOpTraits {
1316   // Members present:
1317   //
1318   // static const SCEV::NoWrapFlags WrapType;
1319   //
1320   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1321   //
1322   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1323   //                                           ICmpInst::Predicate *Pred,
1324   //                                           ScalarEvolution *SE);
1325 };
1326 
1327 template <>
1328 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1329   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1330 
1331   static const GetExtendExprTy GetExtendExpr;
1332 
1333   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1334                                              ICmpInst::Predicate *Pred,
1335                                              ScalarEvolution *SE) {
1336     return getSignedOverflowLimitForStep(Step, Pred, SE);
1337   }
1338 };
1339 
1340 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1341     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1342 
1343 template <>
1344 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1345   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1346 
1347   static const GetExtendExprTy GetExtendExpr;
1348 
1349   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1350                                              ICmpInst::Predicate *Pred,
1351                                              ScalarEvolution *SE) {
1352     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1353   }
1354 };
1355 
1356 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1357     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1358 
1359 } // end anonymous namespace
1360 
1361 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1362 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1363 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1364 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1365 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1366 // expression "Step + sext/zext(PreIncAR)" is congruent with
1367 // "sext/zext(PostIncAR)"
1368 template <typename ExtendOpTy>
1369 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1370                                         ScalarEvolution *SE, unsigned Depth) {
1371   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1372   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1373 
1374   const Loop *L = AR->getLoop();
1375   const SCEV *Start = AR->getStart();
1376   const SCEV *Step = AR->getStepRecurrence(*SE);
1377 
1378   // Check for a simple looking step prior to loop entry.
1379   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1380   if (!SA)
1381     return nullptr;
1382 
1383   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1384   // subtraction is expensive. For this purpose, perform a quick and dirty
1385   // difference, by checking for Step in the operand list.
1386   SmallVector<const SCEV *, 4> DiffOps;
1387   for (const SCEV *Op : SA->operands())
1388     if (Op != Step)
1389       DiffOps.push_back(Op);
1390 
1391   if (DiffOps.size() == SA->getNumOperands())
1392     return nullptr;
1393 
1394   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1395   // `Step`:
1396 
1397   // 1. NSW/NUW flags on the step increment.
1398   auto PreStartFlags =
1399     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1400   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1401   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1402       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1403 
1404   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1405   // "S+X does not sign/unsign-overflow".
1406   //
1407 
1408   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1409   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1410       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1411     return PreStart;
1412 
1413   // 2. Direct overflow check on the step operation's expression.
1414   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1415   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1416   const SCEV *OperandExtendedStart =
1417       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1418                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1419   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1420     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1421       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1422       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1423       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1424       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1425     }
1426     return PreStart;
1427   }
1428 
1429   // 3. Loop precondition.
1430   ICmpInst::Predicate Pred;
1431   const SCEV *OverflowLimit =
1432       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1433 
1434   if (OverflowLimit &&
1435       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1436     return PreStart;
1437 
1438   return nullptr;
1439 }
1440 
1441 // Get the normalized zero or sign extended expression for this AddRec's Start.
1442 template <typename ExtendOpTy>
1443 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1444                                         ScalarEvolution *SE,
1445                                         unsigned Depth) {
1446   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1447 
1448   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1449   if (!PreStart)
1450     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1451 
1452   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1453                                              Depth),
1454                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1455 }
1456 
1457 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1458 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1459 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1460 //
1461 // Formally:
1462 //
1463 //     {S,+,X} == {S-T,+,X} + T
1464 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1465 //
1466 // If ({S-T,+,X} + T) does not overflow  ... (1)
1467 //
1468 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1469 //
1470 // If {S-T,+,X} does not overflow  ... (2)
1471 //
1472 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1473 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1474 //
1475 // If (S-T)+T does not overflow  ... (3)
1476 //
1477 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1478 //      == {Ext(S),+,Ext(X)} == LHS
1479 //
1480 // Thus, if (1), (2) and (3) are true for some T, then
1481 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1482 //
1483 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1484 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1485 // to check for (1) and (2).
1486 //
1487 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1488 // is `Delta` (defined below).
1489 template <typename ExtendOpTy>
1490 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1491                                                 const SCEV *Step,
1492                                                 const Loop *L) {
1493   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1494 
1495   // We restrict `Start` to a constant to prevent SCEV from spending too much
1496   // time here.  It is correct (but more expensive) to continue with a
1497   // non-constant `Start` and do a general SCEV subtraction to compute
1498   // `PreStart` below.
1499   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1500   if (!StartC)
1501     return false;
1502 
1503   APInt StartAI = StartC->getAPInt();
1504 
1505   for (unsigned Delta : {-2, -1, 1, 2}) {
1506     const SCEV *PreStart = getConstant(StartAI - Delta);
1507 
1508     FoldingSetNodeID ID;
1509     ID.AddInteger(scAddRecExpr);
1510     ID.AddPointer(PreStart);
1511     ID.AddPointer(Step);
1512     ID.AddPointer(L);
1513     void *IP = nullptr;
1514     const auto *PreAR =
1515       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1516 
1517     // Give up if we don't already have the add recurrence we need because
1518     // actually constructing an add recurrence is relatively expensive.
1519     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1520       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1521       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1522       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1523           DeltaS, &Pred, this);
1524       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1525         return true;
1526     }
1527   }
1528 
1529   return false;
1530 }
1531 
1532 // Finds an integer D for an expression (C + x + y + ...) such that the top
1533 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1534 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1535 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1536 // the (C + x + y + ...) expression is \p WholeAddExpr.
1537 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1538                                             const SCEVConstant *ConstantTerm,
1539                                             const SCEVAddExpr *WholeAddExpr) {
1540   const APInt &C = ConstantTerm->getAPInt();
1541   const unsigned BitWidth = C.getBitWidth();
1542   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1543   uint32_t TZ = BitWidth;
1544   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1545     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1546   if (TZ) {
1547     // Set D to be as many least significant bits of C as possible while still
1548     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1549     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1550   }
1551   return APInt(BitWidth, 0);
1552 }
1553 
1554 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1555 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1556 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1557 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1558 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1559                                             const APInt &ConstantStart,
1560                                             const SCEV *Step) {
1561   const unsigned BitWidth = ConstantStart.getBitWidth();
1562   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1563   if (TZ)
1564     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1565                          : ConstantStart;
1566   return APInt(BitWidth, 0);
1567 }
1568 
1569 const SCEV *
1570 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1571   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1572          "This is not an extending conversion!");
1573   assert(isSCEVable(Ty) &&
1574          "This is not a conversion to a SCEVable type!");
1575   Ty = getEffectiveSCEVType(Ty);
1576 
1577   // Fold if the operand is constant.
1578   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1579     return getConstant(
1580       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1581 
1582   // zext(zext(x)) --> zext(x)
1583   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1584     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1585 
1586   // Before doing any expensive analysis, check to see if we've already
1587   // computed a SCEV for this Op and Ty.
1588   FoldingSetNodeID ID;
1589   ID.AddInteger(scZeroExtend);
1590   ID.AddPointer(Op);
1591   ID.AddPointer(Ty);
1592   void *IP = nullptr;
1593   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1594   if (Depth > MaxCastDepth) {
1595     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1596                                                      Op, Ty);
1597     UniqueSCEVs.InsertNode(S, IP);
1598     addToLoopUseLists(S);
1599     return S;
1600   }
1601 
1602   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1603   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1604     // It's possible the bits taken off by the truncate were all zero bits. If
1605     // so, we should be able to simplify this further.
1606     const SCEV *X = ST->getOperand();
1607     ConstantRange CR = getUnsignedRange(X);
1608     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1609     unsigned NewBits = getTypeSizeInBits(Ty);
1610     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1611             CR.zextOrTrunc(NewBits)))
1612       return getTruncateOrZeroExtend(X, Ty, Depth);
1613   }
1614 
1615   // If the input value is a chrec scev, and we can prove that the value
1616   // did not overflow the old, smaller, value, we can zero extend all of the
1617   // operands (often constants).  This allows analysis of something like
1618   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1619   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1620     if (AR->isAffine()) {
1621       const SCEV *Start = AR->getStart();
1622       const SCEV *Step = AR->getStepRecurrence(*this);
1623       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1624       const Loop *L = AR->getLoop();
1625 
1626       if (!AR->hasNoUnsignedWrap()) {
1627         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1628         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1629       }
1630 
1631       // If we have special knowledge that this addrec won't overflow,
1632       // we don't need to do any further analysis.
1633       if (AR->hasNoUnsignedWrap())
1634         return getAddRecExpr(
1635             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1636             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1637 
1638       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1639       // Note that this serves two purposes: It filters out loops that are
1640       // simply not analyzable, and it covers the case where this code is
1641       // being called from within backedge-taken count analysis, such that
1642       // attempting to ask for the backedge-taken count would likely result
1643       // in infinite recursion. In the later case, the analysis code will
1644       // cope with a conservative value, and it will take care to purge
1645       // that value once it has finished.
1646       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1647       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1648         // Manually compute the final value for AR, checking for overflow.
1649 
1650         // Check whether the backedge-taken count can be losslessly casted to
1651         // the addrec's type. The count is always unsigned.
1652         const SCEV *CastedMaxBECount =
1653             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1654         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1655             CastedMaxBECount, MaxBECount->getType(), Depth);
1656         if (MaxBECount == RecastedMaxBECount) {
1657           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1658           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1659           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1660                                         SCEV::FlagAnyWrap, Depth + 1);
1661           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1662                                                           SCEV::FlagAnyWrap,
1663                                                           Depth + 1),
1664                                                WideTy, Depth + 1);
1665           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1666           const SCEV *WideMaxBECount =
1667             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1668           const SCEV *OperandExtendedAdd =
1669             getAddExpr(WideStart,
1670                        getMulExpr(WideMaxBECount,
1671                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1672                                   SCEV::FlagAnyWrap, Depth + 1),
1673                        SCEV::FlagAnyWrap, Depth + 1);
1674           if (ZAdd == OperandExtendedAdd) {
1675             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1676             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1677             // Return the expression with the addrec on the outside.
1678             return getAddRecExpr(
1679                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1680                                                          Depth + 1),
1681                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1682                 AR->getNoWrapFlags());
1683           }
1684           // Similar to above, only this time treat the step value as signed.
1685           // This covers loops that count down.
1686           OperandExtendedAdd =
1687             getAddExpr(WideStart,
1688                        getMulExpr(WideMaxBECount,
1689                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1690                                   SCEV::FlagAnyWrap, Depth + 1),
1691                        SCEV::FlagAnyWrap, Depth + 1);
1692           if (ZAdd == OperandExtendedAdd) {
1693             // Cache knowledge of AR NW, which is propagated to this AddRec.
1694             // Negative step causes unsigned wrap, but it still can't self-wrap.
1695             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1696             // Return the expression with the addrec on the outside.
1697             return getAddRecExpr(
1698                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1699                                                          Depth + 1),
1700                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1701                 AR->getNoWrapFlags());
1702           }
1703         }
1704       }
1705 
1706       // Normally, in the cases we can prove no-overflow via a
1707       // backedge guarding condition, we can also compute a backedge
1708       // taken count for the loop.  The exceptions are assumptions and
1709       // guards present in the loop -- SCEV is not great at exploiting
1710       // these to compute max backedge taken counts, but can still use
1711       // these to prove lack of overflow.  Use this fact to avoid
1712       // doing extra work that may not pay off.
1713       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1714           !AC.assumptions().empty()) {
1715 
1716         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1717         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1718         if (AR->hasNoUnsignedWrap()) {
1719           // Same as nuw case above - duplicated here to avoid a compile time
1720           // issue.  It's not clear that the order of checks does matter, but
1721           // it's one of two issue possible causes for a change which was
1722           // reverted.  Be conservative for the moment.
1723           return getAddRecExpr(
1724                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1725                                                          Depth + 1),
1726                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1727                 AR->getNoWrapFlags());
1728         }
1729 
1730         // For a negative step, we can extend the operands iff doing so only
1731         // traverses values in the range zext([0,UINT_MAX]).
1732         if (isKnownNegative(Step)) {
1733           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1734                                       getSignedRangeMin(Step));
1735           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1736               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1737             // Cache knowledge of AR NW, which is propagated to this
1738             // AddRec.  Negative step causes unsigned wrap, but it
1739             // still can't self-wrap.
1740             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1741             // Return the expression with the addrec on the outside.
1742             return getAddRecExpr(
1743                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1744                                                          Depth + 1),
1745                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1746                 AR->getNoWrapFlags());
1747           }
1748         }
1749       }
1750 
1751       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1752       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1753       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1754       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1755         const APInt &C = SC->getAPInt();
1756         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1757         if (D != 0) {
1758           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1759           const SCEV *SResidual =
1760               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1761           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1762           return getAddExpr(SZExtD, SZExtR,
1763                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1764                             Depth + 1);
1765         }
1766       }
1767 
1768       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1769         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1770         return getAddRecExpr(
1771             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1772             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1773       }
1774     }
1775 
1776   // zext(A % B) --> zext(A) % zext(B)
1777   {
1778     const SCEV *LHS;
1779     const SCEV *RHS;
1780     if (matchURem(Op, LHS, RHS))
1781       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1782                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1783   }
1784 
1785   // zext(A / B) --> zext(A) / zext(B).
1786   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1787     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1788                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1789 
1790   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1791     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1792     if (SA->hasNoUnsignedWrap()) {
1793       // If the addition does not unsign overflow then we can, by definition,
1794       // commute the zero extension with the addition operation.
1795       SmallVector<const SCEV *, 4> Ops;
1796       for (const auto *Op : SA->operands())
1797         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1798       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1799     }
1800 
1801     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1802     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1803     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1804     //
1805     // Often address arithmetics contain expressions like
1806     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1807     // This transformation is useful while proving that such expressions are
1808     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1809     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1810       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1811       if (D != 0) {
1812         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1813         const SCEV *SResidual =
1814             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1815         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1816         return getAddExpr(SZExtD, SZExtR,
1817                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1818                           Depth + 1);
1819       }
1820     }
1821   }
1822 
1823   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1824     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1825     if (SM->hasNoUnsignedWrap()) {
1826       // If the multiply does not unsign overflow then we can, by definition,
1827       // commute the zero extension with the multiply operation.
1828       SmallVector<const SCEV *, 4> Ops;
1829       for (const auto *Op : SM->operands())
1830         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1831       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1832     }
1833 
1834     // zext(2^K * (trunc X to iN)) to iM ->
1835     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1836     //
1837     // Proof:
1838     //
1839     //     zext(2^K * (trunc X to iN)) to iM
1840     //   = zext((trunc X to iN) << K) to iM
1841     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1842     //     (because shl removes the top K bits)
1843     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1844     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1845     //
1846     if (SM->getNumOperands() == 2)
1847       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1848         if (MulLHS->getAPInt().isPowerOf2())
1849           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1850             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1851                                MulLHS->getAPInt().logBase2();
1852             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1853             return getMulExpr(
1854                 getZeroExtendExpr(MulLHS, Ty),
1855                 getZeroExtendExpr(
1856                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1857                 SCEV::FlagNUW, Depth + 1);
1858           }
1859   }
1860 
1861   // The cast wasn't folded; create an explicit cast node.
1862   // Recompute the insert position, as it may have been invalidated.
1863   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1864   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1865                                                    Op, Ty);
1866   UniqueSCEVs.InsertNode(S, IP);
1867   addToLoopUseLists(S);
1868   return S;
1869 }
1870 
1871 const SCEV *
1872 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1873   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1874          "This is not an extending conversion!");
1875   assert(isSCEVable(Ty) &&
1876          "This is not a conversion to a SCEVable type!");
1877   Ty = getEffectiveSCEVType(Ty);
1878 
1879   // Fold if the operand is constant.
1880   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1881     return getConstant(
1882       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1883 
1884   // sext(sext(x)) --> sext(x)
1885   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1886     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1887 
1888   // sext(zext(x)) --> zext(x)
1889   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1890     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1891 
1892   // Before doing any expensive analysis, check to see if we've already
1893   // computed a SCEV for this Op and Ty.
1894   FoldingSetNodeID ID;
1895   ID.AddInteger(scSignExtend);
1896   ID.AddPointer(Op);
1897   ID.AddPointer(Ty);
1898   void *IP = nullptr;
1899   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1900   // Limit recursion depth.
1901   if (Depth > MaxCastDepth) {
1902     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1903                                                      Op, Ty);
1904     UniqueSCEVs.InsertNode(S, IP);
1905     addToLoopUseLists(S);
1906     return S;
1907   }
1908 
1909   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1910   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1911     // It's possible the bits taken off by the truncate were all sign bits. If
1912     // so, we should be able to simplify this further.
1913     const SCEV *X = ST->getOperand();
1914     ConstantRange CR = getSignedRange(X);
1915     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1916     unsigned NewBits = getTypeSizeInBits(Ty);
1917     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1918             CR.sextOrTrunc(NewBits)))
1919       return getTruncateOrSignExtend(X, Ty, Depth);
1920   }
1921 
1922   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1923     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1924     if (SA->hasNoSignedWrap()) {
1925       // If the addition does not sign overflow then we can, by definition,
1926       // commute the sign extension with the addition operation.
1927       SmallVector<const SCEV *, 4> Ops;
1928       for (const auto *Op : SA->operands())
1929         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1930       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1931     }
1932 
1933     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1934     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1935     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1936     //
1937     // For instance, this will bring two seemingly different expressions:
1938     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1939     //         sext(6 + 20 * %x + 24 * %y)
1940     // to the same form:
1941     //     2 + sext(4 + 20 * %x + 24 * %y)
1942     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1943       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1944       if (D != 0) {
1945         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1946         const SCEV *SResidual =
1947             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1948         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1949         return getAddExpr(SSExtD, SSExtR,
1950                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1951                           Depth + 1);
1952       }
1953     }
1954   }
1955   // If the input value is a chrec scev, and we can prove that the value
1956   // did not overflow the old, smaller, value, we can sign extend all of the
1957   // operands (often constants).  This allows analysis of something like
1958   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1959   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1960     if (AR->isAffine()) {
1961       const SCEV *Start = AR->getStart();
1962       const SCEV *Step = AR->getStepRecurrence(*this);
1963       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1964       const Loop *L = AR->getLoop();
1965 
1966       if (!AR->hasNoSignedWrap()) {
1967         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1968         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1969       }
1970 
1971       // If we have special knowledge that this addrec won't overflow,
1972       // we don't need to do any further analysis.
1973       if (AR->hasNoSignedWrap())
1974         return getAddRecExpr(
1975             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1976             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1977 
1978       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1979       // Note that this serves two purposes: It filters out loops that are
1980       // simply not analyzable, and it covers the case where this code is
1981       // being called from within backedge-taken count analysis, such that
1982       // attempting to ask for the backedge-taken count would likely result
1983       // in infinite recursion. In the later case, the analysis code will
1984       // cope with a conservative value, and it will take care to purge
1985       // that value once it has finished.
1986       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1987       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1988         // Manually compute the final value for AR, checking for
1989         // overflow.
1990 
1991         // Check whether the backedge-taken count can be losslessly casted to
1992         // the addrec's type. The count is always unsigned.
1993         const SCEV *CastedMaxBECount =
1994             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1995         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1996             CastedMaxBECount, MaxBECount->getType(), Depth);
1997         if (MaxBECount == RecastedMaxBECount) {
1998           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1999           // Check whether Start+Step*MaxBECount has no signed overflow.
2000           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2001                                         SCEV::FlagAnyWrap, Depth + 1);
2002           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2003                                                           SCEV::FlagAnyWrap,
2004                                                           Depth + 1),
2005                                                WideTy, Depth + 1);
2006           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2007           const SCEV *WideMaxBECount =
2008             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2009           const SCEV *OperandExtendedAdd =
2010             getAddExpr(WideStart,
2011                        getMulExpr(WideMaxBECount,
2012                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2013                                   SCEV::FlagAnyWrap, Depth + 1),
2014                        SCEV::FlagAnyWrap, Depth + 1);
2015           if (SAdd == OperandExtendedAdd) {
2016             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2017             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2018             // Return the expression with the addrec on the outside.
2019             return getAddRecExpr(
2020                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2021                                                          Depth + 1),
2022                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2023                 AR->getNoWrapFlags());
2024           }
2025           // Similar to above, only this time treat the step value as unsigned.
2026           // This covers loops that count up with an unsigned step.
2027           OperandExtendedAdd =
2028             getAddExpr(WideStart,
2029                        getMulExpr(WideMaxBECount,
2030                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2031                                   SCEV::FlagAnyWrap, Depth + 1),
2032                        SCEV::FlagAnyWrap, Depth + 1);
2033           if (SAdd == OperandExtendedAdd) {
2034             // If AR wraps around then
2035             //
2036             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2037             // => SAdd != OperandExtendedAdd
2038             //
2039             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2040             // (SAdd == OperandExtendedAdd => AR is NW)
2041 
2042             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2043 
2044             // Return the expression with the addrec on the outside.
2045             return getAddRecExpr(
2046                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2047                                                          Depth + 1),
2048                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2049                 AR->getNoWrapFlags());
2050           }
2051         }
2052       }
2053 
2054       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2055       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2056       if (AR->hasNoSignedWrap()) {
2057         // Same as nsw case above - duplicated here to avoid a compile time
2058         // issue.  It's not clear that the order of checks does matter, but
2059         // it's one of two issue possible causes for a change which was
2060         // reverted.  Be conservative for the moment.
2061         return getAddRecExpr(
2062             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2063             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2064       }
2065 
2066       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2067       // if D + (C - D + Step * n) could be proven to not signed wrap
2068       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2069       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2070         const APInt &C = SC->getAPInt();
2071         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2072         if (D != 0) {
2073           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2074           const SCEV *SResidual =
2075               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2076           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2077           return getAddExpr(SSExtD, SSExtR,
2078                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2079                             Depth + 1);
2080         }
2081       }
2082 
2083       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2084         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2085         return getAddRecExpr(
2086             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2087             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2088       }
2089     }
2090 
2091   // If the input value is provably positive and we could not simplify
2092   // away the sext build a zext instead.
2093   if (isKnownNonNegative(Op))
2094     return getZeroExtendExpr(Op, Ty, Depth + 1);
2095 
2096   // The cast wasn't folded; create an explicit cast node.
2097   // Recompute the insert position, as it may have been invalidated.
2098   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2099   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2100                                                    Op, Ty);
2101   UniqueSCEVs.InsertNode(S, IP);
2102   addToLoopUseLists(S);
2103   return S;
2104 }
2105 
2106 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2107 /// unspecified bits out to the given type.
2108 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2109                                               Type *Ty) {
2110   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2111          "This is not an extending conversion!");
2112   assert(isSCEVable(Ty) &&
2113          "This is not a conversion to a SCEVable type!");
2114   Ty = getEffectiveSCEVType(Ty);
2115 
2116   // Sign-extend negative constants.
2117   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2118     if (SC->getAPInt().isNegative())
2119       return getSignExtendExpr(Op, Ty);
2120 
2121   // Peel off a truncate cast.
2122   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2123     const SCEV *NewOp = T->getOperand();
2124     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2125       return getAnyExtendExpr(NewOp, Ty);
2126     return getTruncateOrNoop(NewOp, Ty);
2127   }
2128 
2129   // Next try a zext cast. If the cast is folded, use it.
2130   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2131   if (!isa<SCEVZeroExtendExpr>(ZExt))
2132     return ZExt;
2133 
2134   // Next try a sext cast. If the cast is folded, use it.
2135   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2136   if (!isa<SCEVSignExtendExpr>(SExt))
2137     return SExt;
2138 
2139   // Force the cast to be folded into the operands of an addrec.
2140   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2141     SmallVector<const SCEV *, 4> Ops;
2142     for (const SCEV *Op : AR->operands())
2143       Ops.push_back(getAnyExtendExpr(Op, Ty));
2144     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2145   }
2146 
2147   // If the expression is obviously signed, use the sext cast value.
2148   if (isa<SCEVSMaxExpr>(Op))
2149     return SExt;
2150 
2151   // Absent any other information, use the zext cast value.
2152   return ZExt;
2153 }
2154 
2155 /// Process the given Ops list, which is a list of operands to be added under
2156 /// the given scale, update the given map. This is a helper function for
2157 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2158 /// that would form an add expression like this:
2159 ///
2160 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2161 ///
2162 /// where A and B are constants, update the map with these values:
2163 ///
2164 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2165 ///
2166 /// and add 13 + A*B*29 to AccumulatedConstant.
2167 /// This will allow getAddRecExpr to produce this:
2168 ///
2169 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2170 ///
2171 /// This form often exposes folding opportunities that are hidden in
2172 /// the original operand list.
2173 ///
2174 /// Return true iff it appears that any interesting folding opportunities
2175 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2176 /// the common case where no interesting opportunities are present, and
2177 /// is also used as a check to avoid infinite recursion.
2178 static bool
2179 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2180                              SmallVectorImpl<const SCEV *> &NewOps,
2181                              APInt &AccumulatedConstant,
2182                              const SCEV *const *Ops, size_t NumOperands,
2183                              const APInt &Scale,
2184                              ScalarEvolution &SE) {
2185   bool Interesting = false;
2186 
2187   // Iterate over the add operands. They are sorted, with constants first.
2188   unsigned i = 0;
2189   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2190     ++i;
2191     // Pull a buried constant out to the outside.
2192     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2193       Interesting = true;
2194     AccumulatedConstant += Scale * C->getAPInt();
2195   }
2196 
2197   // Next comes everything else. We're especially interested in multiplies
2198   // here, but they're in the middle, so just visit the rest with one loop.
2199   for (; i != NumOperands; ++i) {
2200     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2201     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2202       APInt NewScale =
2203           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2204       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2205         // A multiplication of a constant with another add; recurse.
2206         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2207         Interesting |=
2208           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2209                                        Add->op_begin(), Add->getNumOperands(),
2210                                        NewScale, SE);
2211       } else {
2212         // A multiplication of a constant with some other value. Update
2213         // the map.
2214         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2215         const SCEV *Key = SE.getMulExpr(MulOps);
2216         auto Pair = M.insert({Key, NewScale});
2217         if (Pair.second) {
2218           NewOps.push_back(Pair.first->first);
2219         } else {
2220           Pair.first->second += NewScale;
2221           // The map already had an entry for this value, which may indicate
2222           // a folding opportunity.
2223           Interesting = true;
2224         }
2225       }
2226     } else {
2227       // An ordinary operand. Update the map.
2228       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2229           M.insert({Ops[i], Scale});
2230       if (Pair.second) {
2231         NewOps.push_back(Pair.first->first);
2232       } else {
2233         Pair.first->second += Scale;
2234         // The map already had an entry for this value, which may indicate
2235         // a folding opportunity.
2236         Interesting = true;
2237       }
2238     }
2239   }
2240 
2241   return Interesting;
2242 }
2243 
2244 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2245                                       const SCEV *LHS, const SCEV *RHS) {
2246   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2247                                             SCEV::NoWrapFlags, unsigned);
2248   switch (BinOp) {
2249   default:
2250     llvm_unreachable("Unsupported binary op");
2251   case Instruction::Add:
2252     Operation = &ScalarEvolution::getAddExpr;
2253     break;
2254   case Instruction::Sub:
2255     Operation = &ScalarEvolution::getMinusSCEV;
2256     break;
2257   case Instruction::Mul:
2258     Operation = &ScalarEvolution::getMulExpr;
2259     break;
2260   }
2261 
2262   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2263       Signed ? &ScalarEvolution::getSignExtendExpr
2264              : &ScalarEvolution::getZeroExtendExpr;
2265 
2266   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2267   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2268   auto *WideTy =
2269       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2270 
2271   const SCEV *A = (this->*Extension)(
2272       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2273   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2274                                      (this->*Extension)(RHS, WideTy, 0),
2275                                      SCEV::FlagAnyWrap, 0);
2276   return A == B;
2277 }
2278 
2279 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2280 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2281     const OverflowingBinaryOperator *OBO) {
2282   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2283 
2284   if (OBO->hasNoUnsignedWrap())
2285     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2286   if (OBO->hasNoSignedWrap())
2287     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2288 
2289   bool Deduced = false;
2290 
2291   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2292     return {Flags, Deduced};
2293 
2294   if (OBO->getOpcode() != Instruction::Add &&
2295       OBO->getOpcode() != Instruction::Sub &&
2296       OBO->getOpcode() != Instruction::Mul)
2297     return {Flags, Deduced};
2298 
2299   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2300   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2301 
2302   if (!OBO->hasNoUnsignedWrap() &&
2303       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2304                       /* Signed */ false, LHS, RHS)) {
2305     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2306     Deduced = true;
2307   }
2308 
2309   if (!OBO->hasNoSignedWrap() &&
2310       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2311                       /* Signed */ true, LHS, RHS)) {
2312     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2313     Deduced = true;
2314   }
2315 
2316   return {Flags, Deduced};
2317 }
2318 
2319 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2320 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2321 // can't-overflow flags for the operation if possible.
2322 static SCEV::NoWrapFlags
2323 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2324                       const ArrayRef<const SCEV *> Ops,
2325                       SCEV::NoWrapFlags Flags) {
2326   using namespace std::placeholders;
2327 
2328   using OBO = OverflowingBinaryOperator;
2329 
2330   bool CanAnalyze =
2331       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2332   (void)CanAnalyze;
2333   assert(CanAnalyze && "don't call from other places!");
2334 
2335   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2336   SCEV::NoWrapFlags SignOrUnsignWrap =
2337       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2338 
2339   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2340   auto IsKnownNonNegative = [&](const SCEV *S) {
2341     return SE->isKnownNonNegative(S);
2342   };
2343 
2344   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2345     Flags =
2346         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2347 
2348   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2349 
2350   if (SignOrUnsignWrap != SignOrUnsignMask &&
2351       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2352       isa<SCEVConstant>(Ops[0])) {
2353 
2354     auto Opcode = [&] {
2355       switch (Type) {
2356       case scAddExpr:
2357         return Instruction::Add;
2358       case scMulExpr:
2359         return Instruction::Mul;
2360       default:
2361         llvm_unreachable("Unexpected SCEV op.");
2362       }
2363     }();
2364 
2365     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2366 
2367     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2368     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2369       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2370           Opcode, C, OBO::NoSignedWrap);
2371       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2372         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2373     }
2374 
2375     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2376     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2377       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2378           Opcode, C, OBO::NoUnsignedWrap);
2379       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2380         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2381     }
2382   }
2383 
2384   return Flags;
2385 }
2386 
2387 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2388   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2389 }
2390 
2391 /// Get a canonical add expression, or something simpler if possible.
2392 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2393                                         SCEV::NoWrapFlags OrigFlags,
2394                                         unsigned Depth) {
2395   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2396          "only nuw or nsw allowed");
2397   assert(!Ops.empty() && "Cannot get empty add!");
2398   if (Ops.size() == 1) return Ops[0];
2399 #ifndef NDEBUG
2400   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2401   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2402     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2403            "SCEVAddExpr operand types don't match!");
2404 #endif
2405 
2406   // Sort by complexity, this groups all similar expression types together.
2407   GroupByComplexity(Ops, &LI, DT);
2408 
2409   // If there are any constants, fold them together.
2410   unsigned Idx = 0;
2411   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2412     ++Idx;
2413     assert(Idx < Ops.size());
2414     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2415       // We found two constants, fold them together!
2416       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2417       if (Ops.size() == 2) return Ops[0];
2418       Ops.erase(Ops.begin()+1);  // Erase the folded element
2419       LHSC = cast<SCEVConstant>(Ops[0]);
2420     }
2421 
2422     // If we are left with a constant zero being added, strip it off.
2423     if (LHSC->getValue()->isZero()) {
2424       Ops.erase(Ops.begin());
2425       --Idx;
2426     }
2427 
2428     if (Ops.size() == 1) return Ops[0];
2429   }
2430 
2431   // Delay expensive flag strengthening until necessary.
2432   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2433     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2434   };
2435 
2436   // Limit recursion calls depth.
2437   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2438     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2439 
2440   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2441     // Don't strengthen flags if we have no new information.
2442     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2443     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2444       Add->setNoWrapFlags(ComputeFlags(Ops));
2445     return S;
2446   }
2447 
2448   // Okay, check to see if the same value occurs in the operand list more than
2449   // once.  If so, merge them together into an multiply expression.  Since we
2450   // sorted the list, these values are required to be adjacent.
2451   Type *Ty = Ops[0]->getType();
2452   bool FoundMatch = false;
2453   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2454     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2455       // Scan ahead to count how many equal operands there are.
2456       unsigned Count = 2;
2457       while (i+Count != e && Ops[i+Count] == Ops[i])
2458         ++Count;
2459       // Merge the values into a multiply.
2460       const SCEV *Scale = getConstant(Ty, Count);
2461       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2462       if (Ops.size() == Count)
2463         return Mul;
2464       Ops[i] = Mul;
2465       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2466       --i; e -= Count - 1;
2467       FoundMatch = true;
2468     }
2469   if (FoundMatch)
2470     return getAddExpr(Ops, OrigFlags, Depth + 1);
2471 
2472   // Check for truncates. If all the operands are truncated from the same
2473   // type, see if factoring out the truncate would permit the result to be
2474   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2475   // if the contents of the resulting outer trunc fold to something simple.
2476   auto FindTruncSrcType = [&]() -> Type * {
2477     // We're ultimately looking to fold an addrec of truncs and muls of only
2478     // constants and truncs, so if we find any other types of SCEV
2479     // as operands of the addrec then we bail and return nullptr here.
2480     // Otherwise, we return the type of the operand of a trunc that we find.
2481     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2482       return T->getOperand()->getType();
2483     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2484       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2485       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2486         return T->getOperand()->getType();
2487     }
2488     return nullptr;
2489   };
2490   if (auto *SrcType = FindTruncSrcType()) {
2491     SmallVector<const SCEV *, 8> LargeOps;
2492     bool Ok = true;
2493     // Check all the operands to see if they can be represented in the
2494     // source type of the truncate.
2495     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2496       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2497         if (T->getOperand()->getType() != SrcType) {
2498           Ok = false;
2499           break;
2500         }
2501         LargeOps.push_back(T->getOperand());
2502       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2503         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2504       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2505         SmallVector<const SCEV *, 8> LargeMulOps;
2506         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2507           if (const SCEVTruncateExpr *T =
2508                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2509             if (T->getOperand()->getType() != SrcType) {
2510               Ok = false;
2511               break;
2512             }
2513             LargeMulOps.push_back(T->getOperand());
2514           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2515             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2516           } else {
2517             Ok = false;
2518             break;
2519           }
2520         }
2521         if (Ok)
2522           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2523       } else {
2524         Ok = false;
2525         break;
2526       }
2527     }
2528     if (Ok) {
2529       // Evaluate the expression in the larger type.
2530       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2531       // If it folds to something simple, use it. Otherwise, don't.
2532       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2533         return getTruncateExpr(Fold, Ty);
2534     }
2535   }
2536 
2537   // Skip past any other cast SCEVs.
2538   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2539     ++Idx;
2540 
2541   // If there are add operands they would be next.
2542   if (Idx < Ops.size()) {
2543     bool DeletedAdd = false;
2544     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2545     // common NUW flag for expression after inlining. Other flags cannot be
2546     // preserved, because they may depend on the original order of operations.
2547     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2548     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2549       if (Ops.size() > AddOpsInlineThreshold ||
2550           Add->getNumOperands() > AddOpsInlineThreshold)
2551         break;
2552       // If we have an add, expand the add operands onto the end of the operands
2553       // list.
2554       Ops.erase(Ops.begin()+Idx);
2555       Ops.append(Add->op_begin(), Add->op_end());
2556       DeletedAdd = true;
2557       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2558     }
2559 
2560     // If we deleted at least one add, we added operands to the end of the list,
2561     // and they are not necessarily sorted.  Recurse to resort and resimplify
2562     // any operands we just acquired.
2563     if (DeletedAdd)
2564       return getAddExpr(Ops, CommonFlags, Depth + 1);
2565   }
2566 
2567   // Skip over the add expression until we get to a multiply.
2568   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2569     ++Idx;
2570 
2571   // Check to see if there are any folding opportunities present with
2572   // operands multiplied by constant values.
2573   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2574     uint64_t BitWidth = getTypeSizeInBits(Ty);
2575     DenseMap<const SCEV *, APInt> M;
2576     SmallVector<const SCEV *, 8> NewOps;
2577     APInt AccumulatedConstant(BitWidth, 0);
2578     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2579                                      Ops.data(), Ops.size(),
2580                                      APInt(BitWidth, 1), *this)) {
2581       struct APIntCompare {
2582         bool operator()(const APInt &LHS, const APInt &RHS) const {
2583           return LHS.ult(RHS);
2584         }
2585       };
2586 
2587       // Some interesting folding opportunity is present, so its worthwhile to
2588       // re-generate the operands list. Group the operands by constant scale,
2589       // to avoid multiplying by the same constant scale multiple times.
2590       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2591       for (const SCEV *NewOp : NewOps)
2592         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2593       // Re-generate the operands list.
2594       Ops.clear();
2595       if (AccumulatedConstant != 0)
2596         Ops.push_back(getConstant(AccumulatedConstant));
2597       for (auto &MulOp : MulOpLists)
2598         if (MulOp.first != 0)
2599           Ops.push_back(getMulExpr(
2600               getConstant(MulOp.first),
2601               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2602               SCEV::FlagAnyWrap, Depth + 1));
2603       if (Ops.empty())
2604         return getZero(Ty);
2605       if (Ops.size() == 1)
2606         return Ops[0];
2607       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2608     }
2609   }
2610 
2611   // If we are adding something to a multiply expression, make sure the
2612   // something is not already an operand of the multiply.  If so, merge it into
2613   // the multiply.
2614   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2615     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2616     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2617       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2618       if (isa<SCEVConstant>(MulOpSCEV))
2619         continue;
2620       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2621         if (MulOpSCEV == Ops[AddOp]) {
2622           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2623           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2624           if (Mul->getNumOperands() != 2) {
2625             // If the multiply has more than two operands, we must get the
2626             // Y*Z term.
2627             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2628                                                 Mul->op_begin()+MulOp);
2629             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2630             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2631           }
2632           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2633           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2634           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2635                                             SCEV::FlagAnyWrap, Depth + 1);
2636           if (Ops.size() == 2) return OuterMul;
2637           if (AddOp < Idx) {
2638             Ops.erase(Ops.begin()+AddOp);
2639             Ops.erase(Ops.begin()+Idx-1);
2640           } else {
2641             Ops.erase(Ops.begin()+Idx);
2642             Ops.erase(Ops.begin()+AddOp-1);
2643           }
2644           Ops.push_back(OuterMul);
2645           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2646         }
2647 
2648       // Check this multiply against other multiplies being added together.
2649       for (unsigned OtherMulIdx = Idx+1;
2650            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2651            ++OtherMulIdx) {
2652         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2653         // If MulOp occurs in OtherMul, we can fold the two multiplies
2654         // together.
2655         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2656              OMulOp != e; ++OMulOp)
2657           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2658             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2659             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2660             if (Mul->getNumOperands() != 2) {
2661               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2662                                                   Mul->op_begin()+MulOp);
2663               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2664               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2665             }
2666             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2667             if (OtherMul->getNumOperands() != 2) {
2668               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2669                                                   OtherMul->op_begin()+OMulOp);
2670               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2671               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2672             }
2673             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2674             const SCEV *InnerMulSum =
2675                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2676             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2677                                               SCEV::FlagAnyWrap, Depth + 1);
2678             if (Ops.size() == 2) return OuterMul;
2679             Ops.erase(Ops.begin()+Idx);
2680             Ops.erase(Ops.begin()+OtherMulIdx-1);
2681             Ops.push_back(OuterMul);
2682             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2683           }
2684       }
2685     }
2686   }
2687 
2688   // If there are any add recurrences in the operands list, see if any other
2689   // added values are loop invariant.  If so, we can fold them into the
2690   // recurrence.
2691   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2692     ++Idx;
2693 
2694   // Scan over all recurrences, trying to fold loop invariants into them.
2695   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2696     // Scan all of the other operands to this add and add them to the vector if
2697     // they are loop invariant w.r.t. the recurrence.
2698     SmallVector<const SCEV *, 8> LIOps;
2699     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2700     const Loop *AddRecLoop = AddRec->getLoop();
2701     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2702       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2703         LIOps.push_back(Ops[i]);
2704         Ops.erase(Ops.begin()+i);
2705         --i; --e;
2706       }
2707 
2708     // If we found some loop invariants, fold them into the recurrence.
2709     if (!LIOps.empty()) {
2710       // Compute nowrap flags for the addition of the loop-invariant ops and
2711       // the addrec. Temporarily push it as an operand for that purpose.
2712       LIOps.push_back(AddRec);
2713       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2714       LIOps.pop_back();
2715 
2716       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2717       LIOps.push_back(AddRec->getStart());
2718 
2719       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2720       // This follows from the fact that the no-wrap flags on the outer add
2721       // expression are applicable on the 0th iteration, when the add recurrence
2722       // will be equal to its start value.
2723       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2724 
2725       // Build the new addrec. Propagate the NUW and NSW flags if both the
2726       // outer add and the inner addrec are guaranteed to have no overflow.
2727       // Always propagate NW.
2728       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2729       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2730 
2731       // If all of the other operands were loop invariant, we are done.
2732       if (Ops.size() == 1) return NewRec;
2733 
2734       // Otherwise, add the folded AddRec by the non-invariant parts.
2735       for (unsigned i = 0;; ++i)
2736         if (Ops[i] == AddRec) {
2737           Ops[i] = NewRec;
2738           break;
2739         }
2740       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2741     }
2742 
2743     // Okay, if there weren't any loop invariants to be folded, check to see if
2744     // there are multiple AddRec's with the same loop induction variable being
2745     // added together.  If so, we can fold them.
2746     for (unsigned OtherIdx = Idx+1;
2747          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2748          ++OtherIdx) {
2749       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2750       // so that the 1st found AddRecExpr is dominated by all others.
2751       assert(DT.dominates(
2752            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2753            AddRec->getLoop()->getHeader()) &&
2754         "AddRecExprs are not sorted in reverse dominance order?");
2755       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2756         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2757         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2758         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2759              ++OtherIdx) {
2760           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2761           if (OtherAddRec->getLoop() == AddRecLoop) {
2762             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2763                  i != e; ++i) {
2764               if (i >= AddRecOps.size()) {
2765                 AddRecOps.append(OtherAddRec->op_begin()+i,
2766                                  OtherAddRec->op_end());
2767                 break;
2768               }
2769               SmallVector<const SCEV *, 2> TwoOps = {
2770                   AddRecOps[i], OtherAddRec->getOperand(i)};
2771               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2772             }
2773             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2774           }
2775         }
2776         // Step size has changed, so we cannot guarantee no self-wraparound.
2777         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2778         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2779       }
2780     }
2781 
2782     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2783     // next one.
2784   }
2785 
2786   // Okay, it looks like we really DO need an add expr.  Check to see if we
2787   // already have one, otherwise create a new one.
2788   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2789 }
2790 
2791 const SCEV *
2792 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2793                                     SCEV::NoWrapFlags Flags) {
2794   FoldingSetNodeID ID;
2795   ID.AddInteger(scAddExpr);
2796   for (const SCEV *Op : Ops)
2797     ID.AddPointer(Op);
2798   void *IP = nullptr;
2799   SCEVAddExpr *S =
2800       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2801   if (!S) {
2802     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2803     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2804     S = new (SCEVAllocator)
2805         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2806     UniqueSCEVs.InsertNode(S, IP);
2807     addToLoopUseLists(S);
2808   }
2809   S->setNoWrapFlags(Flags);
2810   return S;
2811 }
2812 
2813 const SCEV *
2814 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2815                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2816   FoldingSetNodeID ID;
2817   ID.AddInteger(scAddRecExpr);
2818   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2819     ID.AddPointer(Ops[i]);
2820   ID.AddPointer(L);
2821   void *IP = nullptr;
2822   SCEVAddRecExpr *S =
2823       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2824   if (!S) {
2825     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2826     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2827     S = new (SCEVAllocator)
2828         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2829     UniqueSCEVs.InsertNode(S, IP);
2830     addToLoopUseLists(S);
2831   }
2832   setNoWrapFlags(S, Flags);
2833   return S;
2834 }
2835 
2836 const SCEV *
2837 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2838                                     SCEV::NoWrapFlags Flags) {
2839   FoldingSetNodeID ID;
2840   ID.AddInteger(scMulExpr);
2841   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2842     ID.AddPointer(Ops[i]);
2843   void *IP = nullptr;
2844   SCEVMulExpr *S =
2845     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2846   if (!S) {
2847     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2848     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2849     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2850                                         O, Ops.size());
2851     UniqueSCEVs.InsertNode(S, IP);
2852     addToLoopUseLists(S);
2853   }
2854   S->setNoWrapFlags(Flags);
2855   return S;
2856 }
2857 
2858 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2859   uint64_t k = i*j;
2860   if (j > 1 && k / j != i) Overflow = true;
2861   return k;
2862 }
2863 
2864 /// Compute the result of "n choose k", the binomial coefficient.  If an
2865 /// intermediate computation overflows, Overflow will be set and the return will
2866 /// be garbage. Overflow is not cleared on absence of overflow.
2867 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2868   // We use the multiplicative formula:
2869   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2870   // At each iteration, we take the n-th term of the numeral and divide by the
2871   // (k-n)th term of the denominator.  This division will always produce an
2872   // integral result, and helps reduce the chance of overflow in the
2873   // intermediate computations. However, we can still overflow even when the
2874   // final result would fit.
2875 
2876   if (n == 0 || n == k) return 1;
2877   if (k > n) return 0;
2878 
2879   if (k > n/2)
2880     k = n-k;
2881 
2882   uint64_t r = 1;
2883   for (uint64_t i = 1; i <= k; ++i) {
2884     r = umul_ov(r, n-(i-1), Overflow);
2885     r /= i;
2886   }
2887   return r;
2888 }
2889 
2890 /// Determine if any of the operands in this SCEV are a constant or if
2891 /// any of the add or multiply expressions in this SCEV contain a constant.
2892 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2893   struct FindConstantInAddMulChain {
2894     bool FoundConstant = false;
2895 
2896     bool follow(const SCEV *S) {
2897       FoundConstant |= isa<SCEVConstant>(S);
2898       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2899     }
2900 
2901     bool isDone() const {
2902       return FoundConstant;
2903     }
2904   };
2905 
2906   FindConstantInAddMulChain F;
2907   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2908   ST.visitAll(StartExpr);
2909   return F.FoundConstant;
2910 }
2911 
2912 /// Get a canonical multiply expression, or something simpler if possible.
2913 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2914                                         SCEV::NoWrapFlags OrigFlags,
2915                                         unsigned Depth) {
2916   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2917          "only nuw or nsw allowed");
2918   assert(!Ops.empty() && "Cannot get empty mul!");
2919   if (Ops.size() == 1) return Ops[0];
2920 #ifndef NDEBUG
2921   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2922   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2923     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2924            "SCEVMulExpr operand types don't match!");
2925 #endif
2926 
2927   // Sort by complexity, this groups all similar expression types together.
2928   GroupByComplexity(Ops, &LI, DT);
2929 
2930   // If there are any constants, fold them together.
2931   unsigned Idx = 0;
2932   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2933     ++Idx;
2934     assert(Idx < Ops.size());
2935     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2936       // We found two constants, fold them together!
2937       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2938       if (Ops.size() == 2) return Ops[0];
2939       Ops.erase(Ops.begin()+1);  // Erase the folded element
2940       LHSC = cast<SCEVConstant>(Ops[0]);
2941     }
2942 
2943     // If we have a multiply of zero, it will always be zero.
2944     if (LHSC->getValue()->isZero())
2945       return LHSC;
2946 
2947     // If we are left with a constant one being multiplied, strip it off.
2948     if (LHSC->getValue()->isOne()) {
2949       Ops.erase(Ops.begin());
2950       --Idx;
2951     }
2952 
2953     if (Ops.size() == 1)
2954       return Ops[0];
2955   }
2956 
2957   // Delay expensive flag strengthening until necessary.
2958   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2959     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2960   };
2961 
2962   // Limit recursion calls depth.
2963   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2964     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2965 
2966   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2967     // Don't strengthen flags if we have no new information.
2968     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2969     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2970       Mul->setNoWrapFlags(ComputeFlags(Ops));
2971     return S;
2972   }
2973 
2974   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2975     if (Ops.size() == 2) {
2976       // C1*(C2+V) -> C1*C2 + C1*V
2977       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2978         // If any of Add's ops are Adds or Muls with a constant, apply this
2979         // transformation as well.
2980         //
2981         // TODO: There are some cases where this transformation is not
2982         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2983         // this transformation should be narrowed down.
2984         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2985           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2986                                        SCEV::FlagAnyWrap, Depth + 1),
2987                             getMulExpr(LHSC, Add->getOperand(1),
2988                                        SCEV::FlagAnyWrap, Depth + 1),
2989                             SCEV::FlagAnyWrap, Depth + 1);
2990 
2991       if (Ops[0]->isAllOnesValue()) {
2992         // If we have a mul by -1 of an add, try distributing the -1 among the
2993         // add operands.
2994         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2995           SmallVector<const SCEV *, 4> NewOps;
2996           bool AnyFolded = false;
2997           for (const SCEV *AddOp : Add->operands()) {
2998             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2999                                          Depth + 1);
3000             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3001             NewOps.push_back(Mul);
3002           }
3003           if (AnyFolded)
3004             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3005         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3006           // Negation preserves a recurrence's no self-wrap property.
3007           SmallVector<const SCEV *, 4> Operands;
3008           for (const SCEV *AddRecOp : AddRec->operands())
3009             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3010                                           Depth + 1));
3011 
3012           return getAddRecExpr(Operands, AddRec->getLoop(),
3013                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3014         }
3015       }
3016     }
3017   }
3018 
3019   // Skip over the add expression until we get to a multiply.
3020   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3021     ++Idx;
3022 
3023   // If there are mul operands inline them all into this expression.
3024   if (Idx < Ops.size()) {
3025     bool DeletedMul = false;
3026     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3027       if (Ops.size() > MulOpsInlineThreshold)
3028         break;
3029       // If we have an mul, expand the mul operands onto the end of the
3030       // operands list.
3031       Ops.erase(Ops.begin()+Idx);
3032       Ops.append(Mul->op_begin(), Mul->op_end());
3033       DeletedMul = true;
3034     }
3035 
3036     // If we deleted at least one mul, we added operands to the end of the
3037     // list, and they are not necessarily sorted.  Recurse to resort and
3038     // resimplify any operands we just acquired.
3039     if (DeletedMul)
3040       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3041   }
3042 
3043   // If there are any add recurrences in the operands list, see if any other
3044   // added values are loop invariant.  If so, we can fold them into the
3045   // recurrence.
3046   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3047     ++Idx;
3048 
3049   // Scan over all recurrences, trying to fold loop invariants into them.
3050   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3051     // Scan all of the other operands to this mul and add them to the vector
3052     // if they are loop invariant w.r.t. the recurrence.
3053     SmallVector<const SCEV *, 8> LIOps;
3054     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3055     const Loop *AddRecLoop = AddRec->getLoop();
3056     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3057       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3058         LIOps.push_back(Ops[i]);
3059         Ops.erase(Ops.begin()+i);
3060         --i; --e;
3061       }
3062 
3063     // If we found some loop invariants, fold them into the recurrence.
3064     if (!LIOps.empty()) {
3065       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3066       SmallVector<const SCEV *, 4> NewOps;
3067       NewOps.reserve(AddRec->getNumOperands());
3068       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3069       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3070         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3071                                     SCEV::FlagAnyWrap, Depth + 1));
3072 
3073       // Build the new addrec. Propagate the NUW and NSW flags if both the
3074       // outer mul and the inner addrec are guaranteed to have no overflow.
3075       //
3076       // No self-wrap cannot be guaranteed after changing the step size, but
3077       // will be inferred if either NUW or NSW is true.
3078       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3079       const SCEV *NewRec = getAddRecExpr(
3080           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3081 
3082       // If all of the other operands were loop invariant, we are done.
3083       if (Ops.size() == 1) return NewRec;
3084 
3085       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3086       for (unsigned i = 0;; ++i)
3087         if (Ops[i] == AddRec) {
3088           Ops[i] = NewRec;
3089           break;
3090         }
3091       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3092     }
3093 
3094     // Okay, if there weren't any loop invariants to be folded, check to see
3095     // if there are multiple AddRec's with the same loop induction variable
3096     // being multiplied together.  If so, we can fold them.
3097 
3098     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3099     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3100     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3101     //   ]]],+,...up to x=2n}.
3102     // Note that the arguments to choose() are always integers with values
3103     // known at compile time, never SCEV objects.
3104     //
3105     // The implementation avoids pointless extra computations when the two
3106     // addrec's are of different length (mathematically, it's equivalent to
3107     // an infinite stream of zeros on the right).
3108     bool OpsModified = false;
3109     for (unsigned OtherIdx = Idx+1;
3110          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3111          ++OtherIdx) {
3112       const SCEVAddRecExpr *OtherAddRec =
3113         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3114       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3115         continue;
3116 
3117       // Limit max number of arguments to avoid creation of unreasonably big
3118       // SCEVAddRecs with very complex operands.
3119       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3120           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3121         continue;
3122 
3123       bool Overflow = false;
3124       Type *Ty = AddRec->getType();
3125       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3126       SmallVector<const SCEV*, 7> AddRecOps;
3127       for (int x = 0, xe = AddRec->getNumOperands() +
3128              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3129         SmallVector <const SCEV *, 7> SumOps;
3130         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3131           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3132           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3133                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3134                z < ze && !Overflow; ++z) {
3135             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3136             uint64_t Coeff;
3137             if (LargerThan64Bits)
3138               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3139             else
3140               Coeff = Coeff1*Coeff2;
3141             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3142             const SCEV *Term1 = AddRec->getOperand(y-z);
3143             const SCEV *Term2 = OtherAddRec->getOperand(z);
3144             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3145                                         SCEV::FlagAnyWrap, Depth + 1));
3146           }
3147         }
3148         if (SumOps.empty())
3149           SumOps.push_back(getZero(Ty));
3150         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3151       }
3152       if (!Overflow) {
3153         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3154                                               SCEV::FlagAnyWrap);
3155         if (Ops.size() == 2) return NewAddRec;
3156         Ops[Idx] = NewAddRec;
3157         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3158         OpsModified = true;
3159         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3160         if (!AddRec)
3161           break;
3162       }
3163     }
3164     if (OpsModified)
3165       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3166 
3167     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3168     // next one.
3169   }
3170 
3171   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3172   // already have one, otherwise create a new one.
3173   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3174 }
3175 
3176 /// Represents an unsigned remainder expression based on unsigned division.
3177 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3178                                          const SCEV *RHS) {
3179   assert(getEffectiveSCEVType(LHS->getType()) ==
3180          getEffectiveSCEVType(RHS->getType()) &&
3181          "SCEVURemExpr operand types don't match!");
3182 
3183   // Short-circuit easy cases
3184   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3185     // If constant is one, the result is trivial
3186     if (RHSC->getValue()->isOne())
3187       return getZero(LHS->getType()); // X urem 1 --> 0
3188 
3189     // If constant is a power of two, fold into a zext(trunc(LHS)).
3190     if (RHSC->getAPInt().isPowerOf2()) {
3191       Type *FullTy = LHS->getType();
3192       Type *TruncTy =
3193           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3194       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3195     }
3196   }
3197 
3198   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3199   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3200   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3201   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3202 }
3203 
3204 /// Get a canonical unsigned division expression, or something simpler if
3205 /// possible.
3206 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3207                                          const SCEV *RHS) {
3208   assert(getEffectiveSCEVType(LHS->getType()) ==
3209          getEffectiveSCEVType(RHS->getType()) &&
3210          "SCEVUDivExpr operand types don't match!");
3211 
3212   FoldingSetNodeID ID;
3213   ID.AddInteger(scUDivExpr);
3214   ID.AddPointer(LHS);
3215   ID.AddPointer(RHS);
3216   void *IP = nullptr;
3217   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3218     return S;
3219 
3220   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3221     if (RHSC->getValue()->isOne())
3222       return LHS;                               // X udiv 1 --> x
3223     // If the denominator is zero, the result of the udiv is undefined. Don't
3224     // try to analyze it, because the resolution chosen here may differ from
3225     // the resolution chosen in other parts of the compiler.
3226     if (!RHSC->getValue()->isZero()) {
3227       // Determine if the division can be folded into the operands of
3228       // its operands.
3229       // TODO: Generalize this to non-constants by using known-bits information.
3230       Type *Ty = LHS->getType();
3231       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3232       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3233       // For non-power-of-two values, effectively round the value up to the
3234       // nearest power of two.
3235       if (!RHSC->getAPInt().isPowerOf2())
3236         ++MaxShiftAmt;
3237       IntegerType *ExtTy =
3238         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3239       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3240         if (const SCEVConstant *Step =
3241             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3242           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3243           const APInt &StepInt = Step->getAPInt();
3244           const APInt &DivInt = RHSC->getAPInt();
3245           if (!StepInt.urem(DivInt) &&
3246               getZeroExtendExpr(AR, ExtTy) ==
3247               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3248                             getZeroExtendExpr(Step, ExtTy),
3249                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3250             SmallVector<const SCEV *, 4> Operands;
3251             for (const SCEV *Op : AR->operands())
3252               Operands.push_back(getUDivExpr(Op, RHS));
3253             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3254           }
3255           /// Get a canonical UDivExpr for a recurrence.
3256           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3257           // We can currently only fold X%N if X is constant.
3258           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3259           if (StartC && !DivInt.urem(StepInt) &&
3260               getZeroExtendExpr(AR, ExtTy) ==
3261               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3262                             getZeroExtendExpr(Step, ExtTy),
3263                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3264             const APInt &StartInt = StartC->getAPInt();
3265             const APInt &StartRem = StartInt.urem(StepInt);
3266             if (StartRem != 0) {
3267               const SCEV *NewLHS =
3268                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3269                                 AR->getLoop(), SCEV::FlagNW);
3270               if (LHS != NewLHS) {
3271                 LHS = NewLHS;
3272 
3273                 // Reset the ID to include the new LHS, and check if it is
3274                 // already cached.
3275                 ID.clear();
3276                 ID.AddInteger(scUDivExpr);
3277                 ID.AddPointer(LHS);
3278                 ID.AddPointer(RHS);
3279                 IP = nullptr;
3280                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3281                   return S;
3282               }
3283             }
3284           }
3285         }
3286       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3287       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3288         SmallVector<const SCEV *, 4> Operands;
3289         for (const SCEV *Op : M->operands())
3290           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3291         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3292           // Find an operand that's safely divisible.
3293           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3294             const SCEV *Op = M->getOperand(i);
3295             const SCEV *Div = getUDivExpr(Op, RHSC);
3296             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3297               Operands = SmallVector<const SCEV *, 4>(M->operands());
3298               Operands[i] = Div;
3299               return getMulExpr(Operands);
3300             }
3301           }
3302       }
3303 
3304       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3305       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3306         if (auto *DivisorConstant =
3307                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3308           bool Overflow = false;
3309           APInt NewRHS =
3310               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3311           if (Overflow) {
3312             return getConstant(RHSC->getType(), 0, false);
3313           }
3314           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3315         }
3316       }
3317 
3318       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3319       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3320         SmallVector<const SCEV *, 4> Operands;
3321         for (const SCEV *Op : A->operands())
3322           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3323         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3324           Operands.clear();
3325           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3326             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3327             if (isa<SCEVUDivExpr>(Op) ||
3328                 getMulExpr(Op, RHS) != A->getOperand(i))
3329               break;
3330             Operands.push_back(Op);
3331           }
3332           if (Operands.size() == A->getNumOperands())
3333             return getAddExpr(Operands);
3334         }
3335       }
3336 
3337       // Fold if both operands are constant.
3338       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3339         Constant *LHSCV = LHSC->getValue();
3340         Constant *RHSCV = RHSC->getValue();
3341         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3342                                                                    RHSCV)));
3343       }
3344     }
3345   }
3346 
3347   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3348   // changes). Make sure we get a new one.
3349   IP = nullptr;
3350   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3351   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3352                                              LHS, RHS);
3353   UniqueSCEVs.InsertNode(S, IP);
3354   addToLoopUseLists(S);
3355   return S;
3356 }
3357 
3358 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3359   APInt A = C1->getAPInt().abs();
3360   APInt B = C2->getAPInt().abs();
3361   uint32_t ABW = A.getBitWidth();
3362   uint32_t BBW = B.getBitWidth();
3363 
3364   if (ABW > BBW)
3365     B = B.zext(ABW);
3366   else if (ABW < BBW)
3367     A = A.zext(BBW);
3368 
3369   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3370 }
3371 
3372 /// Get a canonical unsigned division expression, or something simpler if
3373 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3374 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3375 /// it's not exact because the udiv may be clearing bits.
3376 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3377                                               const SCEV *RHS) {
3378   // TODO: we could try to find factors in all sorts of things, but for now we
3379   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3380   // end of this file for inspiration.
3381 
3382   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3383   if (!Mul || !Mul->hasNoUnsignedWrap())
3384     return getUDivExpr(LHS, RHS);
3385 
3386   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3387     // If the mulexpr multiplies by a constant, then that constant must be the
3388     // first element of the mulexpr.
3389     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3390       if (LHSCst == RHSCst) {
3391         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3392         return getMulExpr(Operands);
3393       }
3394 
3395       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3396       // that there's a factor provided by one of the other terms. We need to
3397       // check.
3398       APInt Factor = gcd(LHSCst, RHSCst);
3399       if (!Factor.isIntN(1)) {
3400         LHSCst =
3401             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3402         RHSCst =
3403             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3404         SmallVector<const SCEV *, 2> Operands;
3405         Operands.push_back(LHSCst);
3406         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3407         LHS = getMulExpr(Operands);
3408         RHS = RHSCst;
3409         Mul = dyn_cast<SCEVMulExpr>(LHS);
3410         if (!Mul)
3411           return getUDivExactExpr(LHS, RHS);
3412       }
3413     }
3414   }
3415 
3416   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3417     if (Mul->getOperand(i) == RHS) {
3418       SmallVector<const SCEV *, 2> Operands;
3419       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3420       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3421       return getMulExpr(Operands);
3422     }
3423   }
3424 
3425   return getUDivExpr(LHS, RHS);
3426 }
3427 
3428 /// Get an add recurrence expression for the specified loop.  Simplify the
3429 /// expression as much as possible.
3430 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3431                                            const Loop *L,
3432                                            SCEV::NoWrapFlags Flags) {
3433   SmallVector<const SCEV *, 4> Operands;
3434   Operands.push_back(Start);
3435   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3436     if (StepChrec->getLoop() == L) {
3437       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3438       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3439     }
3440 
3441   Operands.push_back(Step);
3442   return getAddRecExpr(Operands, L, Flags);
3443 }
3444 
3445 /// Get an add recurrence expression for the specified loop.  Simplify the
3446 /// expression as much as possible.
3447 const SCEV *
3448 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3449                                const Loop *L, SCEV::NoWrapFlags Flags) {
3450   if (Operands.size() == 1) return Operands[0];
3451 #ifndef NDEBUG
3452   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3453   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3454     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3455            "SCEVAddRecExpr operand types don't match!");
3456   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3457     assert(isLoopInvariant(Operands[i], L) &&
3458            "SCEVAddRecExpr operand is not loop-invariant!");
3459 #endif
3460 
3461   if (Operands.back()->isZero()) {
3462     Operands.pop_back();
3463     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3464   }
3465 
3466   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3467   // use that information to infer NUW and NSW flags. However, computing a
3468   // BE count requires calling getAddRecExpr, so we may not yet have a
3469   // meaningful BE count at this point (and if we don't, we'd be stuck
3470   // with a SCEVCouldNotCompute as the cached BE count).
3471 
3472   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3473 
3474   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3475   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3476     const Loop *NestedLoop = NestedAR->getLoop();
3477     if (L->contains(NestedLoop)
3478             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3479             : (!NestedLoop->contains(L) &&
3480                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3481       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3482       Operands[0] = NestedAR->getStart();
3483       // AddRecs require their operands be loop-invariant with respect to their
3484       // loops. Don't perform this transformation if it would break this
3485       // requirement.
3486       bool AllInvariant = all_of(
3487           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3488 
3489       if (AllInvariant) {
3490         // Create a recurrence for the outer loop with the same step size.
3491         //
3492         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3493         // inner recurrence has the same property.
3494         SCEV::NoWrapFlags OuterFlags =
3495           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3496 
3497         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3498         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3499           return isLoopInvariant(Op, NestedLoop);
3500         });
3501 
3502         if (AllInvariant) {
3503           // Ok, both add recurrences are valid after the transformation.
3504           //
3505           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3506           // the outer recurrence has the same property.
3507           SCEV::NoWrapFlags InnerFlags =
3508             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3509           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3510         }
3511       }
3512       // Reset Operands to its original state.
3513       Operands[0] = NestedAR;
3514     }
3515   }
3516 
3517   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3518   // already have one, otherwise create a new one.
3519   return getOrCreateAddRecExpr(Operands, L, Flags);
3520 }
3521 
3522 const SCEV *
3523 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3524                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3525   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3526   // getSCEV(Base)->getType() has the same address space as Base->getType()
3527   // because SCEV::getType() preserves the address space.
3528   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3529   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3530   // instruction to its SCEV, because the Instruction may be guarded by control
3531   // flow and the no-overflow bits may not be valid for the expression in any
3532   // context. This can be fixed similarly to how these flags are handled for
3533   // adds.
3534   SCEV::NoWrapFlags OffsetWrap =
3535       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3536 
3537   Type *CurTy = GEP->getType();
3538   bool FirstIter = true;
3539   SmallVector<const SCEV *, 4> Offsets;
3540   for (const SCEV *IndexExpr : IndexExprs) {
3541     // Compute the (potentially symbolic) offset in bytes for this index.
3542     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3543       // For a struct, add the member offset.
3544       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3545       unsigned FieldNo = Index->getZExtValue();
3546       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3547       Offsets.push_back(FieldOffset);
3548 
3549       // Update CurTy to the type of the field at Index.
3550       CurTy = STy->getTypeAtIndex(Index);
3551     } else {
3552       // Update CurTy to its element type.
3553       if (FirstIter) {
3554         assert(isa<PointerType>(CurTy) &&
3555                "The first index of a GEP indexes a pointer");
3556         CurTy = GEP->getSourceElementType();
3557         FirstIter = false;
3558       } else {
3559         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3560       }
3561       // For an array, add the element offset, explicitly scaled.
3562       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3563       // Getelementptr indices are signed.
3564       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3565 
3566       // Multiply the index by the element size to compute the element offset.
3567       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3568       Offsets.push_back(LocalOffset);
3569     }
3570   }
3571 
3572   // Handle degenerate case of GEP without offsets.
3573   if (Offsets.empty())
3574     return BaseExpr;
3575 
3576   // Add the offsets together, assuming nsw if inbounds.
3577   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3578   // Add the base address and the offset. We cannot use the nsw flag, as the
3579   // base address is unsigned. However, if we know that the offset is
3580   // non-negative, we can use nuw.
3581   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3582                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3583   return getAddExpr(BaseExpr, Offset, BaseWrap);
3584 }
3585 
3586 std::tuple<SCEV *, FoldingSetNodeID, void *>
3587 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3588                                          ArrayRef<const SCEV *> Ops) {
3589   FoldingSetNodeID ID;
3590   void *IP = nullptr;
3591   ID.AddInteger(SCEVType);
3592   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3593     ID.AddPointer(Ops[i]);
3594   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3595       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3596 }
3597 
3598 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3599   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3600   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3601 }
3602 
3603 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3604                                            SmallVectorImpl<const SCEV *> &Ops) {
3605   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3606   if (Ops.size() == 1) return Ops[0];
3607 #ifndef NDEBUG
3608   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3609   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3610     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3611            "Operand types don't match!");
3612 #endif
3613 
3614   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3615   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3616 
3617   // Sort by complexity, this groups all similar expression types together.
3618   GroupByComplexity(Ops, &LI, DT);
3619 
3620   // Check if we have created the same expression before.
3621   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3622     return S;
3623   }
3624 
3625   // If there are any constants, fold them together.
3626   unsigned Idx = 0;
3627   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3628     ++Idx;
3629     assert(Idx < Ops.size());
3630     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3631       if (Kind == scSMaxExpr)
3632         return APIntOps::smax(LHS, RHS);
3633       else if (Kind == scSMinExpr)
3634         return APIntOps::smin(LHS, RHS);
3635       else if (Kind == scUMaxExpr)
3636         return APIntOps::umax(LHS, RHS);
3637       else if (Kind == scUMinExpr)
3638         return APIntOps::umin(LHS, RHS);
3639       llvm_unreachable("Unknown SCEV min/max opcode");
3640     };
3641 
3642     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3643       // We found two constants, fold them together!
3644       ConstantInt *Fold = ConstantInt::get(
3645           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3646       Ops[0] = getConstant(Fold);
3647       Ops.erase(Ops.begin()+1);  // Erase the folded element
3648       if (Ops.size() == 1) return Ops[0];
3649       LHSC = cast<SCEVConstant>(Ops[0]);
3650     }
3651 
3652     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3653     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3654 
3655     if (IsMax ? IsMinV : IsMaxV) {
3656       // If we are left with a constant minimum(/maximum)-int, strip it off.
3657       Ops.erase(Ops.begin());
3658       --Idx;
3659     } else if (IsMax ? IsMaxV : IsMinV) {
3660       // If we have a max(/min) with a constant maximum(/minimum)-int,
3661       // it will always be the extremum.
3662       return LHSC;
3663     }
3664 
3665     if (Ops.size() == 1) return Ops[0];
3666   }
3667 
3668   // Find the first operation of the same kind
3669   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3670     ++Idx;
3671 
3672   // Check to see if one of the operands is of the same kind. If so, expand its
3673   // operands onto our operand list, and recurse to simplify.
3674   if (Idx < Ops.size()) {
3675     bool DeletedAny = false;
3676     while (Ops[Idx]->getSCEVType() == Kind) {
3677       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3678       Ops.erase(Ops.begin()+Idx);
3679       Ops.append(SMME->op_begin(), SMME->op_end());
3680       DeletedAny = true;
3681     }
3682 
3683     if (DeletedAny)
3684       return getMinMaxExpr(Kind, Ops);
3685   }
3686 
3687   // Okay, check to see if the same value occurs in the operand list twice.  If
3688   // so, delete one.  Since we sorted the list, these values are required to
3689   // be adjacent.
3690   llvm::CmpInst::Predicate GEPred =
3691       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3692   llvm::CmpInst::Predicate LEPred =
3693       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3694   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3695   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3696   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3697     if (Ops[i] == Ops[i + 1] ||
3698         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3699       //  X op Y op Y  -->  X op Y
3700       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3701       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3702       --i;
3703       --e;
3704     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3705                                                Ops[i + 1])) {
3706       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3707       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3708       --i;
3709       --e;
3710     }
3711   }
3712 
3713   if (Ops.size() == 1) return Ops[0];
3714 
3715   assert(!Ops.empty() && "Reduced smax down to nothing!");
3716 
3717   // Okay, it looks like we really DO need an expr.  Check to see if we
3718   // already have one, otherwise create a new one.
3719   const SCEV *ExistingSCEV;
3720   FoldingSetNodeID ID;
3721   void *IP;
3722   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3723   if (ExistingSCEV)
3724     return ExistingSCEV;
3725   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3726   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3727   SCEV *S = new (SCEVAllocator)
3728       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3729 
3730   UniqueSCEVs.InsertNode(S, IP);
3731   addToLoopUseLists(S);
3732   return S;
3733 }
3734 
3735 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3736   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3737   return getSMaxExpr(Ops);
3738 }
3739 
3740 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3741   return getMinMaxExpr(scSMaxExpr, Ops);
3742 }
3743 
3744 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3745   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3746   return getUMaxExpr(Ops);
3747 }
3748 
3749 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3750   return getMinMaxExpr(scUMaxExpr, Ops);
3751 }
3752 
3753 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3754                                          const SCEV *RHS) {
3755   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3756   return getSMinExpr(Ops);
3757 }
3758 
3759 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3760   return getMinMaxExpr(scSMinExpr, Ops);
3761 }
3762 
3763 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3764                                          const SCEV *RHS) {
3765   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3766   return getUMinExpr(Ops);
3767 }
3768 
3769 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3770   return getMinMaxExpr(scUMinExpr, Ops);
3771 }
3772 
3773 const SCEV *
3774 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3775                                              ScalableVectorType *ScalableTy) {
3776   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3777   Constant *One = ConstantInt::get(IntTy, 1);
3778   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3779   // Note that the expression we created is the final expression, we don't
3780   // want to simplify it any further Also, if we call a normal getSCEV(),
3781   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3782   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3783 }
3784 
3785 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3786   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3787     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3788   // We can bypass creating a target-independent constant expression and then
3789   // folding it back into a ConstantInt. This is just a compile-time
3790   // optimization.
3791   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3792 }
3793 
3794 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3795   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3796     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3797   // We can bypass creating a target-independent constant expression and then
3798   // folding it back into a ConstantInt. This is just a compile-time
3799   // optimization.
3800   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3801 }
3802 
3803 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3804                                              StructType *STy,
3805                                              unsigned FieldNo) {
3806   // We can bypass creating a target-independent constant expression and then
3807   // folding it back into a ConstantInt. This is just a compile-time
3808   // optimization.
3809   return getConstant(
3810       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3811 }
3812 
3813 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3814   // Don't attempt to do anything other than create a SCEVUnknown object
3815   // here.  createSCEV only calls getUnknown after checking for all other
3816   // interesting possibilities, and any other code that calls getUnknown
3817   // is doing so in order to hide a value from SCEV canonicalization.
3818 
3819   FoldingSetNodeID ID;
3820   ID.AddInteger(scUnknown);
3821   ID.AddPointer(V);
3822   void *IP = nullptr;
3823   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3824     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3825            "Stale SCEVUnknown in uniquing map!");
3826     return S;
3827   }
3828   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3829                                             FirstUnknown);
3830   FirstUnknown = cast<SCEVUnknown>(S);
3831   UniqueSCEVs.InsertNode(S, IP);
3832   return S;
3833 }
3834 
3835 //===----------------------------------------------------------------------===//
3836 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3837 //
3838 
3839 /// Test if values of the given type are analyzable within the SCEV
3840 /// framework. This primarily includes integer types, and it can optionally
3841 /// include pointer types if the ScalarEvolution class has access to
3842 /// target-specific information.
3843 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3844   // Integers and pointers are always SCEVable.
3845   return Ty->isIntOrPtrTy();
3846 }
3847 
3848 /// Return the size in bits of the specified type, for which isSCEVable must
3849 /// return true.
3850 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3851   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3852   if (Ty->isPointerTy())
3853     return getDataLayout().getIndexTypeSizeInBits(Ty);
3854   return getDataLayout().getTypeSizeInBits(Ty);
3855 }
3856 
3857 /// Return a type with the same bitwidth as the given type and which represents
3858 /// how SCEV will treat the given type, for which isSCEVable must return
3859 /// true. For pointer types, this is the pointer index sized integer type.
3860 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3861   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3862 
3863   if (Ty->isIntegerTy())
3864     return Ty;
3865 
3866   // The only other support type is pointer.
3867   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3868   return getDataLayout().getIndexType(Ty);
3869 }
3870 
3871 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3872   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3873 }
3874 
3875 const SCEV *ScalarEvolution::getCouldNotCompute() {
3876   return CouldNotCompute.get();
3877 }
3878 
3879 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3880   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3881     auto *SU = dyn_cast<SCEVUnknown>(S);
3882     return SU && SU->getValue() == nullptr;
3883   });
3884 
3885   return !ContainsNulls;
3886 }
3887 
3888 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3889   HasRecMapType::iterator I = HasRecMap.find(S);
3890   if (I != HasRecMap.end())
3891     return I->second;
3892 
3893   bool FoundAddRec =
3894       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3895   HasRecMap.insert({S, FoundAddRec});
3896   return FoundAddRec;
3897 }
3898 
3899 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3900 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3901 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3902 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3903   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3904   if (!Add)
3905     return {S, nullptr};
3906 
3907   if (Add->getNumOperands() != 2)
3908     return {S, nullptr};
3909 
3910   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3911   if (!ConstOp)
3912     return {S, nullptr};
3913 
3914   return {Add->getOperand(1), ConstOp->getValue()};
3915 }
3916 
3917 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3918 /// by the value and offset from any ValueOffsetPair in the set.
3919 ScalarEvolution::ValueOffsetPairSetVector *
3920 ScalarEvolution::getSCEVValues(const SCEV *S) {
3921   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3922   if (SI == ExprValueMap.end())
3923     return nullptr;
3924 #ifndef NDEBUG
3925   if (VerifySCEVMap) {
3926     // Check there is no dangling Value in the set returned.
3927     for (const auto &VE : SI->second)
3928       assert(ValueExprMap.count(VE.first));
3929   }
3930 #endif
3931   return &SI->second;
3932 }
3933 
3934 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3935 /// cannot be used separately. eraseValueFromMap should be used to remove
3936 /// V from ValueExprMap and ExprValueMap at the same time.
3937 void ScalarEvolution::eraseValueFromMap(Value *V) {
3938   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3939   if (I != ValueExprMap.end()) {
3940     const SCEV *S = I->second;
3941     // Remove {V, 0} from the set of ExprValueMap[S]
3942     if (auto *SV = getSCEVValues(S))
3943       SV->remove({V, nullptr});
3944 
3945     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3946     const SCEV *Stripped;
3947     ConstantInt *Offset;
3948     std::tie(Stripped, Offset) = splitAddExpr(S);
3949     if (Offset != nullptr) {
3950       if (auto *SV = getSCEVValues(Stripped))
3951         SV->remove({V, Offset});
3952     }
3953     ValueExprMap.erase(V);
3954   }
3955 }
3956 
3957 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3958 /// TODO: In reality it is better to check the poison recursively
3959 /// but this is better than nothing.
3960 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3961   if (auto *I = dyn_cast<Instruction>(V)) {
3962     if (isa<OverflowingBinaryOperator>(I)) {
3963       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3964         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3965           return true;
3966         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3967           return true;
3968       }
3969     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3970       return true;
3971   }
3972   return false;
3973 }
3974 
3975 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3976 /// create a new one.
3977 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3978   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3979 
3980   const SCEV *S = getExistingSCEV(V);
3981   if (S == nullptr) {
3982     S = createSCEV(V);
3983     // During PHI resolution, it is possible to create two SCEVs for the same
3984     // V, so it is needed to double check whether V->S is inserted into
3985     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3986     std::pair<ValueExprMapType::iterator, bool> Pair =
3987         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3988     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3989       ExprValueMap[S].insert({V, nullptr});
3990 
3991       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3992       // ExprValueMap.
3993       const SCEV *Stripped = S;
3994       ConstantInt *Offset = nullptr;
3995       std::tie(Stripped, Offset) = splitAddExpr(S);
3996       // If stripped is SCEVUnknown, don't bother to save
3997       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3998       // increase the complexity of the expansion code.
3999       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
4000       // because it may generate add/sub instead of GEP in SCEV expansion.
4001       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
4002           !isa<GetElementPtrInst>(V))
4003         ExprValueMap[Stripped].insert({V, Offset});
4004     }
4005   }
4006   return S;
4007 }
4008 
4009 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4010   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4011 
4012   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4013   if (I != ValueExprMap.end()) {
4014     const SCEV *S = I->second;
4015     if (checkValidity(S))
4016       return S;
4017     eraseValueFromMap(V);
4018     forgetMemoizedResults(S);
4019   }
4020   return nullptr;
4021 }
4022 
4023 /// Return a SCEV corresponding to -V = -1*V
4024 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4025                                              SCEV::NoWrapFlags Flags) {
4026   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4027     return getConstant(
4028                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4029 
4030   Type *Ty = V->getType();
4031   Ty = getEffectiveSCEVType(Ty);
4032   return getMulExpr(V, getMinusOne(Ty), Flags);
4033 }
4034 
4035 /// If Expr computes ~A, return A else return nullptr
4036 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4037   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4038   if (!Add || Add->getNumOperands() != 2 ||
4039       !Add->getOperand(0)->isAllOnesValue())
4040     return nullptr;
4041 
4042   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4043   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4044       !AddRHS->getOperand(0)->isAllOnesValue())
4045     return nullptr;
4046 
4047   return AddRHS->getOperand(1);
4048 }
4049 
4050 /// Return a SCEV corresponding to ~V = -1-V
4051 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4052   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4053     return getConstant(
4054                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4055 
4056   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4057   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4058     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4059       SmallVector<const SCEV *, 2> MatchedOperands;
4060       for (const SCEV *Operand : MME->operands()) {
4061         const SCEV *Matched = MatchNotExpr(Operand);
4062         if (!Matched)
4063           return (const SCEV *)nullptr;
4064         MatchedOperands.push_back(Matched);
4065       }
4066       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4067                            MatchedOperands);
4068     };
4069     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4070       return Replaced;
4071   }
4072 
4073   Type *Ty = V->getType();
4074   Ty = getEffectiveSCEVType(Ty);
4075   return getMinusSCEV(getMinusOne(Ty), V);
4076 }
4077 
4078 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4079                                           SCEV::NoWrapFlags Flags,
4080                                           unsigned Depth) {
4081   // Fast path: X - X --> 0.
4082   if (LHS == RHS)
4083     return getZero(LHS->getType());
4084 
4085   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4086   // makes it so that we cannot make much use of NUW.
4087   auto AddFlags = SCEV::FlagAnyWrap;
4088   const bool RHSIsNotMinSigned =
4089       !getSignedRangeMin(RHS).isMinSignedValue();
4090   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4091     // Let M be the minimum representable signed value. Then (-1)*RHS
4092     // signed-wraps if and only if RHS is M. That can happen even for
4093     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4094     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4095     // (-1)*RHS, we need to prove that RHS != M.
4096     //
4097     // If LHS is non-negative and we know that LHS - RHS does not
4098     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4099     // either by proving that RHS > M or that LHS >= 0.
4100     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4101       AddFlags = SCEV::FlagNSW;
4102     }
4103   }
4104 
4105   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4106   // RHS is NSW and LHS >= 0.
4107   //
4108   // The difficulty here is that the NSW flag may have been proven
4109   // relative to a loop that is to be found in a recurrence in LHS and
4110   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4111   // larger scope than intended.
4112   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4113 
4114   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4115 }
4116 
4117 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4118                                                      unsigned Depth) {
4119   Type *SrcTy = V->getType();
4120   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4121          "Cannot truncate or zero extend with non-integer arguments!");
4122   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4123     return V;  // No conversion
4124   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4125     return getTruncateExpr(V, Ty, Depth);
4126   return getZeroExtendExpr(V, Ty, Depth);
4127 }
4128 
4129 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4130                                                      unsigned Depth) {
4131   Type *SrcTy = V->getType();
4132   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4133          "Cannot truncate or zero extend with non-integer arguments!");
4134   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4135     return V;  // No conversion
4136   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4137     return getTruncateExpr(V, Ty, Depth);
4138   return getSignExtendExpr(V, Ty, Depth);
4139 }
4140 
4141 const SCEV *
4142 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4143   Type *SrcTy = V->getType();
4144   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4145          "Cannot noop or zero extend with non-integer arguments!");
4146   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4147          "getNoopOrZeroExtend cannot truncate!");
4148   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4149     return V;  // No conversion
4150   return getZeroExtendExpr(V, Ty);
4151 }
4152 
4153 const SCEV *
4154 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4155   Type *SrcTy = V->getType();
4156   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4157          "Cannot noop or sign extend with non-integer arguments!");
4158   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4159          "getNoopOrSignExtend cannot truncate!");
4160   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4161     return V;  // No conversion
4162   return getSignExtendExpr(V, Ty);
4163 }
4164 
4165 const SCEV *
4166 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4167   Type *SrcTy = V->getType();
4168   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4169          "Cannot noop or any extend with non-integer arguments!");
4170   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4171          "getNoopOrAnyExtend cannot truncate!");
4172   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4173     return V;  // No conversion
4174   return getAnyExtendExpr(V, Ty);
4175 }
4176 
4177 const SCEV *
4178 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4179   Type *SrcTy = V->getType();
4180   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4181          "Cannot truncate or noop with non-integer arguments!");
4182   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4183          "getTruncateOrNoop cannot extend!");
4184   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4185     return V;  // No conversion
4186   return getTruncateExpr(V, Ty);
4187 }
4188 
4189 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4190                                                         const SCEV *RHS) {
4191   const SCEV *PromotedLHS = LHS;
4192   const SCEV *PromotedRHS = RHS;
4193 
4194   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4195     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4196   else
4197     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4198 
4199   return getUMaxExpr(PromotedLHS, PromotedRHS);
4200 }
4201 
4202 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4203                                                         const SCEV *RHS) {
4204   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4205   return getUMinFromMismatchedTypes(Ops);
4206 }
4207 
4208 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4209     SmallVectorImpl<const SCEV *> &Ops) {
4210   assert(!Ops.empty() && "At least one operand must be!");
4211   // Trivial case.
4212   if (Ops.size() == 1)
4213     return Ops[0];
4214 
4215   // Find the max type first.
4216   Type *MaxType = nullptr;
4217   for (auto *S : Ops)
4218     if (MaxType)
4219       MaxType = getWiderType(MaxType, S->getType());
4220     else
4221       MaxType = S->getType();
4222   assert(MaxType && "Failed to find maximum type!");
4223 
4224   // Extend all ops to max type.
4225   SmallVector<const SCEV *, 2> PromotedOps;
4226   for (auto *S : Ops)
4227     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4228 
4229   // Generate umin.
4230   return getUMinExpr(PromotedOps);
4231 }
4232 
4233 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4234   // A pointer operand may evaluate to a nonpointer expression, such as null.
4235   if (!V->getType()->isPointerTy())
4236     return V;
4237 
4238   while (true) {
4239     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4240       V = Cast->getOperand();
4241     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4242       const SCEV *PtrOp = nullptr;
4243       for (const SCEV *NAryOp : NAry->operands()) {
4244         if (NAryOp->getType()->isPointerTy()) {
4245           // Cannot find the base of an expression with multiple pointer ops.
4246           if (PtrOp)
4247             return V;
4248           PtrOp = NAryOp;
4249         }
4250       }
4251       if (!PtrOp) // All operands were non-pointer.
4252         return V;
4253       V = PtrOp;
4254     } else // Not something we can look further into.
4255       return V;
4256   }
4257 }
4258 
4259 /// Push users of the given Instruction onto the given Worklist.
4260 static void
4261 PushDefUseChildren(Instruction *I,
4262                    SmallVectorImpl<Instruction *> &Worklist) {
4263   // Push the def-use children onto the Worklist stack.
4264   for (User *U : I->users())
4265     Worklist.push_back(cast<Instruction>(U));
4266 }
4267 
4268 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4269   SmallVector<Instruction *, 16> Worklist;
4270   PushDefUseChildren(PN, Worklist);
4271 
4272   SmallPtrSet<Instruction *, 8> Visited;
4273   Visited.insert(PN);
4274   while (!Worklist.empty()) {
4275     Instruction *I = Worklist.pop_back_val();
4276     if (!Visited.insert(I).second)
4277       continue;
4278 
4279     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4280     if (It != ValueExprMap.end()) {
4281       const SCEV *Old = It->second;
4282 
4283       // Short-circuit the def-use traversal if the symbolic name
4284       // ceases to appear in expressions.
4285       if (Old != SymName && !hasOperand(Old, SymName))
4286         continue;
4287 
4288       // SCEVUnknown for a PHI either means that it has an unrecognized
4289       // structure, it's a PHI that's in the progress of being computed
4290       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4291       // additional loop trip count information isn't going to change anything.
4292       // In the second case, createNodeForPHI will perform the necessary
4293       // updates on its own when it gets to that point. In the third, we do
4294       // want to forget the SCEVUnknown.
4295       if (!isa<PHINode>(I) ||
4296           !isa<SCEVUnknown>(Old) ||
4297           (I != PN && Old == SymName)) {
4298         eraseValueFromMap(It->first);
4299         forgetMemoizedResults(Old);
4300       }
4301     }
4302 
4303     PushDefUseChildren(I, Worklist);
4304   }
4305 }
4306 
4307 namespace {
4308 
4309 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4310 /// expression in case its Loop is L. If it is not L then
4311 /// if IgnoreOtherLoops is true then use AddRec itself
4312 /// otherwise rewrite cannot be done.
4313 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4314 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4315 public:
4316   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4317                              bool IgnoreOtherLoops = true) {
4318     SCEVInitRewriter Rewriter(L, SE);
4319     const SCEV *Result = Rewriter.visit(S);
4320     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4321       return SE.getCouldNotCompute();
4322     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4323                ? SE.getCouldNotCompute()
4324                : Result;
4325   }
4326 
4327   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4328     if (!SE.isLoopInvariant(Expr, L))
4329       SeenLoopVariantSCEVUnknown = true;
4330     return Expr;
4331   }
4332 
4333   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4334     // Only re-write AddRecExprs for this loop.
4335     if (Expr->getLoop() == L)
4336       return Expr->getStart();
4337     SeenOtherLoops = true;
4338     return Expr;
4339   }
4340 
4341   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4342 
4343   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4344 
4345 private:
4346   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4347       : SCEVRewriteVisitor(SE), L(L) {}
4348 
4349   const Loop *L;
4350   bool SeenLoopVariantSCEVUnknown = false;
4351   bool SeenOtherLoops = false;
4352 };
4353 
4354 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4355 /// increment expression in case its Loop is L. If it is not L then
4356 /// use AddRec itself.
4357 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4358 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4359 public:
4360   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4361     SCEVPostIncRewriter Rewriter(L, SE);
4362     const SCEV *Result = Rewriter.visit(S);
4363     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4364         ? SE.getCouldNotCompute()
4365         : Result;
4366   }
4367 
4368   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4369     if (!SE.isLoopInvariant(Expr, L))
4370       SeenLoopVariantSCEVUnknown = true;
4371     return Expr;
4372   }
4373 
4374   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4375     // Only re-write AddRecExprs for this loop.
4376     if (Expr->getLoop() == L)
4377       return Expr->getPostIncExpr(SE);
4378     SeenOtherLoops = true;
4379     return Expr;
4380   }
4381 
4382   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4383 
4384   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4385 
4386 private:
4387   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4388       : SCEVRewriteVisitor(SE), L(L) {}
4389 
4390   const Loop *L;
4391   bool SeenLoopVariantSCEVUnknown = false;
4392   bool SeenOtherLoops = false;
4393 };
4394 
4395 /// This class evaluates the compare condition by matching it against the
4396 /// condition of loop latch. If there is a match we assume a true value
4397 /// for the condition while building SCEV nodes.
4398 class SCEVBackedgeConditionFolder
4399     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4400 public:
4401   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4402                              ScalarEvolution &SE) {
4403     bool IsPosBECond = false;
4404     Value *BECond = nullptr;
4405     if (BasicBlock *Latch = L->getLoopLatch()) {
4406       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4407       if (BI && BI->isConditional()) {
4408         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4409                "Both outgoing branches should not target same header!");
4410         BECond = BI->getCondition();
4411         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4412       } else {
4413         return S;
4414       }
4415     }
4416     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4417     return Rewriter.visit(S);
4418   }
4419 
4420   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4421     const SCEV *Result = Expr;
4422     bool InvariantF = SE.isLoopInvariant(Expr, L);
4423 
4424     if (!InvariantF) {
4425       Instruction *I = cast<Instruction>(Expr->getValue());
4426       switch (I->getOpcode()) {
4427       case Instruction::Select: {
4428         SelectInst *SI = cast<SelectInst>(I);
4429         Optional<const SCEV *> Res =
4430             compareWithBackedgeCondition(SI->getCondition());
4431         if (Res.hasValue()) {
4432           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4433           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4434         }
4435         break;
4436       }
4437       default: {
4438         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4439         if (Res.hasValue())
4440           Result = Res.getValue();
4441         break;
4442       }
4443       }
4444     }
4445     return Result;
4446   }
4447 
4448 private:
4449   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4450                                        bool IsPosBECond, ScalarEvolution &SE)
4451       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4452         IsPositiveBECond(IsPosBECond) {}
4453 
4454   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4455 
4456   const Loop *L;
4457   /// Loop back condition.
4458   Value *BackedgeCond = nullptr;
4459   /// Set to true if loop back is on positive branch condition.
4460   bool IsPositiveBECond;
4461 };
4462 
4463 Optional<const SCEV *>
4464 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4465 
4466   // If value matches the backedge condition for loop latch,
4467   // then return a constant evolution node based on loopback
4468   // branch taken.
4469   if (BackedgeCond == IC)
4470     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4471                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4472   return None;
4473 }
4474 
4475 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4476 public:
4477   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4478                              ScalarEvolution &SE) {
4479     SCEVShiftRewriter Rewriter(L, SE);
4480     const SCEV *Result = Rewriter.visit(S);
4481     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4482   }
4483 
4484   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4485     // Only allow AddRecExprs for this loop.
4486     if (!SE.isLoopInvariant(Expr, L))
4487       Valid = false;
4488     return Expr;
4489   }
4490 
4491   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4492     if (Expr->getLoop() == L && Expr->isAffine())
4493       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4494     Valid = false;
4495     return Expr;
4496   }
4497 
4498   bool isValid() { return Valid; }
4499 
4500 private:
4501   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4502       : SCEVRewriteVisitor(SE), L(L) {}
4503 
4504   const Loop *L;
4505   bool Valid = true;
4506 };
4507 
4508 } // end anonymous namespace
4509 
4510 SCEV::NoWrapFlags
4511 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4512   if (!AR->isAffine())
4513     return SCEV::FlagAnyWrap;
4514 
4515   using OBO = OverflowingBinaryOperator;
4516 
4517   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4518 
4519   if (!AR->hasNoSignedWrap()) {
4520     ConstantRange AddRecRange = getSignedRange(AR);
4521     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4522 
4523     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4524         Instruction::Add, IncRange, OBO::NoSignedWrap);
4525     if (NSWRegion.contains(AddRecRange))
4526       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4527   }
4528 
4529   if (!AR->hasNoUnsignedWrap()) {
4530     ConstantRange AddRecRange = getUnsignedRange(AR);
4531     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4532 
4533     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4534         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4535     if (NUWRegion.contains(AddRecRange))
4536       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4537   }
4538 
4539   return Result;
4540 }
4541 
4542 SCEV::NoWrapFlags
4543 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4544   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4545 
4546   if (AR->hasNoSignedWrap())
4547     return Result;
4548 
4549   if (!AR->isAffine())
4550     return Result;
4551 
4552   const SCEV *Step = AR->getStepRecurrence(*this);
4553   const Loop *L = AR->getLoop();
4554 
4555   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4556   // Note that this serves two purposes: It filters out loops that are
4557   // simply not analyzable, and it covers the case where this code is
4558   // being called from within backedge-taken count analysis, such that
4559   // attempting to ask for the backedge-taken count would likely result
4560   // in infinite recursion. In the later case, the analysis code will
4561   // cope with a conservative value, and it will take care to purge
4562   // that value once it has finished.
4563   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4564 
4565   // Normally, in the cases we can prove no-overflow via a
4566   // backedge guarding condition, we can also compute a backedge
4567   // taken count for the loop.  The exceptions are assumptions and
4568   // guards present in the loop -- SCEV is not great at exploiting
4569   // these to compute max backedge taken counts, but can still use
4570   // these to prove lack of overflow.  Use this fact to avoid
4571   // doing extra work that may not pay off.
4572 
4573   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4574       AC.assumptions().empty())
4575     return Result;
4576 
4577   // If the backedge is guarded by a comparison with the pre-inc  value the
4578   // addrec is safe. Also, if the entry is guarded by a comparison with the
4579   // start value and the backedge is guarded by a comparison with the post-inc
4580   // value, the addrec is safe.
4581   ICmpInst::Predicate Pred;
4582   const SCEV *OverflowLimit =
4583     getSignedOverflowLimitForStep(Step, &Pred, this);
4584   if (OverflowLimit &&
4585       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4586        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4587     Result = setFlags(Result, SCEV::FlagNSW);
4588   }
4589   return Result;
4590 }
4591 SCEV::NoWrapFlags
4592 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4593   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4594 
4595   if (AR->hasNoUnsignedWrap())
4596     return Result;
4597 
4598   if (!AR->isAffine())
4599     return Result;
4600 
4601   const SCEV *Step = AR->getStepRecurrence(*this);
4602   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4603   const Loop *L = AR->getLoop();
4604 
4605   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4606   // Note that this serves two purposes: It filters out loops that are
4607   // simply not analyzable, and it covers the case where this code is
4608   // being called from within backedge-taken count analysis, such that
4609   // attempting to ask for the backedge-taken count would likely result
4610   // in infinite recursion. In the later case, the analysis code will
4611   // cope with a conservative value, and it will take care to purge
4612   // that value once it has finished.
4613   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4614 
4615   // Normally, in the cases we can prove no-overflow via a
4616   // backedge guarding condition, we can also compute a backedge
4617   // taken count for the loop.  The exceptions are assumptions and
4618   // guards present in the loop -- SCEV is not great at exploiting
4619   // these to compute max backedge taken counts, but can still use
4620   // these to prove lack of overflow.  Use this fact to avoid
4621   // doing extra work that may not pay off.
4622 
4623   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4624       AC.assumptions().empty())
4625     return Result;
4626 
4627   // If the backedge is guarded by a comparison with the pre-inc  value the
4628   // addrec is safe. Also, if the entry is guarded by a comparison with the
4629   // start value and the backedge is guarded by a comparison with the post-inc
4630   // value, the addrec is safe.
4631   if (isKnownPositive(Step)) {
4632     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4633                                 getUnsignedRangeMax(Step));
4634     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4635         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4636       Result = setFlags(Result, SCEV::FlagNUW);
4637     }
4638   }
4639 
4640   return Result;
4641 }
4642 
4643 namespace {
4644 
4645 /// Represents an abstract binary operation.  This may exist as a
4646 /// normal instruction or constant expression, or may have been
4647 /// derived from an expression tree.
4648 struct BinaryOp {
4649   unsigned Opcode;
4650   Value *LHS;
4651   Value *RHS;
4652   bool IsNSW = false;
4653   bool IsNUW = false;
4654 
4655   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4656   /// constant expression.
4657   Operator *Op = nullptr;
4658 
4659   explicit BinaryOp(Operator *Op)
4660       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4661         Op(Op) {
4662     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4663       IsNSW = OBO->hasNoSignedWrap();
4664       IsNUW = OBO->hasNoUnsignedWrap();
4665     }
4666   }
4667 
4668   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4669                     bool IsNUW = false)
4670       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4671 };
4672 
4673 } // end anonymous namespace
4674 
4675 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4676 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4677   auto *Op = dyn_cast<Operator>(V);
4678   if (!Op)
4679     return None;
4680 
4681   // Implementation detail: all the cleverness here should happen without
4682   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4683   // SCEV expressions when possible, and we should not break that.
4684 
4685   switch (Op->getOpcode()) {
4686   case Instruction::Add:
4687   case Instruction::Sub:
4688   case Instruction::Mul:
4689   case Instruction::UDiv:
4690   case Instruction::URem:
4691   case Instruction::And:
4692   case Instruction::Or:
4693   case Instruction::AShr:
4694   case Instruction::Shl:
4695     return BinaryOp(Op);
4696 
4697   case Instruction::Xor:
4698     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4699       // If the RHS of the xor is a signmask, then this is just an add.
4700       // Instcombine turns add of signmask into xor as a strength reduction step.
4701       if (RHSC->getValue().isSignMask())
4702         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4703     return BinaryOp(Op);
4704 
4705   case Instruction::LShr:
4706     // Turn logical shift right of a constant into a unsigned divide.
4707     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4708       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4709 
4710       // If the shift count is not less than the bitwidth, the result of
4711       // the shift is undefined. Don't try to analyze it, because the
4712       // resolution chosen here may differ from the resolution chosen in
4713       // other parts of the compiler.
4714       if (SA->getValue().ult(BitWidth)) {
4715         Constant *X =
4716             ConstantInt::get(SA->getContext(),
4717                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4718         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4719       }
4720     }
4721     return BinaryOp(Op);
4722 
4723   case Instruction::ExtractValue: {
4724     auto *EVI = cast<ExtractValueInst>(Op);
4725     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4726       break;
4727 
4728     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4729     if (!WO)
4730       break;
4731 
4732     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4733     bool Signed = WO->isSigned();
4734     // TODO: Should add nuw/nsw flags for mul as well.
4735     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4736       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4737 
4738     // Now that we know that all uses of the arithmetic-result component of
4739     // CI are guarded by the overflow check, we can go ahead and pretend
4740     // that the arithmetic is non-overflowing.
4741     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4742                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4743   }
4744 
4745   default:
4746     break;
4747   }
4748 
4749   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4750   // semantics as a Sub, return a binary sub expression.
4751   if (auto *II = dyn_cast<IntrinsicInst>(V))
4752     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4753       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4754 
4755   return None;
4756 }
4757 
4758 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4759 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4760 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4761 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4762 /// follows one of the following patterns:
4763 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4764 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4765 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4766 /// we return the type of the truncation operation, and indicate whether the
4767 /// truncated type should be treated as signed/unsigned by setting
4768 /// \p Signed to true/false, respectively.
4769 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4770                                bool &Signed, ScalarEvolution &SE) {
4771   // The case where Op == SymbolicPHI (that is, with no type conversions on
4772   // the way) is handled by the regular add recurrence creating logic and
4773   // would have already been triggered in createAddRecForPHI. Reaching it here
4774   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4775   // because one of the other operands of the SCEVAddExpr updating this PHI is
4776   // not invariant).
4777   //
4778   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4779   // this case predicates that allow us to prove that Op == SymbolicPHI will
4780   // be added.
4781   if (Op == SymbolicPHI)
4782     return nullptr;
4783 
4784   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4785   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4786   if (SourceBits != NewBits)
4787     return nullptr;
4788 
4789   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4790   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4791   if (!SExt && !ZExt)
4792     return nullptr;
4793   const SCEVTruncateExpr *Trunc =
4794       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4795            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4796   if (!Trunc)
4797     return nullptr;
4798   const SCEV *X = Trunc->getOperand();
4799   if (X != SymbolicPHI)
4800     return nullptr;
4801   Signed = SExt != nullptr;
4802   return Trunc->getType();
4803 }
4804 
4805 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4806   if (!PN->getType()->isIntegerTy())
4807     return nullptr;
4808   const Loop *L = LI.getLoopFor(PN->getParent());
4809   if (!L || L->getHeader() != PN->getParent())
4810     return nullptr;
4811   return L;
4812 }
4813 
4814 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4815 // computation that updates the phi follows the following pattern:
4816 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4817 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4818 // If so, try to see if it can be rewritten as an AddRecExpr under some
4819 // Predicates. If successful, return them as a pair. Also cache the results
4820 // of the analysis.
4821 //
4822 // Example usage scenario:
4823 //    Say the Rewriter is called for the following SCEV:
4824 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4825 //    where:
4826 //         %X = phi i64 (%Start, %BEValue)
4827 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4828 //    and call this function with %SymbolicPHI = %X.
4829 //
4830 //    The analysis will find that the value coming around the backedge has
4831 //    the following SCEV:
4832 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4833 //    Upon concluding that this matches the desired pattern, the function
4834 //    will return the pair {NewAddRec, SmallPredsVec} where:
4835 //         NewAddRec = {%Start,+,%Step}
4836 //         SmallPredsVec = {P1, P2, P3} as follows:
4837 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4838 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4839 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4840 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4841 //    under the predicates {P1,P2,P3}.
4842 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4843 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4844 //
4845 // TODO's:
4846 //
4847 // 1) Extend the Induction descriptor to also support inductions that involve
4848 //    casts: When needed (namely, when we are called in the context of the
4849 //    vectorizer induction analysis), a Set of cast instructions will be
4850 //    populated by this method, and provided back to isInductionPHI. This is
4851 //    needed to allow the vectorizer to properly record them to be ignored by
4852 //    the cost model and to avoid vectorizing them (otherwise these casts,
4853 //    which are redundant under the runtime overflow checks, will be
4854 //    vectorized, which can be costly).
4855 //
4856 // 2) Support additional induction/PHISCEV patterns: We also want to support
4857 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4858 //    after the induction update operation (the induction increment):
4859 //
4860 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4861 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4862 //
4863 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4864 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4865 //
4866 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4867 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4868 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4869   SmallVector<const SCEVPredicate *, 3> Predicates;
4870 
4871   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4872   // return an AddRec expression under some predicate.
4873 
4874   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4875   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4876   assert(L && "Expecting an integer loop header phi");
4877 
4878   // The loop may have multiple entrances or multiple exits; we can analyze
4879   // this phi as an addrec if it has a unique entry value and a unique
4880   // backedge value.
4881   Value *BEValueV = nullptr, *StartValueV = nullptr;
4882   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4883     Value *V = PN->getIncomingValue(i);
4884     if (L->contains(PN->getIncomingBlock(i))) {
4885       if (!BEValueV) {
4886         BEValueV = V;
4887       } else if (BEValueV != V) {
4888         BEValueV = nullptr;
4889         break;
4890       }
4891     } else if (!StartValueV) {
4892       StartValueV = V;
4893     } else if (StartValueV != V) {
4894       StartValueV = nullptr;
4895       break;
4896     }
4897   }
4898   if (!BEValueV || !StartValueV)
4899     return None;
4900 
4901   const SCEV *BEValue = getSCEV(BEValueV);
4902 
4903   // If the value coming around the backedge is an add with the symbolic
4904   // value we just inserted, possibly with casts that we can ignore under
4905   // an appropriate runtime guard, then we found a simple induction variable!
4906   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4907   if (!Add)
4908     return None;
4909 
4910   // If there is a single occurrence of the symbolic value, possibly
4911   // casted, replace it with a recurrence.
4912   unsigned FoundIndex = Add->getNumOperands();
4913   Type *TruncTy = nullptr;
4914   bool Signed;
4915   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4916     if ((TruncTy =
4917              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4918       if (FoundIndex == e) {
4919         FoundIndex = i;
4920         break;
4921       }
4922 
4923   if (FoundIndex == Add->getNumOperands())
4924     return None;
4925 
4926   // Create an add with everything but the specified operand.
4927   SmallVector<const SCEV *, 8> Ops;
4928   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4929     if (i != FoundIndex)
4930       Ops.push_back(Add->getOperand(i));
4931   const SCEV *Accum = getAddExpr(Ops);
4932 
4933   // The runtime checks will not be valid if the step amount is
4934   // varying inside the loop.
4935   if (!isLoopInvariant(Accum, L))
4936     return None;
4937 
4938   // *** Part2: Create the predicates
4939 
4940   // Analysis was successful: we have a phi-with-cast pattern for which we
4941   // can return an AddRec expression under the following predicates:
4942   //
4943   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4944   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4945   // P2: An Equal predicate that guarantees that
4946   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4947   // P3: An Equal predicate that guarantees that
4948   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4949   //
4950   // As we next prove, the above predicates guarantee that:
4951   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4952   //
4953   //
4954   // More formally, we want to prove that:
4955   //     Expr(i+1) = Start + (i+1) * Accum
4956   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4957   //
4958   // Given that:
4959   // 1) Expr(0) = Start
4960   // 2) Expr(1) = Start + Accum
4961   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4962   // 3) Induction hypothesis (step i):
4963   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4964   //
4965   // Proof:
4966   //  Expr(i+1) =
4967   //   = Start + (i+1)*Accum
4968   //   = (Start + i*Accum) + Accum
4969   //   = Expr(i) + Accum
4970   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4971   //                                                             :: from step i
4972   //
4973   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4974   //
4975   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4976   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4977   //     + Accum                                                     :: from P3
4978   //
4979   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4980   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4981   //
4982   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4983   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4984   //
4985   // By induction, the same applies to all iterations 1<=i<n:
4986   //
4987 
4988   // Create a truncated addrec for which we will add a no overflow check (P1).
4989   const SCEV *StartVal = getSCEV(StartValueV);
4990   const SCEV *PHISCEV =
4991       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4992                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4993 
4994   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4995   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4996   // will be constant.
4997   //
4998   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4999   // add P1.
5000   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5001     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5002         Signed ? SCEVWrapPredicate::IncrementNSSW
5003                : SCEVWrapPredicate::IncrementNUSW;
5004     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5005     Predicates.push_back(AddRecPred);
5006   }
5007 
5008   // Create the Equal Predicates P2,P3:
5009 
5010   // It is possible that the predicates P2 and/or P3 are computable at
5011   // compile time due to StartVal and/or Accum being constants.
5012   // If either one is, then we can check that now and escape if either P2
5013   // or P3 is false.
5014 
5015   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5016   // for each of StartVal and Accum
5017   auto getExtendedExpr = [&](const SCEV *Expr,
5018                              bool CreateSignExtend) -> const SCEV * {
5019     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5020     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5021     const SCEV *ExtendedExpr =
5022         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5023                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5024     return ExtendedExpr;
5025   };
5026 
5027   // Given:
5028   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5029   //               = getExtendedExpr(Expr)
5030   // Determine whether the predicate P: Expr == ExtendedExpr
5031   // is known to be false at compile time
5032   auto PredIsKnownFalse = [&](const SCEV *Expr,
5033                               const SCEV *ExtendedExpr) -> bool {
5034     return Expr != ExtendedExpr &&
5035            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5036   };
5037 
5038   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5039   if (PredIsKnownFalse(StartVal, StartExtended)) {
5040     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5041     return None;
5042   }
5043 
5044   // The Step is always Signed (because the overflow checks are either
5045   // NSSW or NUSW)
5046   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5047   if (PredIsKnownFalse(Accum, AccumExtended)) {
5048     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5049     return None;
5050   }
5051 
5052   auto AppendPredicate = [&](const SCEV *Expr,
5053                              const SCEV *ExtendedExpr) -> void {
5054     if (Expr != ExtendedExpr &&
5055         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5056       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5057       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5058       Predicates.push_back(Pred);
5059     }
5060   };
5061 
5062   AppendPredicate(StartVal, StartExtended);
5063   AppendPredicate(Accum, AccumExtended);
5064 
5065   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5066   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5067   // into NewAR if it will also add the runtime overflow checks specified in
5068   // Predicates.
5069   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5070 
5071   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5072       std::make_pair(NewAR, Predicates);
5073   // Remember the result of the analysis for this SCEV at this locayyytion.
5074   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5075   return PredRewrite;
5076 }
5077 
5078 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5079 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5080   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5081   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5082   if (!L)
5083     return None;
5084 
5085   // Check to see if we already analyzed this PHI.
5086   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5087   if (I != PredicatedSCEVRewrites.end()) {
5088     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5089         I->second;
5090     // Analysis was done before and failed to create an AddRec:
5091     if (Rewrite.first == SymbolicPHI)
5092       return None;
5093     // Analysis was done before and succeeded to create an AddRec under
5094     // a predicate:
5095     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5096     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5097     return Rewrite;
5098   }
5099 
5100   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5101     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5102 
5103   // Record in the cache that the analysis failed
5104   if (!Rewrite) {
5105     SmallVector<const SCEVPredicate *, 3> Predicates;
5106     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5107     return None;
5108   }
5109 
5110   return Rewrite;
5111 }
5112 
5113 // FIXME: This utility is currently required because the Rewriter currently
5114 // does not rewrite this expression:
5115 // {0, +, (sext ix (trunc iy to ix) to iy)}
5116 // into {0, +, %step},
5117 // even when the following Equal predicate exists:
5118 // "%step == (sext ix (trunc iy to ix) to iy)".
5119 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5120     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5121   if (AR1 == AR2)
5122     return true;
5123 
5124   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5125     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5126         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5127       return false;
5128     return true;
5129   };
5130 
5131   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5132       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5133     return false;
5134   return true;
5135 }
5136 
5137 /// A helper function for createAddRecFromPHI to handle simple cases.
5138 ///
5139 /// This function tries to find an AddRec expression for the simplest (yet most
5140 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5141 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5142 /// technique for finding the AddRec expression.
5143 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5144                                                       Value *BEValueV,
5145                                                       Value *StartValueV) {
5146   const Loop *L = LI.getLoopFor(PN->getParent());
5147   assert(L && L->getHeader() == PN->getParent());
5148   assert(BEValueV && StartValueV);
5149 
5150   auto BO = MatchBinaryOp(BEValueV, DT);
5151   if (!BO)
5152     return nullptr;
5153 
5154   if (BO->Opcode != Instruction::Add)
5155     return nullptr;
5156 
5157   const SCEV *Accum = nullptr;
5158   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5159     Accum = getSCEV(BO->RHS);
5160   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5161     Accum = getSCEV(BO->LHS);
5162 
5163   if (!Accum)
5164     return nullptr;
5165 
5166   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5167   if (BO->IsNUW)
5168     Flags = setFlags(Flags, SCEV::FlagNUW);
5169   if (BO->IsNSW)
5170     Flags = setFlags(Flags, SCEV::FlagNSW);
5171 
5172   const SCEV *StartVal = getSCEV(StartValueV);
5173   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5174 
5175   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5176 
5177   // We can add Flags to the post-inc expression only if we
5178   // know that it is *undefined behavior* for BEValueV to
5179   // overflow.
5180   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5181     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5182       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5183 
5184   return PHISCEV;
5185 }
5186 
5187 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5188   const Loop *L = LI.getLoopFor(PN->getParent());
5189   if (!L || L->getHeader() != PN->getParent())
5190     return nullptr;
5191 
5192   // The loop may have multiple entrances or multiple exits; we can analyze
5193   // this phi as an addrec if it has a unique entry value and a unique
5194   // backedge value.
5195   Value *BEValueV = nullptr, *StartValueV = nullptr;
5196   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5197     Value *V = PN->getIncomingValue(i);
5198     if (L->contains(PN->getIncomingBlock(i))) {
5199       if (!BEValueV) {
5200         BEValueV = V;
5201       } else if (BEValueV != V) {
5202         BEValueV = nullptr;
5203         break;
5204       }
5205     } else if (!StartValueV) {
5206       StartValueV = V;
5207     } else if (StartValueV != V) {
5208       StartValueV = nullptr;
5209       break;
5210     }
5211   }
5212   if (!BEValueV || !StartValueV)
5213     return nullptr;
5214 
5215   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5216          "PHI node already processed?");
5217 
5218   // First, try to find AddRec expression without creating a fictituos symbolic
5219   // value for PN.
5220   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5221     return S;
5222 
5223   // Handle PHI node value symbolically.
5224   const SCEV *SymbolicName = getUnknown(PN);
5225   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5226 
5227   // Using this symbolic name for the PHI, analyze the value coming around
5228   // the back-edge.
5229   const SCEV *BEValue = getSCEV(BEValueV);
5230 
5231   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5232   // has a special value for the first iteration of the loop.
5233 
5234   // If the value coming around the backedge is an add with the symbolic
5235   // value we just inserted, then we found a simple induction variable!
5236   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5237     // If there is a single occurrence of the symbolic value, replace it
5238     // with a recurrence.
5239     unsigned FoundIndex = Add->getNumOperands();
5240     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5241       if (Add->getOperand(i) == SymbolicName)
5242         if (FoundIndex == e) {
5243           FoundIndex = i;
5244           break;
5245         }
5246 
5247     if (FoundIndex != Add->getNumOperands()) {
5248       // Create an add with everything but the specified operand.
5249       SmallVector<const SCEV *, 8> Ops;
5250       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5251         if (i != FoundIndex)
5252           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5253                                                              L, *this));
5254       const SCEV *Accum = getAddExpr(Ops);
5255 
5256       // This is not a valid addrec if the step amount is varying each
5257       // loop iteration, but is not itself an addrec in this loop.
5258       if (isLoopInvariant(Accum, L) ||
5259           (isa<SCEVAddRecExpr>(Accum) &&
5260            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5261         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5262 
5263         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5264           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5265             if (BO->IsNUW)
5266               Flags = setFlags(Flags, SCEV::FlagNUW);
5267             if (BO->IsNSW)
5268               Flags = setFlags(Flags, SCEV::FlagNSW);
5269           }
5270         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5271           // If the increment is an inbounds GEP, then we know the address
5272           // space cannot be wrapped around. We cannot make any guarantee
5273           // about signed or unsigned overflow because pointers are
5274           // unsigned but we may have a negative index from the base
5275           // pointer. We can guarantee that no unsigned wrap occurs if the
5276           // indices form a positive value.
5277           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5278             Flags = setFlags(Flags, SCEV::FlagNW);
5279 
5280             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5281             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5282               Flags = setFlags(Flags, SCEV::FlagNUW);
5283           }
5284 
5285           // We cannot transfer nuw and nsw flags from subtraction
5286           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5287           // for instance.
5288         }
5289 
5290         const SCEV *StartVal = getSCEV(StartValueV);
5291         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5292 
5293         // Okay, for the entire analysis of this edge we assumed the PHI
5294         // to be symbolic.  We now need to go back and purge all of the
5295         // entries for the scalars that use the symbolic expression.
5296         forgetSymbolicName(PN, SymbolicName);
5297         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5298 
5299         // We can add Flags to the post-inc expression only if we
5300         // know that it is *undefined behavior* for BEValueV to
5301         // overflow.
5302         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5303           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5304             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5305 
5306         return PHISCEV;
5307       }
5308     }
5309   } else {
5310     // Otherwise, this could be a loop like this:
5311     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5312     // In this case, j = {1,+,1}  and BEValue is j.
5313     // Because the other in-value of i (0) fits the evolution of BEValue
5314     // i really is an addrec evolution.
5315     //
5316     // We can generalize this saying that i is the shifted value of BEValue
5317     // by one iteration:
5318     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5319     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5320     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5321     if (Shifted != getCouldNotCompute() &&
5322         Start != getCouldNotCompute()) {
5323       const SCEV *StartVal = getSCEV(StartValueV);
5324       if (Start == StartVal) {
5325         // Okay, for the entire analysis of this edge we assumed the PHI
5326         // to be symbolic.  We now need to go back and purge all of the
5327         // entries for the scalars that use the symbolic expression.
5328         forgetSymbolicName(PN, SymbolicName);
5329         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5330         return Shifted;
5331       }
5332     }
5333   }
5334 
5335   // Remove the temporary PHI node SCEV that has been inserted while intending
5336   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5337   // as it will prevent later (possibly simpler) SCEV expressions to be added
5338   // to the ValueExprMap.
5339   eraseValueFromMap(PN);
5340 
5341   return nullptr;
5342 }
5343 
5344 // Checks if the SCEV S is available at BB.  S is considered available at BB
5345 // if S can be materialized at BB without introducing a fault.
5346 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5347                                BasicBlock *BB) {
5348   struct CheckAvailable {
5349     bool TraversalDone = false;
5350     bool Available = true;
5351 
5352     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5353     BasicBlock *BB = nullptr;
5354     DominatorTree &DT;
5355 
5356     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5357       : L(L), BB(BB), DT(DT) {}
5358 
5359     bool setUnavailable() {
5360       TraversalDone = true;
5361       Available = false;
5362       return false;
5363     }
5364 
5365     bool follow(const SCEV *S) {
5366       switch (S->getSCEVType()) {
5367       case scConstant:
5368       case scPtrToInt:
5369       case scTruncate:
5370       case scZeroExtend:
5371       case scSignExtend:
5372       case scAddExpr:
5373       case scMulExpr:
5374       case scUMaxExpr:
5375       case scSMaxExpr:
5376       case scUMinExpr:
5377       case scSMinExpr:
5378         // These expressions are available if their operand(s) is/are.
5379         return true;
5380 
5381       case scAddRecExpr: {
5382         // We allow add recurrences that are on the loop BB is in, or some
5383         // outer loop.  This guarantees availability because the value of the
5384         // add recurrence at BB is simply the "current" value of the induction
5385         // variable.  We can relax this in the future; for instance an add
5386         // recurrence on a sibling dominating loop is also available at BB.
5387         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5388         if (L && (ARLoop == L || ARLoop->contains(L)))
5389           return true;
5390 
5391         return setUnavailable();
5392       }
5393 
5394       case scUnknown: {
5395         // For SCEVUnknown, we check for simple dominance.
5396         const auto *SU = cast<SCEVUnknown>(S);
5397         Value *V = SU->getValue();
5398 
5399         if (isa<Argument>(V))
5400           return false;
5401 
5402         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5403           return false;
5404 
5405         return setUnavailable();
5406       }
5407 
5408       case scUDivExpr:
5409       case scCouldNotCompute:
5410         // We do not try to smart about these at all.
5411         return setUnavailable();
5412       }
5413       llvm_unreachable("Unknown SCEV kind!");
5414     }
5415 
5416     bool isDone() { return TraversalDone; }
5417   };
5418 
5419   CheckAvailable CA(L, BB, DT);
5420   SCEVTraversal<CheckAvailable> ST(CA);
5421 
5422   ST.visitAll(S);
5423   return CA.Available;
5424 }
5425 
5426 // Try to match a control flow sequence that branches out at BI and merges back
5427 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5428 // match.
5429 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5430                           Value *&C, Value *&LHS, Value *&RHS) {
5431   C = BI->getCondition();
5432 
5433   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5434   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5435 
5436   if (!LeftEdge.isSingleEdge())
5437     return false;
5438 
5439   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5440 
5441   Use &LeftUse = Merge->getOperandUse(0);
5442   Use &RightUse = Merge->getOperandUse(1);
5443 
5444   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5445     LHS = LeftUse;
5446     RHS = RightUse;
5447     return true;
5448   }
5449 
5450   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5451     LHS = RightUse;
5452     RHS = LeftUse;
5453     return true;
5454   }
5455 
5456   return false;
5457 }
5458 
5459 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5460   auto IsReachable =
5461       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5462   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5463     const Loop *L = LI.getLoopFor(PN->getParent());
5464 
5465     // We don't want to break LCSSA, even in a SCEV expression tree.
5466     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5467       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5468         return nullptr;
5469 
5470     // Try to match
5471     //
5472     //  br %cond, label %left, label %right
5473     // left:
5474     //  br label %merge
5475     // right:
5476     //  br label %merge
5477     // merge:
5478     //  V = phi [ %x, %left ], [ %y, %right ]
5479     //
5480     // as "select %cond, %x, %y"
5481 
5482     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5483     assert(IDom && "At least the entry block should dominate PN");
5484 
5485     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5486     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5487 
5488     if (BI && BI->isConditional() &&
5489         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5490         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5491         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5492       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5493   }
5494 
5495   return nullptr;
5496 }
5497 
5498 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5499   if (const SCEV *S = createAddRecFromPHI(PN))
5500     return S;
5501 
5502   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5503     return S;
5504 
5505   // If the PHI has a single incoming value, follow that value, unless the
5506   // PHI's incoming blocks are in a different loop, in which case doing so
5507   // risks breaking LCSSA form. Instcombine would normally zap these, but
5508   // it doesn't have DominatorTree information, so it may miss cases.
5509   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5510     if (LI.replacementPreservesLCSSAForm(PN, V))
5511       return getSCEV(V);
5512 
5513   // If it's not a loop phi, we can't handle it yet.
5514   return getUnknown(PN);
5515 }
5516 
5517 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5518                                                       Value *Cond,
5519                                                       Value *TrueVal,
5520                                                       Value *FalseVal) {
5521   // Handle "constant" branch or select. This can occur for instance when a
5522   // loop pass transforms an inner loop and moves on to process the outer loop.
5523   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5524     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5525 
5526   // Try to match some simple smax or umax patterns.
5527   auto *ICI = dyn_cast<ICmpInst>(Cond);
5528   if (!ICI)
5529     return getUnknown(I);
5530 
5531   Value *LHS = ICI->getOperand(0);
5532   Value *RHS = ICI->getOperand(1);
5533 
5534   switch (ICI->getPredicate()) {
5535   case ICmpInst::ICMP_SLT:
5536   case ICmpInst::ICMP_SLE:
5537     std::swap(LHS, RHS);
5538     LLVM_FALLTHROUGH;
5539   case ICmpInst::ICMP_SGT:
5540   case ICmpInst::ICMP_SGE:
5541     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5542     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5543     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5544       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5545       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5546       const SCEV *LA = getSCEV(TrueVal);
5547       const SCEV *RA = getSCEV(FalseVal);
5548       const SCEV *LDiff = getMinusSCEV(LA, LS);
5549       const SCEV *RDiff = getMinusSCEV(RA, RS);
5550       if (LDiff == RDiff)
5551         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5552       LDiff = getMinusSCEV(LA, RS);
5553       RDiff = getMinusSCEV(RA, LS);
5554       if (LDiff == RDiff)
5555         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5556     }
5557     break;
5558   case ICmpInst::ICMP_ULT:
5559   case ICmpInst::ICMP_ULE:
5560     std::swap(LHS, RHS);
5561     LLVM_FALLTHROUGH;
5562   case ICmpInst::ICMP_UGT:
5563   case ICmpInst::ICMP_UGE:
5564     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5565     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5566     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5567       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5568       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5569       const SCEV *LA = getSCEV(TrueVal);
5570       const SCEV *RA = getSCEV(FalseVal);
5571       const SCEV *LDiff = getMinusSCEV(LA, LS);
5572       const SCEV *RDiff = getMinusSCEV(RA, RS);
5573       if (LDiff == RDiff)
5574         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5575       LDiff = getMinusSCEV(LA, RS);
5576       RDiff = getMinusSCEV(RA, LS);
5577       if (LDiff == RDiff)
5578         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5579     }
5580     break;
5581   case ICmpInst::ICMP_NE:
5582     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5583     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5584         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5585       const SCEV *One = getOne(I->getType());
5586       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5587       const SCEV *LA = getSCEV(TrueVal);
5588       const SCEV *RA = getSCEV(FalseVal);
5589       const SCEV *LDiff = getMinusSCEV(LA, LS);
5590       const SCEV *RDiff = getMinusSCEV(RA, One);
5591       if (LDiff == RDiff)
5592         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5593     }
5594     break;
5595   case ICmpInst::ICMP_EQ:
5596     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5597     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5598         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5599       const SCEV *One = getOne(I->getType());
5600       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5601       const SCEV *LA = getSCEV(TrueVal);
5602       const SCEV *RA = getSCEV(FalseVal);
5603       const SCEV *LDiff = getMinusSCEV(LA, One);
5604       const SCEV *RDiff = getMinusSCEV(RA, LS);
5605       if (LDiff == RDiff)
5606         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5607     }
5608     break;
5609   default:
5610     break;
5611   }
5612 
5613   return getUnknown(I);
5614 }
5615 
5616 /// Expand GEP instructions into add and multiply operations. This allows them
5617 /// to be analyzed by regular SCEV code.
5618 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5619   // Don't attempt to analyze GEPs over unsized objects.
5620   if (!GEP->getSourceElementType()->isSized())
5621     return getUnknown(GEP);
5622 
5623   SmallVector<const SCEV *, 4> IndexExprs;
5624   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5625     IndexExprs.push_back(getSCEV(*Index));
5626   return getGEPExpr(GEP, IndexExprs);
5627 }
5628 
5629 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5630   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5631     return C->getAPInt().countTrailingZeros();
5632 
5633   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5634     return GetMinTrailingZeros(I->getOperand());
5635 
5636   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5637     return std::min(GetMinTrailingZeros(T->getOperand()),
5638                     (uint32_t)getTypeSizeInBits(T->getType()));
5639 
5640   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5641     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5642     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5643                ? getTypeSizeInBits(E->getType())
5644                : OpRes;
5645   }
5646 
5647   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5648     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5649     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5650                ? getTypeSizeInBits(E->getType())
5651                : OpRes;
5652   }
5653 
5654   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5655     // The result is the min of all operands results.
5656     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5657     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5658       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5659     return MinOpRes;
5660   }
5661 
5662   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5663     // The result is the sum of all operands results.
5664     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5665     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5666     for (unsigned i = 1, e = M->getNumOperands();
5667          SumOpRes != BitWidth && i != e; ++i)
5668       SumOpRes =
5669           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5670     return SumOpRes;
5671   }
5672 
5673   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5674     // The result is the min of all operands results.
5675     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5676     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5677       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5678     return MinOpRes;
5679   }
5680 
5681   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5682     // The result is the min of all operands results.
5683     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5684     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5685       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5686     return MinOpRes;
5687   }
5688 
5689   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5690     // The result is the min of all operands results.
5691     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5692     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5693       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5694     return MinOpRes;
5695   }
5696 
5697   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5698     // For a SCEVUnknown, ask ValueTracking.
5699     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5700     return Known.countMinTrailingZeros();
5701   }
5702 
5703   // SCEVUDivExpr
5704   return 0;
5705 }
5706 
5707 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5708   auto I = MinTrailingZerosCache.find(S);
5709   if (I != MinTrailingZerosCache.end())
5710     return I->second;
5711 
5712   uint32_t Result = GetMinTrailingZerosImpl(S);
5713   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5714   assert(InsertPair.second && "Should insert a new key");
5715   return InsertPair.first->second;
5716 }
5717 
5718 /// Helper method to assign a range to V from metadata present in the IR.
5719 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5720   if (Instruction *I = dyn_cast<Instruction>(V))
5721     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5722       return getConstantRangeFromMetadata(*MD);
5723 
5724   return None;
5725 }
5726 
5727 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5728                                      SCEV::NoWrapFlags Flags) {
5729   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5730     AddRec->setNoWrapFlags(Flags);
5731     UnsignedRanges.erase(AddRec);
5732     SignedRanges.erase(AddRec);
5733   }
5734 }
5735 
5736 ConstantRange ScalarEvolution::
5737 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5738   const DataLayout &DL = getDataLayout();
5739 
5740   unsigned BitWidth = getTypeSizeInBits(U->getType());
5741   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
5742 
5743   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5744   // use information about the trip count to improve our available range.  Note
5745   // that the trip count independent cases are already handled by known bits.
5746   // WARNING: The definition of recurrence used here is subtly different than
5747   // the one used by AddRec (and thus most of this file).  Step is allowed to
5748   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5749   // and other addrecs in the same loop (for non-affine addrecs).  The code
5750   // below intentionally handles the case where step is not loop invariant.
5751   auto *P = dyn_cast<PHINode>(U->getValue());
5752   if (!P)
5753     return FullSet;
5754 
5755   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5756   // even the values that are not available in these blocks may come from them,
5757   // and this leads to false-positive recurrence test.
5758   for (auto *Pred : predecessors(P->getParent()))
5759     if (!DT.isReachableFromEntry(Pred))
5760       return FullSet;
5761 
5762   BinaryOperator *BO;
5763   Value *Start, *Step;
5764   if (!matchSimpleRecurrence(P, BO, Start, Step))
5765     return FullSet;
5766 
5767   // If we found a recurrence in reachable code, we must be in a loop. Note
5768   // that BO might be in some subloop of L, and that's completely okay.
5769   auto *L = LI.getLoopFor(P->getParent());
5770   assert(L && L->getHeader() == P->getParent());
5771   if (!L->contains(BO->getParent()))
5772     // NOTE: This bailout should be an assert instead.  However, asserting
5773     // the condition here exposes a case where LoopFusion is querying SCEV
5774     // with malformed loop information during the midst of the transform.
5775     // There doesn't appear to be an obvious fix, so for the moment bailout
5776     // until the caller issue can be fixed.  PR49566 tracks the bug.
5777     return FullSet;
5778 
5779   // TODO: Extend to other opcodes such as mul, and div
5780   switch (BO->getOpcode()) {
5781   default:
5782     return FullSet;
5783   case Instruction::AShr:
5784   case Instruction::LShr:
5785   case Instruction::Shl:
5786     break;
5787   };
5788 
5789   if (BO->getOperand(0) != P)
5790     // TODO: Handle the power function forms some day.
5791     return FullSet;
5792 
5793   unsigned TC = getSmallConstantMaxTripCount(L);
5794   if (!TC || TC >= BitWidth)
5795     return FullSet;
5796 
5797   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5798   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5799   assert(KnownStart.getBitWidth() == BitWidth &&
5800          KnownStep.getBitWidth() == BitWidth);
5801 
5802   // Compute total shift amount, being careful of overflow and bitwidths.
5803   auto MaxShiftAmt = KnownStep.getMaxValue();
5804   APInt TCAP(BitWidth, TC-1);
5805   bool Overflow = false;
5806   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5807   if (Overflow)
5808     return FullSet;
5809 
5810   switch (BO->getOpcode()) {
5811   default:
5812     llvm_unreachable("filtered out above");
5813   case Instruction::AShr: {
5814     // For each ashr, three cases:
5815     //   shift = 0 => unchanged value
5816     //   saturation => 0 or -1
5817     //   other => a value closer to zero (of the same sign)
5818     // Thus, the end value is closer to zero than the start.
5819     auto KnownEnd = KnownBits::ashr(KnownStart,
5820                                     KnownBits::makeConstant(TotalShift));
5821     if (KnownStart.isNonNegative())
5822       // Analogous to lshr (simply not yet canonicalized)
5823       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5824                                         KnownStart.getMaxValue() + 1);
5825     if (KnownStart.isNegative())
5826       // End >=u Start && End <=s Start
5827       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
5828                                         KnownEnd.getMaxValue() + 1);
5829     break;
5830   }
5831   case Instruction::LShr: {
5832     // For each lshr, three cases:
5833     //   shift = 0 => unchanged value
5834     //   saturation => 0
5835     //   other => a smaller positive number
5836     // Thus, the low end of the unsigned range is the last value produced.
5837     auto KnownEnd = KnownBits::lshr(KnownStart,
5838                                     KnownBits::makeConstant(TotalShift));
5839     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5840                                       KnownStart.getMaxValue() + 1);
5841   }
5842   case Instruction::Shl: {
5843     // Iff no bits are shifted out, value increases on every shift.
5844     auto KnownEnd = KnownBits::shl(KnownStart,
5845                                    KnownBits::makeConstant(TotalShift));
5846     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5847       return ConstantRange(KnownStart.getMinValue(),
5848                            KnownEnd.getMaxValue() + 1);
5849     break;
5850   }
5851   };
5852   return FullSet;
5853 }
5854 
5855 /// Determine the range for a particular SCEV.  If SignHint is
5856 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5857 /// with a "cleaner" unsigned (resp. signed) representation.
5858 const ConstantRange &
5859 ScalarEvolution::getRangeRef(const SCEV *S,
5860                              ScalarEvolution::RangeSignHint SignHint) {
5861   DenseMap<const SCEV *, ConstantRange> &Cache =
5862       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5863                                                        : SignedRanges;
5864   ConstantRange::PreferredRangeType RangeType =
5865       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5866           ? ConstantRange::Unsigned : ConstantRange::Signed;
5867 
5868   // See if we've computed this range already.
5869   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5870   if (I != Cache.end())
5871     return I->second;
5872 
5873   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5874     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5875 
5876   unsigned BitWidth = getTypeSizeInBits(S->getType());
5877   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5878   using OBO = OverflowingBinaryOperator;
5879 
5880   // If the value has known zeros, the maximum value will have those known zeros
5881   // as well.
5882   uint32_t TZ = GetMinTrailingZeros(S);
5883   if (TZ != 0) {
5884     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5885       ConservativeResult =
5886           ConstantRange(APInt::getMinValue(BitWidth),
5887                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5888     else
5889       ConservativeResult = ConstantRange(
5890           APInt::getSignedMinValue(BitWidth),
5891           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5892   }
5893 
5894   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5895     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5896     unsigned WrapType = OBO::AnyWrap;
5897     if (Add->hasNoSignedWrap())
5898       WrapType |= OBO::NoSignedWrap;
5899     if (Add->hasNoUnsignedWrap())
5900       WrapType |= OBO::NoUnsignedWrap;
5901     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5902       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5903                           WrapType, RangeType);
5904     return setRange(Add, SignHint,
5905                     ConservativeResult.intersectWith(X, RangeType));
5906   }
5907 
5908   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5909     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5910     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5911       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5912     return setRange(Mul, SignHint,
5913                     ConservativeResult.intersectWith(X, RangeType));
5914   }
5915 
5916   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5917     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5918     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5919       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5920     return setRange(SMax, SignHint,
5921                     ConservativeResult.intersectWith(X, RangeType));
5922   }
5923 
5924   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5925     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5926     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5927       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5928     return setRange(UMax, SignHint,
5929                     ConservativeResult.intersectWith(X, RangeType));
5930   }
5931 
5932   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5933     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5934     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5935       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5936     return setRange(SMin, SignHint,
5937                     ConservativeResult.intersectWith(X, RangeType));
5938   }
5939 
5940   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5941     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5942     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5943       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5944     return setRange(UMin, SignHint,
5945                     ConservativeResult.intersectWith(X, RangeType));
5946   }
5947 
5948   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5949     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5950     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5951     return setRange(UDiv, SignHint,
5952                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5953   }
5954 
5955   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5956     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5957     return setRange(ZExt, SignHint,
5958                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5959                                                      RangeType));
5960   }
5961 
5962   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5963     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5964     return setRange(SExt, SignHint,
5965                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5966                                                      RangeType));
5967   }
5968 
5969   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5970     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5971     return setRange(PtrToInt, SignHint, X);
5972   }
5973 
5974   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5975     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5976     return setRange(Trunc, SignHint,
5977                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5978                                                      RangeType));
5979   }
5980 
5981   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5982     // If there's no unsigned wrap, the value will never be less than its
5983     // initial value.
5984     if (AddRec->hasNoUnsignedWrap()) {
5985       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5986       if (!UnsignedMinValue.isNullValue())
5987         ConservativeResult = ConservativeResult.intersectWith(
5988             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5989     }
5990 
5991     // If there's no signed wrap, and all the operands except initial value have
5992     // the same sign or zero, the value won't ever be:
5993     // 1: smaller than initial value if operands are non negative,
5994     // 2: bigger than initial value if operands are non positive.
5995     // For both cases, value can not cross signed min/max boundary.
5996     if (AddRec->hasNoSignedWrap()) {
5997       bool AllNonNeg = true;
5998       bool AllNonPos = true;
5999       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6000         if (!isKnownNonNegative(AddRec->getOperand(i)))
6001           AllNonNeg = false;
6002         if (!isKnownNonPositive(AddRec->getOperand(i)))
6003           AllNonPos = false;
6004       }
6005       if (AllNonNeg)
6006         ConservativeResult = ConservativeResult.intersectWith(
6007             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6008                                        APInt::getSignedMinValue(BitWidth)),
6009             RangeType);
6010       else if (AllNonPos)
6011         ConservativeResult = ConservativeResult.intersectWith(
6012             ConstantRange::getNonEmpty(
6013                 APInt::getSignedMinValue(BitWidth),
6014                 getSignedRangeMax(AddRec->getStart()) + 1),
6015             RangeType);
6016     }
6017 
6018     // TODO: non-affine addrec
6019     if (AddRec->isAffine()) {
6020       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6021       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6022           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6023         auto RangeFromAffine = getRangeForAffineAR(
6024             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6025             BitWidth);
6026         ConservativeResult =
6027             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6028 
6029         auto RangeFromFactoring = getRangeViaFactoring(
6030             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6031             BitWidth);
6032         ConservativeResult =
6033             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6034       }
6035 
6036       // Now try symbolic BE count and more powerful methods.
6037       if (UseExpensiveRangeSharpening) {
6038         const SCEV *SymbolicMaxBECount =
6039             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6040         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6041             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6042             AddRec->hasNoSelfWrap()) {
6043           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6044               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6045           ConservativeResult =
6046               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6047         }
6048       }
6049     }
6050 
6051     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6052   }
6053 
6054   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6055 
6056     // Check if the IR explicitly contains !range metadata.
6057     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6058     if (MDRange.hasValue())
6059       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6060                                                             RangeType);
6061 
6062     // Use facts about recurrences in the underlying IR.  Note that add
6063     // recurrences are AddRecExprs and thus don't hit this path.  This
6064     // primarily handles shift recurrences.
6065     auto CR = getRangeForUnknownRecurrence(U);
6066     ConservativeResult = ConservativeResult.intersectWith(CR);
6067 
6068     // See if ValueTracking can give us a useful range.
6069     const DataLayout &DL = getDataLayout();
6070     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6071     if (Known.getBitWidth() != BitWidth)
6072       Known = Known.zextOrTrunc(BitWidth);
6073 
6074     // ValueTracking may be able to compute a tighter result for the number of
6075     // sign bits than for the value of those sign bits.
6076     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6077     if (U->getType()->isPointerTy()) {
6078       // If the pointer size is larger than the index size type, this can cause
6079       // NS to be larger than BitWidth. So compensate for this.
6080       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6081       int ptrIdxDiff = ptrSize - BitWidth;
6082       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6083         NS -= ptrIdxDiff;
6084     }
6085 
6086     if (NS > 1) {
6087       // If we know any of the sign bits, we know all of the sign bits.
6088       if (!Known.Zero.getHiBits(NS).isNullValue())
6089         Known.Zero.setHighBits(NS);
6090       if (!Known.One.getHiBits(NS).isNullValue())
6091         Known.One.setHighBits(NS);
6092     }
6093 
6094     if (Known.getMinValue() != Known.getMaxValue() + 1)
6095       ConservativeResult = ConservativeResult.intersectWith(
6096           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6097           RangeType);
6098     if (NS > 1)
6099       ConservativeResult = ConservativeResult.intersectWith(
6100           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6101                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6102           RangeType);
6103 
6104     // A range of Phi is a subset of union of all ranges of its input.
6105     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6106       // Make sure that we do not run over cycled Phis.
6107       if (PendingPhiRanges.insert(Phi).second) {
6108         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6109         for (auto &Op : Phi->operands()) {
6110           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6111           RangeFromOps = RangeFromOps.unionWith(OpRange);
6112           // No point to continue if we already have a full set.
6113           if (RangeFromOps.isFullSet())
6114             break;
6115         }
6116         ConservativeResult =
6117             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6118         bool Erased = PendingPhiRanges.erase(Phi);
6119         assert(Erased && "Failed to erase Phi properly?");
6120         (void) Erased;
6121       }
6122     }
6123 
6124     return setRange(U, SignHint, std::move(ConservativeResult));
6125   }
6126 
6127   return setRange(S, SignHint, std::move(ConservativeResult));
6128 }
6129 
6130 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6131 // values that the expression can take. Initially, the expression has a value
6132 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6133 // argument defines if we treat Step as signed or unsigned.
6134 static ConstantRange getRangeForAffineARHelper(APInt Step,
6135                                                const ConstantRange &StartRange,
6136                                                const APInt &MaxBECount,
6137                                                unsigned BitWidth, bool Signed) {
6138   // If either Step or MaxBECount is 0, then the expression won't change, and we
6139   // just need to return the initial range.
6140   if (Step == 0 || MaxBECount == 0)
6141     return StartRange;
6142 
6143   // If we don't know anything about the initial value (i.e. StartRange is
6144   // FullRange), then we don't know anything about the final range either.
6145   // Return FullRange.
6146   if (StartRange.isFullSet())
6147     return ConstantRange::getFull(BitWidth);
6148 
6149   // If Step is signed and negative, then we use its absolute value, but we also
6150   // note that we're moving in the opposite direction.
6151   bool Descending = Signed && Step.isNegative();
6152 
6153   if (Signed)
6154     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6155     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6156     // This equations hold true due to the well-defined wrap-around behavior of
6157     // APInt.
6158     Step = Step.abs();
6159 
6160   // Check if Offset is more than full span of BitWidth. If it is, the
6161   // expression is guaranteed to overflow.
6162   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6163     return ConstantRange::getFull(BitWidth);
6164 
6165   // Offset is by how much the expression can change. Checks above guarantee no
6166   // overflow here.
6167   APInt Offset = Step * MaxBECount;
6168 
6169   // Minimum value of the final range will match the minimal value of StartRange
6170   // if the expression is increasing and will be decreased by Offset otherwise.
6171   // Maximum value of the final range will match the maximal value of StartRange
6172   // if the expression is decreasing and will be increased by Offset otherwise.
6173   APInt StartLower = StartRange.getLower();
6174   APInt StartUpper = StartRange.getUpper() - 1;
6175   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6176                                    : (StartUpper + std::move(Offset));
6177 
6178   // It's possible that the new minimum/maximum value will fall into the initial
6179   // range (due to wrap around). This means that the expression can take any
6180   // value in this bitwidth, and we have to return full range.
6181   if (StartRange.contains(MovedBoundary))
6182     return ConstantRange::getFull(BitWidth);
6183 
6184   APInt NewLower =
6185       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6186   APInt NewUpper =
6187       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6188   NewUpper += 1;
6189 
6190   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6191   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6192 }
6193 
6194 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6195                                                    const SCEV *Step,
6196                                                    const SCEV *MaxBECount,
6197                                                    unsigned BitWidth) {
6198   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6199          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6200          "Precondition!");
6201 
6202   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6203   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6204 
6205   // First, consider step signed.
6206   ConstantRange StartSRange = getSignedRange(Start);
6207   ConstantRange StepSRange = getSignedRange(Step);
6208 
6209   // If Step can be both positive and negative, we need to find ranges for the
6210   // maximum absolute step values in both directions and union them.
6211   ConstantRange SR =
6212       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6213                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6214   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6215                                               StartSRange, MaxBECountValue,
6216                                               BitWidth, /* Signed = */ true));
6217 
6218   // Next, consider step unsigned.
6219   ConstantRange UR = getRangeForAffineARHelper(
6220       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6221       MaxBECountValue, BitWidth, /* Signed = */ false);
6222 
6223   // Finally, intersect signed and unsigned ranges.
6224   return SR.intersectWith(UR, ConstantRange::Smallest);
6225 }
6226 
6227 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6228     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6229     ScalarEvolution::RangeSignHint SignHint) {
6230   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6231   assert(AddRec->hasNoSelfWrap() &&
6232          "This only works for non-self-wrapping AddRecs!");
6233   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6234   const SCEV *Step = AddRec->getStepRecurrence(*this);
6235   // Only deal with constant step to save compile time.
6236   if (!isa<SCEVConstant>(Step))
6237     return ConstantRange::getFull(BitWidth);
6238   // Let's make sure that we can prove that we do not self-wrap during
6239   // MaxBECount iterations. We need this because MaxBECount is a maximum
6240   // iteration count estimate, and we might infer nw from some exit for which we
6241   // do not know max exit count (or any other side reasoning).
6242   // TODO: Turn into assert at some point.
6243   if (getTypeSizeInBits(MaxBECount->getType()) >
6244       getTypeSizeInBits(AddRec->getType()))
6245     return ConstantRange::getFull(BitWidth);
6246   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6247   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6248   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6249   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6250   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6251                                          MaxItersWithoutWrap))
6252     return ConstantRange::getFull(BitWidth);
6253 
6254   ICmpInst::Predicate LEPred =
6255       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6256   ICmpInst::Predicate GEPred =
6257       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6258   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6259 
6260   // We know that there is no self-wrap. Let's take Start and End values and
6261   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6262   // the iteration. They either lie inside the range [Min(Start, End),
6263   // Max(Start, End)] or outside it:
6264   //
6265   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6266   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6267   //
6268   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6269   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6270   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6271   // Start <= End and step is positive, or Start >= End and step is negative.
6272   const SCEV *Start = AddRec->getStart();
6273   ConstantRange StartRange = getRangeRef(Start, SignHint);
6274   ConstantRange EndRange = getRangeRef(End, SignHint);
6275   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6276   // If they already cover full iteration space, we will know nothing useful
6277   // even if we prove what we want to prove.
6278   if (RangeBetween.isFullSet())
6279     return RangeBetween;
6280   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6281   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6282                                : RangeBetween.isWrappedSet();
6283   if (IsWrappedSet)
6284     return ConstantRange::getFull(BitWidth);
6285 
6286   if (isKnownPositive(Step) &&
6287       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6288     return RangeBetween;
6289   else if (isKnownNegative(Step) &&
6290            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6291     return RangeBetween;
6292   return ConstantRange::getFull(BitWidth);
6293 }
6294 
6295 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6296                                                     const SCEV *Step,
6297                                                     const SCEV *MaxBECount,
6298                                                     unsigned BitWidth) {
6299   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6300   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6301 
6302   struct SelectPattern {
6303     Value *Condition = nullptr;
6304     APInt TrueValue;
6305     APInt FalseValue;
6306 
6307     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6308                            const SCEV *S) {
6309       Optional<unsigned> CastOp;
6310       APInt Offset(BitWidth, 0);
6311 
6312       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6313              "Should be!");
6314 
6315       // Peel off a constant offset:
6316       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6317         // In the future we could consider being smarter here and handle
6318         // {Start+Step,+,Step} too.
6319         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6320           return;
6321 
6322         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6323         S = SA->getOperand(1);
6324       }
6325 
6326       // Peel off a cast operation
6327       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6328         CastOp = SCast->getSCEVType();
6329         S = SCast->getOperand();
6330       }
6331 
6332       using namespace llvm::PatternMatch;
6333 
6334       auto *SU = dyn_cast<SCEVUnknown>(S);
6335       const APInt *TrueVal, *FalseVal;
6336       if (!SU ||
6337           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6338                                           m_APInt(FalseVal)))) {
6339         Condition = nullptr;
6340         return;
6341       }
6342 
6343       TrueValue = *TrueVal;
6344       FalseValue = *FalseVal;
6345 
6346       // Re-apply the cast we peeled off earlier
6347       if (CastOp.hasValue())
6348         switch (*CastOp) {
6349         default:
6350           llvm_unreachable("Unknown SCEV cast type!");
6351 
6352         case scTruncate:
6353           TrueValue = TrueValue.trunc(BitWidth);
6354           FalseValue = FalseValue.trunc(BitWidth);
6355           break;
6356         case scZeroExtend:
6357           TrueValue = TrueValue.zext(BitWidth);
6358           FalseValue = FalseValue.zext(BitWidth);
6359           break;
6360         case scSignExtend:
6361           TrueValue = TrueValue.sext(BitWidth);
6362           FalseValue = FalseValue.sext(BitWidth);
6363           break;
6364         }
6365 
6366       // Re-apply the constant offset we peeled off earlier
6367       TrueValue += Offset;
6368       FalseValue += Offset;
6369     }
6370 
6371     bool isRecognized() { return Condition != nullptr; }
6372   };
6373 
6374   SelectPattern StartPattern(*this, BitWidth, Start);
6375   if (!StartPattern.isRecognized())
6376     return ConstantRange::getFull(BitWidth);
6377 
6378   SelectPattern StepPattern(*this, BitWidth, Step);
6379   if (!StepPattern.isRecognized())
6380     return ConstantRange::getFull(BitWidth);
6381 
6382   if (StartPattern.Condition != StepPattern.Condition) {
6383     // We don't handle this case today; but we could, by considering four
6384     // possibilities below instead of two. I'm not sure if there are cases where
6385     // that will help over what getRange already does, though.
6386     return ConstantRange::getFull(BitWidth);
6387   }
6388 
6389   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6390   // construct arbitrary general SCEV expressions here.  This function is called
6391   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6392   // say) can end up caching a suboptimal value.
6393 
6394   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6395   // C2352 and C2512 (otherwise it isn't needed).
6396 
6397   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6398   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6399   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6400   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6401 
6402   ConstantRange TrueRange =
6403       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6404   ConstantRange FalseRange =
6405       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6406 
6407   return TrueRange.unionWith(FalseRange);
6408 }
6409 
6410 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6411   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6412   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6413 
6414   // Return early if there are no flags to propagate to the SCEV.
6415   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6416   if (BinOp->hasNoUnsignedWrap())
6417     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6418   if (BinOp->hasNoSignedWrap())
6419     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6420   if (Flags == SCEV::FlagAnyWrap)
6421     return SCEV::FlagAnyWrap;
6422 
6423   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6424 }
6425 
6426 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6427   // Here we check that I is in the header of the innermost loop containing I,
6428   // since we only deal with instructions in the loop header. The actual loop we
6429   // need to check later will come from an add recurrence, but getting that
6430   // requires computing the SCEV of the operands, which can be expensive. This
6431   // check we can do cheaply to rule out some cases early.
6432   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6433   if (InnermostContainingLoop == nullptr ||
6434       InnermostContainingLoop->getHeader() != I->getParent())
6435     return false;
6436 
6437   // Only proceed if we can prove that I does not yield poison.
6438   if (!programUndefinedIfPoison(I))
6439     return false;
6440 
6441   // At this point we know that if I is executed, then it does not wrap
6442   // according to at least one of NSW or NUW. If I is not executed, then we do
6443   // not know if the calculation that I represents would wrap. Multiple
6444   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6445   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6446   // derived from other instructions that map to the same SCEV. We cannot make
6447   // that guarantee for cases where I is not executed. So we need to find the
6448   // loop that I is considered in relation to and prove that I is executed for
6449   // every iteration of that loop. That implies that the value that I
6450   // calculates does not wrap anywhere in the loop, so then we can apply the
6451   // flags to the SCEV.
6452   //
6453   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6454   // from different loops, so that we know which loop to prove that I is
6455   // executed in.
6456   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6457     // I could be an extractvalue from a call to an overflow intrinsic.
6458     // TODO: We can do better here in some cases.
6459     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6460       return false;
6461     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6462     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6463       bool AllOtherOpsLoopInvariant = true;
6464       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6465            ++OtherOpIndex) {
6466         if (OtherOpIndex != OpIndex) {
6467           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6468           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6469             AllOtherOpsLoopInvariant = false;
6470             break;
6471           }
6472         }
6473       }
6474       if (AllOtherOpsLoopInvariant &&
6475           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6476         return true;
6477     }
6478   }
6479   return false;
6480 }
6481 
6482 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6483   // If we know that \c I can never be poison period, then that's enough.
6484   if (isSCEVExprNeverPoison(I))
6485     return true;
6486 
6487   // For an add recurrence specifically, we assume that infinite loops without
6488   // side effects are undefined behavior, and then reason as follows:
6489   //
6490   // If the add recurrence is poison in any iteration, it is poison on all
6491   // future iterations (since incrementing poison yields poison). If the result
6492   // of the add recurrence is fed into the loop latch condition and the loop
6493   // does not contain any throws or exiting blocks other than the latch, we now
6494   // have the ability to "choose" whether the backedge is taken or not (by
6495   // choosing a sufficiently evil value for the poison feeding into the branch)
6496   // for every iteration including and after the one in which \p I first became
6497   // poison.  There are two possibilities (let's call the iteration in which \p
6498   // I first became poison as K):
6499   //
6500   //  1. In the set of iterations including and after K, the loop body executes
6501   //     no side effects.  In this case executing the backege an infinte number
6502   //     of times will yield undefined behavior.
6503   //
6504   //  2. In the set of iterations including and after K, the loop body executes
6505   //     at least one side effect.  In this case, that specific instance of side
6506   //     effect is control dependent on poison, which also yields undefined
6507   //     behavior.
6508 
6509   auto *ExitingBB = L->getExitingBlock();
6510   auto *LatchBB = L->getLoopLatch();
6511   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6512     return false;
6513 
6514   SmallPtrSet<const Instruction *, 16> Pushed;
6515   SmallVector<const Instruction *, 8> PoisonStack;
6516 
6517   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6518   // things that are known to be poison under that assumption go on the
6519   // PoisonStack.
6520   Pushed.insert(I);
6521   PoisonStack.push_back(I);
6522 
6523   bool LatchControlDependentOnPoison = false;
6524   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6525     const Instruction *Poison = PoisonStack.pop_back_val();
6526 
6527     for (auto *PoisonUser : Poison->users()) {
6528       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6529         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6530           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6531       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6532         assert(BI->isConditional() && "Only possibility!");
6533         if (BI->getParent() == LatchBB) {
6534           LatchControlDependentOnPoison = true;
6535           break;
6536         }
6537       }
6538     }
6539   }
6540 
6541   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6542 }
6543 
6544 ScalarEvolution::LoopProperties
6545 ScalarEvolution::getLoopProperties(const Loop *L) {
6546   using LoopProperties = ScalarEvolution::LoopProperties;
6547 
6548   auto Itr = LoopPropertiesCache.find(L);
6549   if (Itr == LoopPropertiesCache.end()) {
6550     auto HasSideEffects = [](Instruction *I) {
6551       if (auto *SI = dyn_cast<StoreInst>(I))
6552         return !SI->isSimple();
6553 
6554       return I->mayHaveSideEffects();
6555     };
6556 
6557     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6558                          /*HasNoSideEffects*/ true};
6559 
6560     for (auto *BB : L->getBlocks())
6561       for (auto &I : *BB) {
6562         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6563           LP.HasNoAbnormalExits = false;
6564         if (HasSideEffects(&I))
6565           LP.HasNoSideEffects = false;
6566         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6567           break; // We're already as pessimistic as we can get.
6568       }
6569 
6570     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6571     assert(InsertPair.second && "We just checked!");
6572     Itr = InsertPair.first;
6573   }
6574 
6575   return Itr->second;
6576 }
6577 
6578 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
6579   // A mustprogress loop without side effects must be finite.
6580   // TODO: The check used here is very conservative.  It's only *specific*
6581   // side effects which are well defined in infinite loops.
6582   return isMustProgress(L) && loopHasNoSideEffects(L);
6583 }
6584 
6585 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6586   if (!isSCEVable(V->getType()))
6587     return getUnknown(V);
6588 
6589   if (Instruction *I = dyn_cast<Instruction>(V)) {
6590     // Don't attempt to analyze instructions in blocks that aren't
6591     // reachable. Such instructions don't matter, and they aren't required
6592     // to obey basic rules for definitions dominating uses which this
6593     // analysis depends on.
6594     if (!DT.isReachableFromEntry(I->getParent()))
6595       return getUnknown(UndefValue::get(V->getType()));
6596   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6597     return getConstant(CI);
6598   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6599     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6600   else if (!isa<ConstantExpr>(V))
6601     return getUnknown(V);
6602 
6603   Operator *U = cast<Operator>(V);
6604   if (auto BO = MatchBinaryOp(U, DT)) {
6605     switch (BO->Opcode) {
6606     case Instruction::Add: {
6607       // The simple thing to do would be to just call getSCEV on both operands
6608       // and call getAddExpr with the result. However if we're looking at a
6609       // bunch of things all added together, this can be quite inefficient,
6610       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6611       // Instead, gather up all the operands and make a single getAddExpr call.
6612       // LLVM IR canonical form means we need only traverse the left operands.
6613       SmallVector<const SCEV *, 4> AddOps;
6614       do {
6615         if (BO->Op) {
6616           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6617             AddOps.push_back(OpSCEV);
6618             break;
6619           }
6620 
6621           // If a NUW or NSW flag can be applied to the SCEV for this
6622           // addition, then compute the SCEV for this addition by itself
6623           // with a separate call to getAddExpr. We need to do that
6624           // instead of pushing the operands of the addition onto AddOps,
6625           // since the flags are only known to apply to this particular
6626           // addition - they may not apply to other additions that can be
6627           // formed with operands from AddOps.
6628           const SCEV *RHS = getSCEV(BO->RHS);
6629           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6630           if (Flags != SCEV::FlagAnyWrap) {
6631             const SCEV *LHS = getSCEV(BO->LHS);
6632             if (BO->Opcode == Instruction::Sub)
6633               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6634             else
6635               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6636             break;
6637           }
6638         }
6639 
6640         if (BO->Opcode == Instruction::Sub)
6641           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6642         else
6643           AddOps.push_back(getSCEV(BO->RHS));
6644 
6645         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6646         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6647                        NewBO->Opcode != Instruction::Sub)) {
6648           AddOps.push_back(getSCEV(BO->LHS));
6649           break;
6650         }
6651         BO = NewBO;
6652       } while (true);
6653 
6654       return getAddExpr(AddOps);
6655     }
6656 
6657     case Instruction::Mul: {
6658       SmallVector<const SCEV *, 4> MulOps;
6659       do {
6660         if (BO->Op) {
6661           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6662             MulOps.push_back(OpSCEV);
6663             break;
6664           }
6665 
6666           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6667           if (Flags != SCEV::FlagAnyWrap) {
6668             MulOps.push_back(
6669                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6670             break;
6671           }
6672         }
6673 
6674         MulOps.push_back(getSCEV(BO->RHS));
6675         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6676         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6677           MulOps.push_back(getSCEV(BO->LHS));
6678           break;
6679         }
6680         BO = NewBO;
6681       } while (true);
6682 
6683       return getMulExpr(MulOps);
6684     }
6685     case Instruction::UDiv:
6686       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6687     case Instruction::URem:
6688       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6689     case Instruction::Sub: {
6690       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6691       if (BO->Op)
6692         Flags = getNoWrapFlagsFromUB(BO->Op);
6693       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6694     }
6695     case Instruction::And:
6696       // For an expression like x&255 that merely masks off the high bits,
6697       // use zext(trunc(x)) as the SCEV expression.
6698       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6699         if (CI->isZero())
6700           return getSCEV(BO->RHS);
6701         if (CI->isMinusOne())
6702           return getSCEV(BO->LHS);
6703         const APInt &A = CI->getValue();
6704 
6705         // Instcombine's ShrinkDemandedConstant may strip bits out of
6706         // constants, obscuring what would otherwise be a low-bits mask.
6707         // Use computeKnownBits to compute what ShrinkDemandedConstant
6708         // knew about to reconstruct a low-bits mask value.
6709         unsigned LZ = A.countLeadingZeros();
6710         unsigned TZ = A.countTrailingZeros();
6711         unsigned BitWidth = A.getBitWidth();
6712         KnownBits Known(BitWidth);
6713         computeKnownBits(BO->LHS, Known, getDataLayout(),
6714                          0, &AC, nullptr, &DT);
6715 
6716         APInt EffectiveMask =
6717             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6718         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6719           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6720           const SCEV *LHS = getSCEV(BO->LHS);
6721           const SCEV *ShiftedLHS = nullptr;
6722           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6723             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6724               // For an expression like (x * 8) & 8, simplify the multiply.
6725               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6726               unsigned GCD = std::min(MulZeros, TZ);
6727               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6728               SmallVector<const SCEV*, 4> MulOps;
6729               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6730               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6731               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6732               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6733             }
6734           }
6735           if (!ShiftedLHS)
6736             ShiftedLHS = getUDivExpr(LHS, MulCount);
6737           return getMulExpr(
6738               getZeroExtendExpr(
6739                   getTruncateExpr(ShiftedLHS,
6740                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6741                   BO->LHS->getType()),
6742               MulCount);
6743         }
6744       }
6745       break;
6746 
6747     case Instruction::Or:
6748       // If the RHS of the Or is a constant, we may have something like:
6749       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6750       // optimizations will transparently handle this case.
6751       //
6752       // In order for this transformation to be safe, the LHS must be of the
6753       // form X*(2^n) and the Or constant must be less than 2^n.
6754       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6755         const SCEV *LHS = getSCEV(BO->LHS);
6756         const APInt &CIVal = CI->getValue();
6757         if (GetMinTrailingZeros(LHS) >=
6758             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6759           // Build a plain add SCEV.
6760           return getAddExpr(LHS, getSCEV(CI),
6761                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6762         }
6763       }
6764       break;
6765 
6766     case Instruction::Xor:
6767       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6768         // If the RHS of xor is -1, then this is a not operation.
6769         if (CI->isMinusOne())
6770           return getNotSCEV(getSCEV(BO->LHS));
6771 
6772         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6773         // This is a variant of the check for xor with -1, and it handles
6774         // the case where instcombine has trimmed non-demanded bits out
6775         // of an xor with -1.
6776         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6777           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6778             if (LBO->getOpcode() == Instruction::And &&
6779                 LCI->getValue() == CI->getValue())
6780               if (const SCEVZeroExtendExpr *Z =
6781                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6782                 Type *UTy = BO->LHS->getType();
6783                 const SCEV *Z0 = Z->getOperand();
6784                 Type *Z0Ty = Z0->getType();
6785                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6786 
6787                 // If C is a low-bits mask, the zero extend is serving to
6788                 // mask off the high bits. Complement the operand and
6789                 // re-apply the zext.
6790                 if (CI->getValue().isMask(Z0TySize))
6791                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6792 
6793                 // If C is a single bit, it may be in the sign-bit position
6794                 // before the zero-extend. In this case, represent the xor
6795                 // using an add, which is equivalent, and re-apply the zext.
6796                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6797                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6798                     Trunc.isSignMask())
6799                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6800                                            UTy);
6801               }
6802       }
6803       break;
6804 
6805     case Instruction::Shl:
6806       // Turn shift left of a constant amount into a multiply.
6807       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6808         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6809 
6810         // If the shift count is not less than the bitwidth, the result of
6811         // the shift is undefined. Don't try to analyze it, because the
6812         // resolution chosen here may differ from the resolution chosen in
6813         // other parts of the compiler.
6814         if (SA->getValue().uge(BitWidth))
6815           break;
6816 
6817         // We can safely preserve the nuw flag in all cases. It's also safe to
6818         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6819         // requires special handling. It can be preserved as long as we're not
6820         // left shifting by bitwidth - 1.
6821         auto Flags = SCEV::FlagAnyWrap;
6822         if (BO->Op) {
6823           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6824           if ((MulFlags & SCEV::FlagNSW) &&
6825               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6826             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6827           if (MulFlags & SCEV::FlagNUW)
6828             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6829         }
6830 
6831         Constant *X = ConstantInt::get(
6832             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6833         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6834       }
6835       break;
6836 
6837     case Instruction::AShr: {
6838       // AShr X, C, where C is a constant.
6839       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6840       if (!CI)
6841         break;
6842 
6843       Type *OuterTy = BO->LHS->getType();
6844       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6845       // If the shift count is not less than the bitwidth, the result of
6846       // the shift is undefined. Don't try to analyze it, because the
6847       // resolution chosen here may differ from the resolution chosen in
6848       // other parts of the compiler.
6849       if (CI->getValue().uge(BitWidth))
6850         break;
6851 
6852       if (CI->isZero())
6853         return getSCEV(BO->LHS); // shift by zero --> noop
6854 
6855       uint64_t AShrAmt = CI->getZExtValue();
6856       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6857 
6858       Operator *L = dyn_cast<Operator>(BO->LHS);
6859       if (L && L->getOpcode() == Instruction::Shl) {
6860         // X = Shl A, n
6861         // Y = AShr X, m
6862         // Both n and m are constant.
6863 
6864         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6865         if (L->getOperand(1) == BO->RHS)
6866           // For a two-shift sext-inreg, i.e. n = m,
6867           // use sext(trunc(x)) as the SCEV expression.
6868           return getSignExtendExpr(
6869               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6870 
6871         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6872         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6873           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6874           if (ShlAmt > AShrAmt) {
6875             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6876             // expression. We already checked that ShlAmt < BitWidth, so
6877             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6878             // ShlAmt - AShrAmt < Amt.
6879             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6880                                             ShlAmt - AShrAmt);
6881             return getSignExtendExpr(
6882                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6883                 getConstant(Mul)), OuterTy);
6884           }
6885         }
6886       }
6887       break;
6888     }
6889     }
6890   }
6891 
6892   switch (U->getOpcode()) {
6893   case Instruction::Trunc:
6894     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6895 
6896   case Instruction::ZExt:
6897     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6898 
6899   case Instruction::SExt:
6900     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6901       // The NSW flag of a subtract does not always survive the conversion to
6902       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6903       // more likely to preserve NSW and allow later AddRec optimisations.
6904       //
6905       // NOTE: This is effectively duplicating this logic from getSignExtend:
6906       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6907       // but by that point the NSW information has potentially been lost.
6908       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6909         Type *Ty = U->getType();
6910         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6911         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6912         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6913       }
6914     }
6915     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6916 
6917   case Instruction::BitCast:
6918     // BitCasts are no-op casts so we just eliminate the cast.
6919     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6920       return getSCEV(U->getOperand(0));
6921     break;
6922 
6923   case Instruction::PtrToInt: {
6924     // Pointer to integer cast is straight-forward, so do model it.
6925     const SCEV *Op = getSCEV(U->getOperand(0));
6926     Type *DstIntTy = U->getType();
6927     // But only if effective SCEV (integer) type is wide enough to represent
6928     // all possible pointer values.
6929     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
6930     if (isa<SCEVCouldNotCompute>(IntOp))
6931       return getUnknown(V);
6932     return IntOp;
6933   }
6934   case Instruction::IntToPtr:
6935     // Just don't deal with inttoptr casts.
6936     return getUnknown(V);
6937 
6938   case Instruction::SDiv:
6939     // If both operands are non-negative, this is just an udiv.
6940     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6941         isKnownNonNegative(getSCEV(U->getOperand(1))))
6942       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6943     break;
6944 
6945   case Instruction::SRem:
6946     // If both operands are non-negative, this is just an urem.
6947     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6948         isKnownNonNegative(getSCEV(U->getOperand(1))))
6949       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6950     break;
6951 
6952   case Instruction::GetElementPtr:
6953     return createNodeForGEP(cast<GEPOperator>(U));
6954 
6955   case Instruction::PHI:
6956     return createNodeForPHI(cast<PHINode>(U));
6957 
6958   case Instruction::Select:
6959     // U can also be a select constant expr, which let fall through.  Since
6960     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6961     // constant expressions cannot have instructions as operands, we'd have
6962     // returned getUnknown for a select constant expressions anyway.
6963     if (isa<Instruction>(U))
6964       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6965                                       U->getOperand(1), U->getOperand(2));
6966     break;
6967 
6968   case Instruction::Call:
6969   case Instruction::Invoke:
6970     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6971       return getSCEV(RV);
6972 
6973     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6974       switch (II->getIntrinsicID()) {
6975       case Intrinsic::abs:
6976         return getAbsExpr(
6977             getSCEV(II->getArgOperand(0)),
6978             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6979       case Intrinsic::umax:
6980         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6981                            getSCEV(II->getArgOperand(1)));
6982       case Intrinsic::umin:
6983         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6984                            getSCEV(II->getArgOperand(1)));
6985       case Intrinsic::smax:
6986         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6987                            getSCEV(II->getArgOperand(1)));
6988       case Intrinsic::smin:
6989         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6990                            getSCEV(II->getArgOperand(1)));
6991       case Intrinsic::usub_sat: {
6992         const SCEV *X = getSCEV(II->getArgOperand(0));
6993         const SCEV *Y = getSCEV(II->getArgOperand(1));
6994         const SCEV *ClampedY = getUMinExpr(X, Y);
6995         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6996       }
6997       case Intrinsic::uadd_sat: {
6998         const SCEV *X = getSCEV(II->getArgOperand(0));
6999         const SCEV *Y = getSCEV(II->getArgOperand(1));
7000         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7001         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7002       }
7003       case Intrinsic::start_loop_iterations:
7004         // A start_loop_iterations is just equivalent to the first operand for
7005         // SCEV purposes.
7006         return getSCEV(II->getArgOperand(0));
7007       default:
7008         break;
7009       }
7010     }
7011     break;
7012   }
7013 
7014   return getUnknown(V);
7015 }
7016 
7017 //===----------------------------------------------------------------------===//
7018 //                   Iteration Count Computation Code
7019 //
7020 
7021 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
7022   // Get the trip count from the BE count by adding 1.  Overflow, results
7023   // in zero which means "unknown".
7024   return getAddExpr(ExitCount, getOne(ExitCount->getType()));
7025 }
7026 
7027 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7028   if (!ExitCount)
7029     return 0;
7030 
7031   ConstantInt *ExitConst = ExitCount->getValue();
7032 
7033   // Guard against huge trip counts.
7034   if (ExitConst->getValue().getActiveBits() > 32)
7035     return 0;
7036 
7037   // In case of integer overflow, this returns 0, which is correct.
7038   return ((unsigned)ExitConst->getZExtValue()) + 1;
7039 }
7040 
7041 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7042   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7043   return getConstantTripCount(ExitCount);
7044 }
7045 
7046 unsigned
7047 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7048                                            const BasicBlock *ExitingBlock) {
7049   assert(ExitingBlock && "Must pass a non-null exiting block!");
7050   assert(L->isLoopExiting(ExitingBlock) &&
7051          "Exiting block must actually branch out of the loop!");
7052   const SCEVConstant *ExitCount =
7053       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7054   return getConstantTripCount(ExitCount);
7055 }
7056 
7057 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7058   const auto *MaxExitCount =
7059       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7060   return getConstantTripCount(MaxExitCount);
7061 }
7062 
7063 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7064   SmallVector<BasicBlock *, 8> ExitingBlocks;
7065   L->getExitingBlocks(ExitingBlocks);
7066 
7067   Optional<unsigned> Res = None;
7068   for (auto *ExitingBB : ExitingBlocks) {
7069     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7070     if (!Res)
7071       Res = Multiple;
7072     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7073   }
7074   return Res.getValueOr(1);
7075 }
7076 
7077 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7078                                                        const SCEV *ExitCount) {
7079   if (ExitCount == getCouldNotCompute())
7080     return 1;
7081 
7082   // Get the trip count
7083   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7084 
7085   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7086   if (!TC)
7087     // Attempt to factor more general cases. Returns the greatest power of
7088     // two divisor. If overflow happens, the trip count expression is still
7089     // divisible by the greatest power of 2 divisor returned.
7090     return 1U << std::min((uint32_t)31,
7091                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7092 
7093   ConstantInt *Result = TC->getValue();
7094 
7095   // Guard against huge trip counts (this requires checking
7096   // for zero to handle the case where the trip count == -1 and the
7097   // addition wraps).
7098   if (!Result || Result->getValue().getActiveBits() > 32 ||
7099       Result->getValue().getActiveBits() == 0)
7100     return 1;
7101 
7102   return (unsigned)Result->getZExtValue();
7103 }
7104 
7105 /// Returns the largest constant divisor of the trip count of this loop as a
7106 /// normal unsigned value, if possible. This means that the actual trip count is
7107 /// always a multiple of the returned value (don't forget the trip count could
7108 /// very well be zero as well!).
7109 ///
7110 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7111 /// multiple of a constant (which is also the case if the trip count is simply
7112 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7113 /// if the trip count is very large (>= 2^32).
7114 ///
7115 /// As explained in the comments for getSmallConstantTripCount, this assumes
7116 /// that control exits the loop via ExitingBlock.
7117 unsigned
7118 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7119                                               const BasicBlock *ExitingBlock) {
7120   assert(ExitingBlock && "Must pass a non-null exiting block!");
7121   assert(L->isLoopExiting(ExitingBlock) &&
7122          "Exiting block must actually branch out of the loop!");
7123   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7124   return getSmallConstantTripMultiple(L, ExitCount);
7125 }
7126 
7127 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7128                                           const BasicBlock *ExitingBlock,
7129                                           ExitCountKind Kind) {
7130   switch (Kind) {
7131   case Exact:
7132   case SymbolicMaximum:
7133     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7134   case ConstantMaximum:
7135     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7136   };
7137   llvm_unreachable("Invalid ExitCountKind!");
7138 }
7139 
7140 const SCEV *
7141 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7142                                                  SCEVUnionPredicate &Preds) {
7143   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7144 }
7145 
7146 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7147                                                    ExitCountKind Kind) {
7148   switch (Kind) {
7149   case Exact:
7150     return getBackedgeTakenInfo(L).getExact(L, this);
7151   case ConstantMaximum:
7152     return getBackedgeTakenInfo(L).getConstantMax(this);
7153   case SymbolicMaximum:
7154     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7155   };
7156   llvm_unreachable("Invalid ExitCountKind!");
7157 }
7158 
7159 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7160   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7161 }
7162 
7163 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7164 static void
7165 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
7166   BasicBlock *Header = L->getHeader();
7167 
7168   // Push all Loop-header PHIs onto the Worklist stack.
7169   for (PHINode &PN : Header->phis())
7170     Worklist.push_back(&PN);
7171 }
7172 
7173 const ScalarEvolution::BackedgeTakenInfo &
7174 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7175   auto &BTI = getBackedgeTakenInfo(L);
7176   if (BTI.hasFullInfo())
7177     return BTI;
7178 
7179   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7180 
7181   if (!Pair.second)
7182     return Pair.first->second;
7183 
7184   BackedgeTakenInfo Result =
7185       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7186 
7187   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7188 }
7189 
7190 ScalarEvolution::BackedgeTakenInfo &
7191 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7192   // Initially insert an invalid entry for this loop. If the insertion
7193   // succeeds, proceed to actually compute a backedge-taken count and
7194   // update the value. The temporary CouldNotCompute value tells SCEV
7195   // code elsewhere that it shouldn't attempt to request a new
7196   // backedge-taken count, which could result in infinite recursion.
7197   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7198       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7199   if (!Pair.second)
7200     return Pair.first->second;
7201 
7202   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7203   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7204   // must be cleared in this scope.
7205   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7206 
7207   // In product build, there are no usage of statistic.
7208   (void)NumTripCountsComputed;
7209   (void)NumTripCountsNotComputed;
7210 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7211   const SCEV *BEExact = Result.getExact(L, this);
7212   if (BEExact != getCouldNotCompute()) {
7213     assert(isLoopInvariant(BEExact, L) &&
7214            isLoopInvariant(Result.getConstantMax(this), L) &&
7215            "Computed backedge-taken count isn't loop invariant for loop!");
7216     ++NumTripCountsComputed;
7217   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7218              isa<PHINode>(L->getHeader()->begin())) {
7219     // Only count loops that have phi nodes as not being computable.
7220     ++NumTripCountsNotComputed;
7221   }
7222 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7223 
7224   // Now that we know more about the trip count for this loop, forget any
7225   // existing SCEV values for PHI nodes in this loop since they are only
7226   // conservative estimates made without the benefit of trip count
7227   // information. This is similar to the code in forgetLoop, except that
7228   // it handles SCEVUnknown PHI nodes specially.
7229   if (Result.hasAnyInfo()) {
7230     SmallVector<Instruction *, 16> Worklist;
7231     PushLoopPHIs(L, Worklist);
7232 
7233     SmallPtrSet<Instruction *, 8> Discovered;
7234     while (!Worklist.empty()) {
7235       Instruction *I = Worklist.pop_back_val();
7236 
7237       ValueExprMapType::iterator It =
7238         ValueExprMap.find_as(static_cast<Value *>(I));
7239       if (It != ValueExprMap.end()) {
7240         const SCEV *Old = It->second;
7241 
7242         // SCEVUnknown for a PHI either means that it has an unrecognized
7243         // structure, or it's a PHI that's in the progress of being computed
7244         // by createNodeForPHI.  In the former case, additional loop trip
7245         // count information isn't going to change anything. In the later
7246         // case, createNodeForPHI will perform the necessary updates on its
7247         // own when it gets to that point.
7248         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7249           eraseValueFromMap(It->first);
7250           forgetMemoizedResults(Old);
7251         }
7252         if (PHINode *PN = dyn_cast<PHINode>(I))
7253           ConstantEvolutionLoopExitValue.erase(PN);
7254       }
7255 
7256       // Since we don't need to invalidate anything for correctness and we're
7257       // only invalidating to make SCEV's results more precise, we get to stop
7258       // early to avoid invalidating too much.  This is especially important in
7259       // cases like:
7260       //
7261       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7262       // loop0:
7263       //   %pn0 = phi
7264       //   ...
7265       // loop1:
7266       //   %pn1 = phi
7267       //   ...
7268       //
7269       // where both loop0 and loop1's backedge taken count uses the SCEV
7270       // expression for %v.  If we don't have the early stop below then in cases
7271       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7272       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7273       // count for loop1, effectively nullifying SCEV's trip count cache.
7274       for (auto *U : I->users())
7275         if (auto *I = dyn_cast<Instruction>(U)) {
7276           auto *LoopForUser = LI.getLoopFor(I->getParent());
7277           if (LoopForUser && L->contains(LoopForUser) &&
7278               Discovered.insert(I).second)
7279             Worklist.push_back(I);
7280         }
7281     }
7282   }
7283 
7284   // Re-lookup the insert position, since the call to
7285   // computeBackedgeTakenCount above could result in a
7286   // recusive call to getBackedgeTakenInfo (on a different
7287   // loop), which would invalidate the iterator computed
7288   // earlier.
7289   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7290 }
7291 
7292 void ScalarEvolution::forgetAllLoops() {
7293   // This method is intended to forget all info about loops. It should
7294   // invalidate caches as if the following happened:
7295   // - The trip counts of all loops have changed arbitrarily
7296   // - Every llvm::Value has been updated in place to produce a different
7297   // result.
7298   BackedgeTakenCounts.clear();
7299   PredicatedBackedgeTakenCounts.clear();
7300   LoopPropertiesCache.clear();
7301   ConstantEvolutionLoopExitValue.clear();
7302   ValueExprMap.clear();
7303   ValuesAtScopes.clear();
7304   LoopDispositions.clear();
7305   BlockDispositions.clear();
7306   UnsignedRanges.clear();
7307   SignedRanges.clear();
7308   ExprValueMap.clear();
7309   HasRecMap.clear();
7310   MinTrailingZerosCache.clear();
7311   PredicatedSCEVRewrites.clear();
7312 }
7313 
7314 void ScalarEvolution::forgetLoop(const Loop *L) {
7315   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7316   SmallVector<Instruction *, 32> Worklist;
7317   SmallPtrSet<Instruction *, 16> Visited;
7318 
7319   // Iterate over all the loops and sub-loops to drop SCEV information.
7320   while (!LoopWorklist.empty()) {
7321     auto *CurrL = LoopWorklist.pop_back_val();
7322 
7323     // Drop any stored trip count value.
7324     BackedgeTakenCounts.erase(CurrL);
7325     PredicatedBackedgeTakenCounts.erase(CurrL);
7326 
7327     // Drop information about predicated SCEV rewrites for this loop.
7328     for (auto I = PredicatedSCEVRewrites.begin();
7329          I != PredicatedSCEVRewrites.end();) {
7330       std::pair<const SCEV *, const Loop *> Entry = I->first;
7331       if (Entry.second == CurrL)
7332         PredicatedSCEVRewrites.erase(I++);
7333       else
7334         ++I;
7335     }
7336 
7337     auto LoopUsersItr = LoopUsers.find(CurrL);
7338     if (LoopUsersItr != LoopUsers.end()) {
7339       for (auto *S : LoopUsersItr->second)
7340         forgetMemoizedResults(S);
7341       LoopUsers.erase(LoopUsersItr);
7342     }
7343 
7344     // Drop information about expressions based on loop-header PHIs.
7345     PushLoopPHIs(CurrL, Worklist);
7346 
7347     while (!Worklist.empty()) {
7348       Instruction *I = Worklist.pop_back_val();
7349       if (!Visited.insert(I).second)
7350         continue;
7351 
7352       ValueExprMapType::iterator It =
7353           ValueExprMap.find_as(static_cast<Value *>(I));
7354       if (It != ValueExprMap.end()) {
7355         eraseValueFromMap(It->first);
7356         forgetMemoizedResults(It->second);
7357         if (PHINode *PN = dyn_cast<PHINode>(I))
7358           ConstantEvolutionLoopExitValue.erase(PN);
7359       }
7360 
7361       PushDefUseChildren(I, Worklist);
7362     }
7363 
7364     LoopPropertiesCache.erase(CurrL);
7365     // Forget all contained loops too, to avoid dangling entries in the
7366     // ValuesAtScopes map.
7367     LoopWorklist.append(CurrL->begin(), CurrL->end());
7368   }
7369 }
7370 
7371 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7372   while (Loop *Parent = L->getParentLoop())
7373     L = Parent;
7374   forgetLoop(L);
7375 }
7376 
7377 void ScalarEvolution::forgetValue(Value *V) {
7378   Instruction *I = dyn_cast<Instruction>(V);
7379   if (!I) return;
7380 
7381   // Drop information about expressions based on loop-header PHIs.
7382   SmallVector<Instruction *, 16> Worklist;
7383   Worklist.push_back(I);
7384 
7385   SmallPtrSet<Instruction *, 8> Visited;
7386   while (!Worklist.empty()) {
7387     I = Worklist.pop_back_val();
7388     if (!Visited.insert(I).second)
7389       continue;
7390 
7391     ValueExprMapType::iterator It =
7392       ValueExprMap.find_as(static_cast<Value *>(I));
7393     if (It != ValueExprMap.end()) {
7394       eraseValueFromMap(It->first);
7395       forgetMemoizedResults(It->second);
7396       if (PHINode *PN = dyn_cast<PHINode>(I))
7397         ConstantEvolutionLoopExitValue.erase(PN);
7398     }
7399 
7400     PushDefUseChildren(I, Worklist);
7401   }
7402 }
7403 
7404 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7405   LoopDispositions.clear();
7406 }
7407 
7408 /// Get the exact loop backedge taken count considering all loop exits. A
7409 /// computable result can only be returned for loops with all exiting blocks
7410 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7411 /// is never skipped. This is a valid assumption as long as the loop exits via
7412 /// that test. For precise results, it is the caller's responsibility to specify
7413 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7414 const SCEV *
7415 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7416                                              SCEVUnionPredicate *Preds) const {
7417   // If any exits were not computable, the loop is not computable.
7418   if (!isComplete() || ExitNotTaken.empty())
7419     return SE->getCouldNotCompute();
7420 
7421   const BasicBlock *Latch = L->getLoopLatch();
7422   // All exiting blocks we have collected must dominate the only backedge.
7423   if (!Latch)
7424     return SE->getCouldNotCompute();
7425 
7426   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7427   // count is simply a minimum out of all these calculated exit counts.
7428   SmallVector<const SCEV *, 2> Ops;
7429   for (auto &ENT : ExitNotTaken) {
7430     const SCEV *BECount = ENT.ExactNotTaken;
7431     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7432     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7433            "We should only have known counts for exiting blocks that dominate "
7434            "latch!");
7435 
7436     Ops.push_back(BECount);
7437 
7438     if (Preds && !ENT.hasAlwaysTruePredicate())
7439       Preds->add(ENT.Predicate.get());
7440 
7441     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7442            "Predicate should be always true!");
7443   }
7444 
7445   return SE->getUMinFromMismatchedTypes(Ops);
7446 }
7447 
7448 /// Get the exact not taken count for this loop exit.
7449 const SCEV *
7450 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7451                                              ScalarEvolution *SE) const {
7452   for (auto &ENT : ExitNotTaken)
7453     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7454       return ENT.ExactNotTaken;
7455 
7456   return SE->getCouldNotCompute();
7457 }
7458 
7459 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7460     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7461   for (auto &ENT : ExitNotTaken)
7462     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7463       return ENT.MaxNotTaken;
7464 
7465   return SE->getCouldNotCompute();
7466 }
7467 
7468 /// getConstantMax - Get the constant max backedge taken count for the loop.
7469 const SCEV *
7470 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7471   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7472     return !ENT.hasAlwaysTruePredicate();
7473   };
7474 
7475   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7476     return SE->getCouldNotCompute();
7477 
7478   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7479           isa<SCEVConstant>(getConstantMax())) &&
7480          "No point in having a non-constant max backedge taken count!");
7481   return getConstantMax();
7482 }
7483 
7484 const SCEV *
7485 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7486                                                    ScalarEvolution *SE) {
7487   if (!SymbolicMax)
7488     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7489   return SymbolicMax;
7490 }
7491 
7492 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7493     ScalarEvolution *SE) const {
7494   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7495     return !ENT.hasAlwaysTruePredicate();
7496   };
7497   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7498 }
7499 
7500 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const {
7501   return Operands.contains(S);
7502 }
7503 
7504 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7505     : ExactNotTaken(E), MaxNotTaken(E) {
7506   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7507           isa<SCEVConstant>(MaxNotTaken)) &&
7508          "No point in having a non-constant max backedge taken count!");
7509 }
7510 
7511 ScalarEvolution::ExitLimit::ExitLimit(
7512     const SCEV *E, const SCEV *M, bool MaxOrZero,
7513     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7514     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7515   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7516           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7517          "Exact is not allowed to be less precise than Max");
7518   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7519           isa<SCEVConstant>(MaxNotTaken)) &&
7520          "No point in having a non-constant max backedge taken count!");
7521   for (auto *PredSet : PredSetList)
7522     for (auto *P : *PredSet)
7523       addPredicate(P);
7524 }
7525 
7526 ScalarEvolution::ExitLimit::ExitLimit(
7527     const SCEV *E, const SCEV *M, bool MaxOrZero,
7528     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7529     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7530   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7531           isa<SCEVConstant>(MaxNotTaken)) &&
7532          "No point in having a non-constant max backedge taken count!");
7533 }
7534 
7535 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7536                                       bool MaxOrZero)
7537     : ExitLimit(E, M, MaxOrZero, None) {
7538   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7539           isa<SCEVConstant>(MaxNotTaken)) &&
7540          "No point in having a non-constant max backedge taken count!");
7541 }
7542 
7543 class SCEVRecordOperands {
7544   SmallPtrSetImpl<const SCEV *> &Operands;
7545 
7546 public:
7547   SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands)
7548     : Operands(Operands) {}
7549   bool follow(const SCEV *S) {
7550     Operands.insert(S);
7551     return true;
7552   }
7553   bool isDone() { return false; }
7554 };
7555 
7556 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7557 /// computable exit into a persistent ExitNotTakenInfo array.
7558 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7559     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7560     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7561     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7562   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7563 
7564   ExitNotTaken.reserve(ExitCounts.size());
7565   std::transform(
7566       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7567       [&](const EdgeExitInfo &EEI) {
7568         BasicBlock *ExitBB = EEI.first;
7569         const ExitLimit &EL = EEI.second;
7570         if (EL.Predicates.empty())
7571           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7572                                   nullptr);
7573 
7574         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7575         for (auto *Pred : EL.Predicates)
7576           Predicate->add(Pred);
7577 
7578         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7579                                 std::move(Predicate));
7580       });
7581   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7582           isa<SCEVConstant>(ConstantMax)) &&
7583          "No point in having a non-constant max backedge taken count!");
7584 
7585   SCEVRecordOperands RecordOperands(Operands);
7586   SCEVTraversal<SCEVRecordOperands> ST(RecordOperands);
7587   if (!isa<SCEVCouldNotCompute>(ConstantMax))
7588     ST.visitAll(ConstantMax);
7589   for (auto &ENT : ExitNotTaken)
7590     if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken))
7591       ST.visitAll(ENT.ExactNotTaken);
7592 }
7593 
7594 /// Compute the number of times the backedge of the specified loop will execute.
7595 ScalarEvolution::BackedgeTakenInfo
7596 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7597                                            bool AllowPredicates) {
7598   SmallVector<BasicBlock *, 8> ExitingBlocks;
7599   L->getExitingBlocks(ExitingBlocks);
7600 
7601   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7602 
7603   SmallVector<EdgeExitInfo, 4> ExitCounts;
7604   bool CouldComputeBECount = true;
7605   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7606   const SCEV *MustExitMaxBECount = nullptr;
7607   const SCEV *MayExitMaxBECount = nullptr;
7608   bool MustExitMaxOrZero = false;
7609 
7610   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7611   // and compute maxBECount.
7612   // Do a union of all the predicates here.
7613   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7614     BasicBlock *ExitBB = ExitingBlocks[i];
7615 
7616     // We canonicalize untaken exits to br (constant), ignore them so that
7617     // proving an exit untaken doesn't negatively impact our ability to reason
7618     // about the loop as whole.
7619     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7620       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7621         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7622         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7623           continue;
7624       }
7625 
7626     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7627 
7628     assert((AllowPredicates || EL.Predicates.empty()) &&
7629            "Predicated exit limit when predicates are not allowed!");
7630 
7631     // 1. For each exit that can be computed, add an entry to ExitCounts.
7632     // CouldComputeBECount is true only if all exits can be computed.
7633     if (EL.ExactNotTaken == getCouldNotCompute())
7634       // We couldn't compute an exact value for this exit, so
7635       // we won't be able to compute an exact value for the loop.
7636       CouldComputeBECount = false;
7637     else
7638       ExitCounts.emplace_back(ExitBB, EL);
7639 
7640     // 2. Derive the loop's MaxBECount from each exit's max number of
7641     // non-exiting iterations. Partition the loop exits into two kinds:
7642     // LoopMustExits and LoopMayExits.
7643     //
7644     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7645     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7646     // MaxBECount is the minimum EL.MaxNotTaken of computable
7647     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7648     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7649     // computable EL.MaxNotTaken.
7650     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7651         DT.dominates(ExitBB, Latch)) {
7652       if (!MustExitMaxBECount) {
7653         MustExitMaxBECount = EL.MaxNotTaken;
7654         MustExitMaxOrZero = EL.MaxOrZero;
7655       } else {
7656         MustExitMaxBECount =
7657             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7658       }
7659     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7660       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7661         MayExitMaxBECount = EL.MaxNotTaken;
7662       else {
7663         MayExitMaxBECount =
7664             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7665       }
7666     }
7667   }
7668   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7669     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7670   // The loop backedge will be taken the maximum or zero times if there's
7671   // a single exit that must be taken the maximum or zero times.
7672   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7673   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7674                            MaxBECount, MaxOrZero);
7675 }
7676 
7677 ScalarEvolution::ExitLimit
7678 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7679                                       bool AllowPredicates) {
7680   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7681   // If our exiting block does not dominate the latch, then its connection with
7682   // loop's exit limit may be far from trivial.
7683   const BasicBlock *Latch = L->getLoopLatch();
7684   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7685     return getCouldNotCompute();
7686 
7687   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7688   Instruction *Term = ExitingBlock->getTerminator();
7689   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7690     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7691     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7692     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7693            "It should have one successor in loop and one exit block!");
7694     // Proceed to the next level to examine the exit condition expression.
7695     return computeExitLimitFromCond(
7696         L, BI->getCondition(), ExitIfTrue,
7697         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7698   }
7699 
7700   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7701     // For switch, make sure that there is a single exit from the loop.
7702     BasicBlock *Exit = nullptr;
7703     for (auto *SBB : successors(ExitingBlock))
7704       if (!L->contains(SBB)) {
7705         if (Exit) // Multiple exit successors.
7706           return getCouldNotCompute();
7707         Exit = SBB;
7708       }
7709     assert(Exit && "Exiting block must have at least one exit");
7710     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7711                                                 /*ControlsExit=*/IsOnlyExit);
7712   }
7713 
7714   return getCouldNotCompute();
7715 }
7716 
7717 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7718     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7719     bool ControlsExit, bool AllowPredicates) {
7720   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7721   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7722                                         ControlsExit, AllowPredicates);
7723 }
7724 
7725 Optional<ScalarEvolution::ExitLimit>
7726 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7727                                       bool ExitIfTrue, bool ControlsExit,
7728                                       bool AllowPredicates) {
7729   (void)this->L;
7730   (void)this->ExitIfTrue;
7731   (void)this->AllowPredicates;
7732 
7733   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7734          this->AllowPredicates == AllowPredicates &&
7735          "Variance in assumed invariant key components!");
7736   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7737   if (Itr == TripCountMap.end())
7738     return None;
7739   return Itr->second;
7740 }
7741 
7742 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7743                                              bool ExitIfTrue,
7744                                              bool ControlsExit,
7745                                              bool AllowPredicates,
7746                                              const ExitLimit &EL) {
7747   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7748          this->AllowPredicates == AllowPredicates &&
7749          "Variance in assumed invariant key components!");
7750 
7751   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7752   assert(InsertResult.second && "Expected successful insertion!");
7753   (void)InsertResult;
7754   (void)ExitIfTrue;
7755 }
7756 
7757 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7758     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7759     bool ControlsExit, bool AllowPredicates) {
7760 
7761   if (auto MaybeEL =
7762           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7763     return *MaybeEL;
7764 
7765   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7766                                               ControlsExit, AllowPredicates);
7767   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7768   return EL;
7769 }
7770 
7771 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7772     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7773     bool ControlsExit, bool AllowPredicates) {
7774   // Handle BinOp conditions (And, Or).
7775   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7776           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7777     return *LimitFromBinOp;
7778 
7779   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7780   // Proceed to the next level to examine the icmp.
7781   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7782     ExitLimit EL =
7783         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7784     if (EL.hasFullInfo() || !AllowPredicates)
7785       return EL;
7786 
7787     // Try again, but use SCEV predicates this time.
7788     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7789                                     /*AllowPredicates=*/true);
7790   }
7791 
7792   // Check for a constant condition. These are normally stripped out by
7793   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7794   // preserve the CFG and is temporarily leaving constant conditions
7795   // in place.
7796   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7797     if (ExitIfTrue == !CI->getZExtValue())
7798       // The backedge is always taken.
7799       return getCouldNotCompute();
7800     else
7801       // The backedge is never taken.
7802       return getZero(CI->getType());
7803   }
7804 
7805   // If it's not an integer or pointer comparison then compute it the hard way.
7806   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7807 }
7808 
7809 Optional<ScalarEvolution::ExitLimit>
7810 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7811     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7812     bool ControlsExit, bool AllowPredicates) {
7813   // Check if the controlling expression for this loop is an And or Or.
7814   Value *Op0, *Op1;
7815   bool IsAnd = false;
7816   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7817     IsAnd = true;
7818   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7819     IsAnd = false;
7820   else
7821     return None;
7822 
7823   // EitherMayExit is true in these two cases:
7824   //   br (and Op0 Op1), loop, exit
7825   //   br (or  Op0 Op1), exit, loop
7826   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7827   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7828                                                  ControlsExit && !EitherMayExit,
7829                                                  AllowPredicates);
7830   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7831                                                  ControlsExit && !EitherMayExit,
7832                                                  AllowPredicates);
7833 
7834   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7835   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7836   if (isa<ConstantInt>(Op1))
7837     return Op1 == NeutralElement ? EL0 : EL1;
7838   if (isa<ConstantInt>(Op0))
7839     return Op0 == NeutralElement ? EL1 : EL0;
7840 
7841   const SCEV *BECount = getCouldNotCompute();
7842   const SCEV *MaxBECount = getCouldNotCompute();
7843   if (EitherMayExit) {
7844     // Both conditions must be same for the loop to continue executing.
7845     // Choose the less conservative count.
7846     // If ExitCond is a short-circuit form (select), using
7847     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7848     // To see the detailed examples, please see
7849     // test/Analysis/ScalarEvolution/exit-count-select.ll
7850     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7851     if (!PoisonSafe)
7852       // Even if ExitCond is select, we can safely derive BECount using both
7853       // EL0 and EL1 in these cases:
7854       // (1) EL0.ExactNotTaken is non-zero
7855       // (2) EL1.ExactNotTaken is non-poison
7856       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7857       //     it cannot be umin(0, ..))
7858       // The PoisonSafe assignment below is simplified and the assertion after
7859       // BECount calculation fully guarantees the condition (3).
7860       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7861                    isa<SCEVConstant>(EL1.ExactNotTaken);
7862     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7863         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7864       BECount =
7865           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7866 
7867       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7868       // it should have been simplified to zero (see the condition (3) above)
7869       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7870              BECount->isZero());
7871     }
7872     if (EL0.MaxNotTaken == getCouldNotCompute())
7873       MaxBECount = EL1.MaxNotTaken;
7874     else if (EL1.MaxNotTaken == getCouldNotCompute())
7875       MaxBECount = EL0.MaxNotTaken;
7876     else
7877       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7878   } else {
7879     // Both conditions must be same at the same time for the loop to exit.
7880     // For now, be conservative.
7881     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7882       BECount = EL0.ExactNotTaken;
7883   }
7884 
7885   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7886   // to be more aggressive when computing BECount than when computing
7887   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7888   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7889   // to not.
7890   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7891       !isa<SCEVCouldNotCompute>(BECount))
7892     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7893 
7894   return ExitLimit(BECount, MaxBECount, false,
7895                    { &EL0.Predicates, &EL1.Predicates });
7896 }
7897 
7898 ScalarEvolution::ExitLimit
7899 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7900                                           ICmpInst *ExitCond,
7901                                           bool ExitIfTrue,
7902                                           bool ControlsExit,
7903                                           bool AllowPredicates) {
7904   // If the condition was exit on true, convert the condition to exit on false
7905   ICmpInst::Predicate Pred;
7906   if (!ExitIfTrue)
7907     Pred = ExitCond->getPredicate();
7908   else
7909     Pred = ExitCond->getInversePredicate();
7910   const ICmpInst::Predicate OriginalPred = Pred;
7911 
7912   // Handle common loops like: for (X = "string"; *X; ++X)
7913   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7914     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7915       ExitLimit ItCnt =
7916         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7917       if (ItCnt.hasAnyInfo())
7918         return ItCnt;
7919     }
7920 
7921   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7922   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7923 
7924   // Try to evaluate any dependencies out of the loop.
7925   LHS = getSCEVAtScope(LHS, L);
7926   RHS = getSCEVAtScope(RHS, L);
7927 
7928   // At this point, we would like to compute how many iterations of the
7929   // loop the predicate will return true for these inputs.
7930   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7931     // If there is a loop-invariant, force it into the RHS.
7932     std::swap(LHS, RHS);
7933     Pred = ICmpInst::getSwappedPredicate(Pred);
7934   }
7935 
7936   // Simplify the operands before analyzing them.
7937   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7938 
7939   // If we have a comparison of a chrec against a constant, try to use value
7940   // ranges to answer this query.
7941   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7942     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7943       if (AddRec->getLoop() == L) {
7944         // Form the constant range.
7945         ConstantRange CompRange =
7946             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7947 
7948         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7949         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7950       }
7951 
7952   switch (Pred) {
7953   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7954     // Convert to: while (X-Y != 0)
7955     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7956                                 AllowPredicates);
7957     if (EL.hasAnyInfo()) return EL;
7958     break;
7959   }
7960   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7961     // Convert to: while (X-Y == 0)
7962     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7963     if (EL.hasAnyInfo()) return EL;
7964     break;
7965   }
7966   case ICmpInst::ICMP_SLT:
7967   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7968     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7969     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7970                                     AllowPredicates);
7971     if (EL.hasAnyInfo()) return EL;
7972     break;
7973   }
7974   case ICmpInst::ICMP_SGT:
7975   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7976     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7977     ExitLimit EL =
7978         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7979                             AllowPredicates);
7980     if (EL.hasAnyInfo()) return EL;
7981     break;
7982   }
7983   default:
7984     break;
7985   }
7986 
7987   auto *ExhaustiveCount =
7988       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7989 
7990   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7991     return ExhaustiveCount;
7992 
7993   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7994                                       ExitCond->getOperand(1), L, OriginalPred);
7995 }
7996 
7997 ScalarEvolution::ExitLimit
7998 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7999                                                       SwitchInst *Switch,
8000                                                       BasicBlock *ExitingBlock,
8001                                                       bool ControlsExit) {
8002   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8003 
8004   // Give up if the exit is the default dest of a switch.
8005   if (Switch->getDefaultDest() == ExitingBlock)
8006     return getCouldNotCompute();
8007 
8008   assert(L->contains(Switch->getDefaultDest()) &&
8009          "Default case must not exit the loop!");
8010   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8011   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8012 
8013   // while (X != Y) --> while (X-Y != 0)
8014   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8015   if (EL.hasAnyInfo())
8016     return EL;
8017 
8018   return getCouldNotCompute();
8019 }
8020 
8021 static ConstantInt *
8022 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8023                                 ScalarEvolution &SE) {
8024   const SCEV *InVal = SE.getConstant(C);
8025   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8026   assert(isa<SCEVConstant>(Val) &&
8027          "Evaluation of SCEV at constant didn't fold correctly?");
8028   return cast<SCEVConstant>(Val)->getValue();
8029 }
8030 
8031 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
8032 /// compute the backedge execution count.
8033 ScalarEvolution::ExitLimit
8034 ScalarEvolution::computeLoadConstantCompareExitLimit(
8035   LoadInst *LI,
8036   Constant *RHS,
8037   const Loop *L,
8038   ICmpInst::Predicate predicate) {
8039   if (LI->isVolatile()) return getCouldNotCompute();
8040 
8041   // Check to see if the loaded pointer is a getelementptr of a global.
8042   // TODO: Use SCEV instead of manually grubbing with GEPs.
8043   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
8044   if (!GEP) return getCouldNotCompute();
8045 
8046   // Make sure that it is really a constant global we are gepping, with an
8047   // initializer, and make sure the first IDX is really 0.
8048   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
8049   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
8050       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
8051       !cast<Constant>(GEP->getOperand(1))->isNullValue())
8052     return getCouldNotCompute();
8053 
8054   // Okay, we allow one non-constant index into the GEP instruction.
8055   Value *VarIdx = nullptr;
8056   std::vector<Constant*> Indexes;
8057   unsigned VarIdxNum = 0;
8058   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
8059     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
8060       Indexes.push_back(CI);
8061     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
8062       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
8063       VarIdx = GEP->getOperand(i);
8064       VarIdxNum = i-2;
8065       Indexes.push_back(nullptr);
8066     }
8067 
8068   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
8069   if (!VarIdx)
8070     return getCouldNotCompute();
8071 
8072   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
8073   // Check to see if X is a loop variant variable value now.
8074   const SCEV *Idx = getSCEV(VarIdx);
8075   Idx = getSCEVAtScope(Idx, L);
8076 
8077   // We can only recognize very limited forms of loop index expressions, in
8078   // particular, only affine AddRec's like {C1,+,C2}<L>.
8079   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
8080   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
8081       isLoopInvariant(IdxExpr, L) ||
8082       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
8083       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
8084     return getCouldNotCompute();
8085 
8086   unsigned MaxSteps = MaxBruteForceIterations;
8087   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
8088     ConstantInt *ItCst = ConstantInt::get(
8089                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
8090     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
8091 
8092     // Form the GEP offset.
8093     Indexes[VarIdxNum] = Val;
8094 
8095     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
8096                                                          Indexes);
8097     if (!Result) break;  // Cannot compute!
8098 
8099     // Evaluate the condition for this iteration.
8100     Result = ConstantExpr::getICmp(predicate, Result, RHS);
8101     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
8102     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
8103       ++NumArrayLenItCounts;
8104       return getConstant(ItCst);   // Found terminating iteration!
8105     }
8106   }
8107   return getCouldNotCompute();
8108 }
8109 
8110 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8111     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8112   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8113   if (!RHS)
8114     return getCouldNotCompute();
8115 
8116   const BasicBlock *Latch = L->getLoopLatch();
8117   if (!Latch)
8118     return getCouldNotCompute();
8119 
8120   const BasicBlock *Predecessor = L->getLoopPredecessor();
8121   if (!Predecessor)
8122     return getCouldNotCompute();
8123 
8124   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8125   // Return LHS in OutLHS and shift_opt in OutOpCode.
8126   auto MatchPositiveShift =
8127       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8128 
8129     using namespace PatternMatch;
8130 
8131     ConstantInt *ShiftAmt;
8132     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8133       OutOpCode = Instruction::LShr;
8134     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8135       OutOpCode = Instruction::AShr;
8136     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8137       OutOpCode = Instruction::Shl;
8138     else
8139       return false;
8140 
8141     return ShiftAmt->getValue().isStrictlyPositive();
8142   };
8143 
8144   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8145   //
8146   // loop:
8147   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8148   //   %iv.shifted = lshr i32 %iv, <positive constant>
8149   //
8150   // Return true on a successful match.  Return the corresponding PHI node (%iv
8151   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8152   auto MatchShiftRecurrence =
8153       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8154     Optional<Instruction::BinaryOps> PostShiftOpCode;
8155 
8156     {
8157       Instruction::BinaryOps OpC;
8158       Value *V;
8159 
8160       // If we encounter a shift instruction, "peel off" the shift operation,
8161       // and remember that we did so.  Later when we inspect %iv's backedge
8162       // value, we will make sure that the backedge value uses the same
8163       // operation.
8164       //
8165       // Note: the peeled shift operation does not have to be the same
8166       // instruction as the one feeding into the PHI's backedge value.  We only
8167       // really care about it being the same *kind* of shift instruction --
8168       // that's all that is required for our later inferences to hold.
8169       if (MatchPositiveShift(LHS, V, OpC)) {
8170         PostShiftOpCode = OpC;
8171         LHS = V;
8172       }
8173     }
8174 
8175     PNOut = dyn_cast<PHINode>(LHS);
8176     if (!PNOut || PNOut->getParent() != L->getHeader())
8177       return false;
8178 
8179     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8180     Value *OpLHS;
8181 
8182     return
8183         // The backedge value for the PHI node must be a shift by a positive
8184         // amount
8185         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8186 
8187         // of the PHI node itself
8188         OpLHS == PNOut &&
8189 
8190         // and the kind of shift should be match the kind of shift we peeled
8191         // off, if any.
8192         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8193   };
8194 
8195   PHINode *PN;
8196   Instruction::BinaryOps OpCode;
8197   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8198     return getCouldNotCompute();
8199 
8200   const DataLayout &DL = getDataLayout();
8201 
8202   // The key rationale for this optimization is that for some kinds of shift
8203   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8204   // within a finite number of iterations.  If the condition guarding the
8205   // backedge (in the sense that the backedge is taken if the condition is true)
8206   // is false for the value the shift recurrence stabilizes to, then we know
8207   // that the backedge is taken only a finite number of times.
8208 
8209   ConstantInt *StableValue = nullptr;
8210   switch (OpCode) {
8211   default:
8212     llvm_unreachable("Impossible case!");
8213 
8214   case Instruction::AShr: {
8215     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8216     // bitwidth(K) iterations.
8217     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8218     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8219                                        Predecessor->getTerminator(), &DT);
8220     auto *Ty = cast<IntegerType>(RHS->getType());
8221     if (Known.isNonNegative())
8222       StableValue = ConstantInt::get(Ty, 0);
8223     else if (Known.isNegative())
8224       StableValue = ConstantInt::get(Ty, -1, true);
8225     else
8226       return getCouldNotCompute();
8227 
8228     break;
8229   }
8230   case Instruction::LShr:
8231   case Instruction::Shl:
8232     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8233     // stabilize to 0 in at most bitwidth(K) iterations.
8234     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8235     break;
8236   }
8237 
8238   auto *Result =
8239       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8240   assert(Result->getType()->isIntegerTy(1) &&
8241          "Otherwise cannot be an operand to a branch instruction");
8242 
8243   if (Result->isZeroValue()) {
8244     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8245     const SCEV *UpperBound =
8246         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8247     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8248   }
8249 
8250   return getCouldNotCompute();
8251 }
8252 
8253 /// Return true if we can constant fold an instruction of the specified type,
8254 /// assuming that all operands were constants.
8255 static bool CanConstantFold(const Instruction *I) {
8256   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8257       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8258       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8259     return true;
8260 
8261   if (const CallInst *CI = dyn_cast<CallInst>(I))
8262     if (const Function *F = CI->getCalledFunction())
8263       return canConstantFoldCallTo(CI, F);
8264   return false;
8265 }
8266 
8267 /// Determine whether this instruction can constant evolve within this loop
8268 /// assuming its operands can all constant evolve.
8269 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8270   // An instruction outside of the loop can't be derived from a loop PHI.
8271   if (!L->contains(I)) return false;
8272 
8273   if (isa<PHINode>(I)) {
8274     // We don't currently keep track of the control flow needed to evaluate
8275     // PHIs, so we cannot handle PHIs inside of loops.
8276     return L->getHeader() == I->getParent();
8277   }
8278 
8279   // If we won't be able to constant fold this expression even if the operands
8280   // are constants, bail early.
8281   return CanConstantFold(I);
8282 }
8283 
8284 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8285 /// recursing through each instruction operand until reaching a loop header phi.
8286 static PHINode *
8287 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8288                                DenseMap<Instruction *, PHINode *> &PHIMap,
8289                                unsigned Depth) {
8290   if (Depth > MaxConstantEvolvingDepth)
8291     return nullptr;
8292 
8293   // Otherwise, we can evaluate this instruction if all of its operands are
8294   // constant or derived from a PHI node themselves.
8295   PHINode *PHI = nullptr;
8296   for (Value *Op : UseInst->operands()) {
8297     if (isa<Constant>(Op)) continue;
8298 
8299     Instruction *OpInst = dyn_cast<Instruction>(Op);
8300     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8301 
8302     PHINode *P = dyn_cast<PHINode>(OpInst);
8303     if (!P)
8304       // If this operand is already visited, reuse the prior result.
8305       // We may have P != PHI if this is the deepest point at which the
8306       // inconsistent paths meet.
8307       P = PHIMap.lookup(OpInst);
8308     if (!P) {
8309       // Recurse and memoize the results, whether a phi is found or not.
8310       // This recursive call invalidates pointers into PHIMap.
8311       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8312       PHIMap[OpInst] = P;
8313     }
8314     if (!P)
8315       return nullptr;  // Not evolving from PHI
8316     if (PHI && PHI != P)
8317       return nullptr;  // Evolving from multiple different PHIs.
8318     PHI = P;
8319   }
8320   // This is a expression evolving from a constant PHI!
8321   return PHI;
8322 }
8323 
8324 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8325 /// in the loop that V is derived from.  We allow arbitrary operations along the
8326 /// way, but the operands of an operation must either be constants or a value
8327 /// derived from a constant PHI.  If this expression does not fit with these
8328 /// constraints, return null.
8329 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8330   Instruction *I = dyn_cast<Instruction>(V);
8331   if (!I || !canConstantEvolve(I, L)) return nullptr;
8332 
8333   if (PHINode *PN = dyn_cast<PHINode>(I))
8334     return PN;
8335 
8336   // Record non-constant instructions contained by the loop.
8337   DenseMap<Instruction *, PHINode *> PHIMap;
8338   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8339 }
8340 
8341 /// EvaluateExpression - Given an expression that passes the
8342 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8343 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8344 /// reason, return null.
8345 static Constant *EvaluateExpression(Value *V, const Loop *L,
8346                                     DenseMap<Instruction *, Constant *> &Vals,
8347                                     const DataLayout &DL,
8348                                     const TargetLibraryInfo *TLI) {
8349   // Convenient constant check, but redundant for recursive calls.
8350   if (Constant *C = dyn_cast<Constant>(V)) return C;
8351   Instruction *I = dyn_cast<Instruction>(V);
8352   if (!I) return nullptr;
8353 
8354   if (Constant *C = Vals.lookup(I)) return C;
8355 
8356   // An instruction inside the loop depends on a value outside the loop that we
8357   // weren't given a mapping for, or a value such as a call inside the loop.
8358   if (!canConstantEvolve(I, L)) return nullptr;
8359 
8360   // An unmapped PHI can be due to a branch or another loop inside this loop,
8361   // or due to this not being the initial iteration through a loop where we
8362   // couldn't compute the evolution of this particular PHI last time.
8363   if (isa<PHINode>(I)) return nullptr;
8364 
8365   std::vector<Constant*> Operands(I->getNumOperands());
8366 
8367   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8368     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8369     if (!Operand) {
8370       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8371       if (!Operands[i]) return nullptr;
8372       continue;
8373     }
8374     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8375     Vals[Operand] = C;
8376     if (!C) return nullptr;
8377     Operands[i] = C;
8378   }
8379 
8380   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8381     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8382                                            Operands[1], DL, TLI);
8383   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8384     if (!LI->isVolatile())
8385       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8386   }
8387   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8388 }
8389 
8390 
8391 // If every incoming value to PN except the one for BB is a specific Constant,
8392 // return that, else return nullptr.
8393 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8394   Constant *IncomingVal = nullptr;
8395 
8396   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8397     if (PN->getIncomingBlock(i) == BB)
8398       continue;
8399 
8400     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8401     if (!CurrentVal)
8402       return nullptr;
8403 
8404     if (IncomingVal != CurrentVal) {
8405       if (IncomingVal)
8406         return nullptr;
8407       IncomingVal = CurrentVal;
8408     }
8409   }
8410 
8411   return IncomingVal;
8412 }
8413 
8414 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8415 /// in the header of its containing loop, we know the loop executes a
8416 /// constant number of times, and the PHI node is just a recurrence
8417 /// involving constants, fold it.
8418 Constant *
8419 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8420                                                    const APInt &BEs,
8421                                                    const Loop *L) {
8422   auto I = ConstantEvolutionLoopExitValue.find(PN);
8423   if (I != ConstantEvolutionLoopExitValue.end())
8424     return I->second;
8425 
8426   if (BEs.ugt(MaxBruteForceIterations))
8427     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8428 
8429   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8430 
8431   DenseMap<Instruction *, Constant *> CurrentIterVals;
8432   BasicBlock *Header = L->getHeader();
8433   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8434 
8435   BasicBlock *Latch = L->getLoopLatch();
8436   if (!Latch)
8437     return nullptr;
8438 
8439   for (PHINode &PHI : Header->phis()) {
8440     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8441       CurrentIterVals[&PHI] = StartCST;
8442   }
8443   if (!CurrentIterVals.count(PN))
8444     return RetVal = nullptr;
8445 
8446   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8447 
8448   // Execute the loop symbolically to determine the exit value.
8449   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8450          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8451 
8452   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8453   unsigned IterationNum = 0;
8454   const DataLayout &DL = getDataLayout();
8455   for (; ; ++IterationNum) {
8456     if (IterationNum == NumIterations)
8457       return RetVal = CurrentIterVals[PN];  // Got exit value!
8458 
8459     // Compute the value of the PHIs for the next iteration.
8460     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8461     DenseMap<Instruction *, Constant *> NextIterVals;
8462     Constant *NextPHI =
8463         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8464     if (!NextPHI)
8465       return nullptr;        // Couldn't evaluate!
8466     NextIterVals[PN] = NextPHI;
8467 
8468     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8469 
8470     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8471     // cease to be able to evaluate one of them or if they stop evolving,
8472     // because that doesn't necessarily prevent us from computing PN.
8473     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8474     for (const auto &I : CurrentIterVals) {
8475       PHINode *PHI = dyn_cast<PHINode>(I.first);
8476       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8477       PHIsToCompute.emplace_back(PHI, I.second);
8478     }
8479     // We use two distinct loops because EvaluateExpression may invalidate any
8480     // iterators into CurrentIterVals.
8481     for (const auto &I : PHIsToCompute) {
8482       PHINode *PHI = I.first;
8483       Constant *&NextPHI = NextIterVals[PHI];
8484       if (!NextPHI) {   // Not already computed.
8485         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8486         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8487       }
8488       if (NextPHI != I.second)
8489         StoppedEvolving = false;
8490     }
8491 
8492     // If all entries in CurrentIterVals == NextIterVals then we can stop
8493     // iterating, the loop can't continue to change.
8494     if (StoppedEvolving)
8495       return RetVal = CurrentIterVals[PN];
8496 
8497     CurrentIterVals.swap(NextIterVals);
8498   }
8499 }
8500 
8501 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8502                                                           Value *Cond,
8503                                                           bool ExitWhen) {
8504   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8505   if (!PN) return getCouldNotCompute();
8506 
8507   // If the loop is canonicalized, the PHI will have exactly two entries.
8508   // That's the only form we support here.
8509   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8510 
8511   DenseMap<Instruction *, Constant *> CurrentIterVals;
8512   BasicBlock *Header = L->getHeader();
8513   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8514 
8515   BasicBlock *Latch = L->getLoopLatch();
8516   assert(Latch && "Should follow from NumIncomingValues == 2!");
8517 
8518   for (PHINode &PHI : Header->phis()) {
8519     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8520       CurrentIterVals[&PHI] = StartCST;
8521   }
8522   if (!CurrentIterVals.count(PN))
8523     return getCouldNotCompute();
8524 
8525   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8526   // the loop symbolically to determine when the condition gets a value of
8527   // "ExitWhen".
8528   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8529   const DataLayout &DL = getDataLayout();
8530   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8531     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8532         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8533 
8534     // Couldn't symbolically evaluate.
8535     if (!CondVal) return getCouldNotCompute();
8536 
8537     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8538       ++NumBruteForceTripCountsComputed;
8539       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8540     }
8541 
8542     // Update all the PHI nodes for the next iteration.
8543     DenseMap<Instruction *, Constant *> NextIterVals;
8544 
8545     // Create a list of which PHIs we need to compute. We want to do this before
8546     // calling EvaluateExpression on them because that may invalidate iterators
8547     // into CurrentIterVals.
8548     SmallVector<PHINode *, 8> PHIsToCompute;
8549     for (const auto &I : CurrentIterVals) {
8550       PHINode *PHI = dyn_cast<PHINode>(I.first);
8551       if (!PHI || PHI->getParent() != Header) continue;
8552       PHIsToCompute.push_back(PHI);
8553     }
8554     for (PHINode *PHI : PHIsToCompute) {
8555       Constant *&NextPHI = NextIterVals[PHI];
8556       if (NextPHI) continue;    // Already computed!
8557 
8558       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8559       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8560     }
8561     CurrentIterVals.swap(NextIterVals);
8562   }
8563 
8564   // Too many iterations were needed to evaluate.
8565   return getCouldNotCompute();
8566 }
8567 
8568 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8569   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8570       ValuesAtScopes[V];
8571   // Check to see if we've folded this expression at this loop before.
8572   for (auto &LS : Values)
8573     if (LS.first == L)
8574       return LS.second ? LS.second : V;
8575 
8576   Values.emplace_back(L, nullptr);
8577 
8578   // Otherwise compute it.
8579   const SCEV *C = computeSCEVAtScope(V, L);
8580   for (auto &LS : reverse(ValuesAtScopes[V]))
8581     if (LS.first == L) {
8582       LS.second = C;
8583       break;
8584     }
8585   return C;
8586 }
8587 
8588 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8589 /// will return Constants for objects which aren't represented by a
8590 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8591 /// Returns NULL if the SCEV isn't representable as a Constant.
8592 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8593   switch (V->getSCEVType()) {
8594   case scCouldNotCompute:
8595   case scAddRecExpr:
8596     return nullptr;
8597   case scConstant:
8598     return cast<SCEVConstant>(V)->getValue();
8599   case scUnknown:
8600     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8601   case scSignExtend: {
8602     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8603     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8604       return ConstantExpr::getSExt(CastOp, SS->getType());
8605     return nullptr;
8606   }
8607   case scZeroExtend: {
8608     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8609     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8610       return ConstantExpr::getZExt(CastOp, SZ->getType());
8611     return nullptr;
8612   }
8613   case scPtrToInt: {
8614     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8615     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8616       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8617 
8618     return nullptr;
8619   }
8620   case scTruncate: {
8621     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8622     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8623       return ConstantExpr::getTrunc(CastOp, ST->getType());
8624     return nullptr;
8625   }
8626   case scAddExpr: {
8627     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8628     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8629       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8630         unsigned AS = PTy->getAddressSpace();
8631         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8632         C = ConstantExpr::getBitCast(C, DestPtrTy);
8633       }
8634       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8635         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8636         if (!C2)
8637           return nullptr;
8638 
8639         // First pointer!
8640         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8641           unsigned AS = C2->getType()->getPointerAddressSpace();
8642           std::swap(C, C2);
8643           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8644           // The offsets have been converted to bytes.  We can add bytes to an
8645           // i8* by GEP with the byte count in the first index.
8646           C = ConstantExpr::getBitCast(C, DestPtrTy);
8647         }
8648 
8649         // Don't bother trying to sum two pointers. We probably can't
8650         // statically compute a load that results from it anyway.
8651         if (C2->getType()->isPointerTy())
8652           return nullptr;
8653 
8654         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8655           if (PTy->getElementType()->isStructTy())
8656             C2 = ConstantExpr::getIntegerCast(
8657                 C2, Type::getInt32Ty(C->getContext()), true);
8658           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8659         } else
8660           C = ConstantExpr::getAdd(C, C2);
8661       }
8662       return C;
8663     }
8664     return nullptr;
8665   }
8666   case scMulExpr: {
8667     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8668     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8669       // Don't bother with pointers at all.
8670       if (C->getType()->isPointerTy())
8671         return nullptr;
8672       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8673         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8674         if (!C2 || C2->getType()->isPointerTy())
8675           return nullptr;
8676         C = ConstantExpr::getMul(C, C2);
8677       }
8678       return C;
8679     }
8680     return nullptr;
8681   }
8682   case scUDivExpr: {
8683     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8684     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8685       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8686         if (LHS->getType() == RHS->getType())
8687           return ConstantExpr::getUDiv(LHS, RHS);
8688     return nullptr;
8689   }
8690   case scSMaxExpr:
8691   case scUMaxExpr:
8692   case scSMinExpr:
8693   case scUMinExpr:
8694     return nullptr; // TODO: smax, umax, smin, umax.
8695   }
8696   llvm_unreachable("Unknown SCEV kind!");
8697 }
8698 
8699 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8700   if (isa<SCEVConstant>(V)) return V;
8701 
8702   // If this instruction is evolved from a constant-evolving PHI, compute the
8703   // exit value from the loop without using SCEVs.
8704   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8705     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8706       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8707         const Loop *CurrLoop = this->LI[I->getParent()];
8708         // Looking for loop exit value.
8709         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8710             PN->getParent() == CurrLoop->getHeader()) {
8711           // Okay, there is no closed form solution for the PHI node.  Check
8712           // to see if the loop that contains it has a known backedge-taken
8713           // count.  If so, we may be able to force computation of the exit
8714           // value.
8715           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8716           // This trivial case can show up in some degenerate cases where
8717           // the incoming IR has not yet been fully simplified.
8718           if (BackedgeTakenCount->isZero()) {
8719             Value *InitValue = nullptr;
8720             bool MultipleInitValues = false;
8721             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8722               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8723                 if (!InitValue)
8724                   InitValue = PN->getIncomingValue(i);
8725                 else if (InitValue != PN->getIncomingValue(i)) {
8726                   MultipleInitValues = true;
8727                   break;
8728                 }
8729               }
8730             }
8731             if (!MultipleInitValues && InitValue)
8732               return getSCEV(InitValue);
8733           }
8734           // Do we have a loop invariant value flowing around the backedge
8735           // for a loop which must execute the backedge?
8736           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8737               isKnownPositive(BackedgeTakenCount) &&
8738               PN->getNumIncomingValues() == 2) {
8739 
8740             unsigned InLoopPred =
8741                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8742             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8743             if (CurrLoop->isLoopInvariant(BackedgeVal))
8744               return getSCEV(BackedgeVal);
8745           }
8746           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8747             // Okay, we know how many times the containing loop executes.  If
8748             // this is a constant evolving PHI node, get the final value at
8749             // the specified iteration number.
8750             Constant *RV = getConstantEvolutionLoopExitValue(
8751                 PN, BTCC->getAPInt(), CurrLoop);
8752             if (RV) return getSCEV(RV);
8753           }
8754         }
8755 
8756         // If there is a single-input Phi, evaluate it at our scope. If we can
8757         // prove that this replacement does not break LCSSA form, use new value.
8758         if (PN->getNumOperands() == 1) {
8759           const SCEV *Input = getSCEV(PN->getOperand(0));
8760           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8761           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8762           // for the simplest case just support constants.
8763           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8764         }
8765       }
8766 
8767       // Okay, this is an expression that we cannot symbolically evaluate
8768       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8769       // the arguments into constants, and if so, try to constant propagate the
8770       // result.  This is particularly useful for computing loop exit values.
8771       if (CanConstantFold(I)) {
8772         SmallVector<Constant *, 4> Operands;
8773         bool MadeImprovement = false;
8774         for (Value *Op : I->operands()) {
8775           if (Constant *C = dyn_cast<Constant>(Op)) {
8776             Operands.push_back(C);
8777             continue;
8778           }
8779 
8780           // If any of the operands is non-constant and if they are
8781           // non-integer and non-pointer, don't even try to analyze them
8782           // with scev techniques.
8783           if (!isSCEVable(Op->getType()))
8784             return V;
8785 
8786           const SCEV *OrigV = getSCEV(Op);
8787           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8788           MadeImprovement |= OrigV != OpV;
8789 
8790           Constant *C = BuildConstantFromSCEV(OpV);
8791           if (!C) return V;
8792           if (C->getType() != Op->getType())
8793             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8794                                                               Op->getType(),
8795                                                               false),
8796                                       C, Op->getType());
8797           Operands.push_back(C);
8798         }
8799 
8800         // Check to see if getSCEVAtScope actually made an improvement.
8801         if (MadeImprovement) {
8802           Constant *C = nullptr;
8803           const DataLayout &DL = getDataLayout();
8804           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8805             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8806                                                 Operands[1], DL, &TLI);
8807           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8808             if (!Load->isVolatile())
8809               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8810                                                DL);
8811           } else
8812             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8813           if (!C) return V;
8814           return getSCEV(C);
8815         }
8816       }
8817     }
8818 
8819     // This is some other type of SCEVUnknown, just return it.
8820     return V;
8821   }
8822 
8823   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8824     // Avoid performing the look-up in the common case where the specified
8825     // expression has no loop-variant portions.
8826     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8827       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8828       if (OpAtScope != Comm->getOperand(i)) {
8829         // Okay, at least one of these operands is loop variant but might be
8830         // foldable.  Build a new instance of the folded commutative expression.
8831         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8832                                             Comm->op_begin()+i);
8833         NewOps.push_back(OpAtScope);
8834 
8835         for (++i; i != e; ++i) {
8836           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8837           NewOps.push_back(OpAtScope);
8838         }
8839         if (isa<SCEVAddExpr>(Comm))
8840           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8841         if (isa<SCEVMulExpr>(Comm))
8842           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8843         if (isa<SCEVMinMaxExpr>(Comm))
8844           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8845         llvm_unreachable("Unknown commutative SCEV type!");
8846       }
8847     }
8848     // If we got here, all operands are loop invariant.
8849     return Comm;
8850   }
8851 
8852   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8853     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8854     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8855     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8856       return Div;   // must be loop invariant
8857     return getUDivExpr(LHS, RHS);
8858   }
8859 
8860   // If this is a loop recurrence for a loop that does not contain L, then we
8861   // are dealing with the final value computed by the loop.
8862   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8863     // First, attempt to evaluate each operand.
8864     // Avoid performing the look-up in the common case where the specified
8865     // expression has no loop-variant portions.
8866     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8867       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8868       if (OpAtScope == AddRec->getOperand(i))
8869         continue;
8870 
8871       // Okay, at least one of these operands is loop variant but might be
8872       // foldable.  Build a new instance of the folded commutative expression.
8873       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8874                                           AddRec->op_begin()+i);
8875       NewOps.push_back(OpAtScope);
8876       for (++i; i != e; ++i)
8877         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8878 
8879       const SCEV *FoldedRec =
8880         getAddRecExpr(NewOps, AddRec->getLoop(),
8881                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8882       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8883       // The addrec may be folded to a nonrecurrence, for example, if the
8884       // induction variable is multiplied by zero after constant folding. Go
8885       // ahead and return the folded value.
8886       if (!AddRec)
8887         return FoldedRec;
8888       break;
8889     }
8890 
8891     // If the scope is outside the addrec's loop, evaluate it by using the
8892     // loop exit value of the addrec.
8893     if (!AddRec->getLoop()->contains(L)) {
8894       // To evaluate this recurrence, we need to know how many times the AddRec
8895       // loop iterates.  Compute this now.
8896       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8897       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8898 
8899       // Then, evaluate the AddRec.
8900       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8901     }
8902 
8903     return AddRec;
8904   }
8905 
8906   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8907     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8908     if (Op == Cast->getOperand())
8909       return Cast;  // must be loop invariant
8910     return getZeroExtendExpr(Op, Cast->getType());
8911   }
8912 
8913   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8914     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8915     if (Op == Cast->getOperand())
8916       return Cast;  // must be loop invariant
8917     return getSignExtendExpr(Op, Cast->getType());
8918   }
8919 
8920   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8921     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8922     if (Op == Cast->getOperand())
8923       return Cast;  // must be loop invariant
8924     return getTruncateExpr(Op, Cast->getType());
8925   }
8926 
8927   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8928     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8929     if (Op == Cast->getOperand())
8930       return Cast; // must be loop invariant
8931     return getPtrToIntExpr(Op, Cast->getType());
8932   }
8933 
8934   llvm_unreachable("Unknown SCEV type!");
8935 }
8936 
8937 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8938   return getSCEVAtScope(getSCEV(V), L);
8939 }
8940 
8941 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8942   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8943     return stripInjectiveFunctions(ZExt->getOperand());
8944   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8945     return stripInjectiveFunctions(SExt->getOperand());
8946   return S;
8947 }
8948 
8949 /// Finds the minimum unsigned root of the following equation:
8950 ///
8951 ///     A * X = B (mod N)
8952 ///
8953 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8954 /// A and B isn't important.
8955 ///
8956 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8957 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8958                                                ScalarEvolution &SE) {
8959   uint32_t BW = A.getBitWidth();
8960   assert(BW == SE.getTypeSizeInBits(B->getType()));
8961   assert(A != 0 && "A must be non-zero.");
8962 
8963   // 1. D = gcd(A, N)
8964   //
8965   // The gcd of A and N may have only one prime factor: 2. The number of
8966   // trailing zeros in A is its multiplicity
8967   uint32_t Mult2 = A.countTrailingZeros();
8968   // D = 2^Mult2
8969 
8970   // 2. Check if B is divisible by D.
8971   //
8972   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8973   // is not less than multiplicity of this prime factor for D.
8974   if (SE.GetMinTrailingZeros(B) < Mult2)
8975     return SE.getCouldNotCompute();
8976 
8977   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8978   // modulo (N / D).
8979   //
8980   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8981   // (N / D) in general. The inverse itself always fits into BW bits, though,
8982   // so we immediately truncate it.
8983   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8984   APInt Mod(BW + 1, 0);
8985   Mod.setBit(BW - Mult2);  // Mod = N / D
8986   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8987 
8988   // 4. Compute the minimum unsigned root of the equation:
8989   // I * (B / D) mod (N / D)
8990   // To simplify the computation, we factor out the divide by D:
8991   // (I * B mod N) / D
8992   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8993   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8994 }
8995 
8996 /// For a given quadratic addrec, generate coefficients of the corresponding
8997 /// quadratic equation, multiplied by a common value to ensure that they are
8998 /// integers.
8999 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9000 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9001 /// were multiplied by, and BitWidth is the bit width of the original addrec
9002 /// coefficients.
9003 /// This function returns None if the addrec coefficients are not compile-
9004 /// time constants.
9005 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9006 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9007   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9008   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9009   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9010   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9011   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9012                     << *AddRec << '\n');
9013 
9014   // We currently can only solve this if the coefficients are constants.
9015   if (!LC || !MC || !NC) {
9016     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9017     return None;
9018   }
9019 
9020   APInt L = LC->getAPInt();
9021   APInt M = MC->getAPInt();
9022   APInt N = NC->getAPInt();
9023   assert(!N.isNullValue() && "This is not a quadratic addrec");
9024 
9025   unsigned BitWidth = LC->getAPInt().getBitWidth();
9026   unsigned NewWidth = BitWidth + 1;
9027   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9028                     << BitWidth << '\n');
9029   // The sign-extension (as opposed to a zero-extension) here matches the
9030   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9031   N = N.sext(NewWidth);
9032   M = M.sext(NewWidth);
9033   L = L.sext(NewWidth);
9034 
9035   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9036   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9037   //   L+M, L+2M+N, L+3M+3N, ...
9038   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9039   //
9040   // The equation Acc = 0 is then
9041   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9042   // In a quadratic form it becomes:
9043   //   N n^2 + (2M-N) n + 2L = 0.
9044 
9045   APInt A = N;
9046   APInt B = 2 * M - A;
9047   APInt C = 2 * L;
9048   APInt T = APInt(NewWidth, 2);
9049   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9050                     << "x + " << C << ", coeff bw: " << NewWidth
9051                     << ", multiplied by " << T << '\n');
9052   return std::make_tuple(A, B, C, T, BitWidth);
9053 }
9054 
9055 /// Helper function to compare optional APInts:
9056 /// (a) if X and Y both exist, return min(X, Y),
9057 /// (b) if neither X nor Y exist, return None,
9058 /// (c) if exactly one of X and Y exists, return that value.
9059 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9060   if (X.hasValue() && Y.hasValue()) {
9061     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9062     APInt XW = X->sextOrSelf(W);
9063     APInt YW = Y->sextOrSelf(W);
9064     return XW.slt(YW) ? *X : *Y;
9065   }
9066   if (!X.hasValue() && !Y.hasValue())
9067     return None;
9068   return X.hasValue() ? *X : *Y;
9069 }
9070 
9071 /// Helper function to truncate an optional APInt to a given BitWidth.
9072 /// When solving addrec-related equations, it is preferable to return a value
9073 /// that has the same bit width as the original addrec's coefficients. If the
9074 /// solution fits in the original bit width, truncate it (except for i1).
9075 /// Returning a value of a different bit width may inhibit some optimizations.
9076 ///
9077 /// In general, a solution to a quadratic equation generated from an addrec
9078 /// may require BW+1 bits, where BW is the bit width of the addrec's
9079 /// coefficients. The reason is that the coefficients of the quadratic
9080 /// equation are BW+1 bits wide (to avoid truncation when converting from
9081 /// the addrec to the equation).
9082 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9083   if (!X.hasValue())
9084     return None;
9085   unsigned W = X->getBitWidth();
9086   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9087     return X->trunc(BitWidth);
9088   return X;
9089 }
9090 
9091 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9092 /// iterations. The values L, M, N are assumed to be signed, and they
9093 /// should all have the same bit widths.
9094 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9095 /// where BW is the bit width of the addrec's coefficients.
9096 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9097 /// returned as such, otherwise the bit width of the returned value may
9098 /// be greater than BW.
9099 ///
9100 /// This function returns None if
9101 /// (a) the addrec coefficients are not constant, or
9102 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9103 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9104 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9105 static Optional<APInt>
9106 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9107   APInt A, B, C, M;
9108   unsigned BitWidth;
9109   auto T = GetQuadraticEquation(AddRec);
9110   if (!T.hasValue())
9111     return None;
9112 
9113   std::tie(A, B, C, M, BitWidth) = *T;
9114   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9115   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9116   if (!X.hasValue())
9117     return None;
9118 
9119   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9120   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9121   if (!V->isZero())
9122     return None;
9123 
9124   return TruncIfPossible(X, BitWidth);
9125 }
9126 
9127 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9128 /// iterations. The values M, N are assumed to be signed, and they
9129 /// should all have the same bit widths.
9130 /// Find the least n such that c(n) does not belong to the given range,
9131 /// while c(n-1) does.
9132 ///
9133 /// This function returns None if
9134 /// (a) the addrec coefficients are not constant, or
9135 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9136 ///     bounds of the range.
9137 static Optional<APInt>
9138 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9139                           const ConstantRange &Range, ScalarEvolution &SE) {
9140   assert(AddRec->getOperand(0)->isZero() &&
9141          "Starting value of addrec should be 0");
9142   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9143                     << Range << ", addrec " << *AddRec << '\n');
9144   // This case is handled in getNumIterationsInRange. Here we can assume that
9145   // we start in the range.
9146   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9147          "Addrec's initial value should be in range");
9148 
9149   APInt A, B, C, M;
9150   unsigned BitWidth;
9151   auto T = GetQuadraticEquation(AddRec);
9152   if (!T.hasValue())
9153     return None;
9154 
9155   // Be careful about the return value: there can be two reasons for not
9156   // returning an actual number. First, if no solutions to the equations
9157   // were found, and second, if the solutions don't leave the given range.
9158   // The first case means that the actual solution is "unknown", the second
9159   // means that it's known, but not valid. If the solution is unknown, we
9160   // cannot make any conclusions.
9161   // Return a pair: the optional solution and a flag indicating if the
9162   // solution was found.
9163   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9164     // Solve for signed overflow and unsigned overflow, pick the lower
9165     // solution.
9166     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9167                       << Bound << " (before multiplying by " << M << ")\n");
9168     Bound *= M; // The quadratic equation multiplier.
9169 
9170     Optional<APInt> SO = None;
9171     if (BitWidth > 1) {
9172       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9173                            "signed overflow\n");
9174       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9175     }
9176     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9177                          "unsigned overflow\n");
9178     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9179                                                               BitWidth+1);
9180 
9181     auto LeavesRange = [&] (const APInt &X) {
9182       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9183       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9184       if (Range.contains(V0->getValue()))
9185         return false;
9186       // X should be at least 1, so X-1 is non-negative.
9187       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9188       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9189       if (Range.contains(V1->getValue()))
9190         return true;
9191       return false;
9192     };
9193 
9194     // If SolveQuadraticEquationWrap returns None, it means that there can
9195     // be a solution, but the function failed to find it. We cannot treat it
9196     // as "no solution".
9197     if (!SO.hasValue() || !UO.hasValue())
9198       return { None, false };
9199 
9200     // Check the smaller value first to see if it leaves the range.
9201     // At this point, both SO and UO must have values.
9202     Optional<APInt> Min = MinOptional(SO, UO);
9203     if (LeavesRange(*Min))
9204       return { Min, true };
9205     Optional<APInt> Max = Min == SO ? UO : SO;
9206     if (LeavesRange(*Max))
9207       return { Max, true };
9208 
9209     // Solutions were found, but were eliminated, hence the "true".
9210     return { None, true };
9211   };
9212 
9213   std::tie(A, B, C, M, BitWidth) = *T;
9214   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9215   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9216   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9217   auto SL = SolveForBoundary(Lower);
9218   auto SU = SolveForBoundary(Upper);
9219   // If any of the solutions was unknown, no meaninigful conclusions can
9220   // be made.
9221   if (!SL.second || !SU.second)
9222     return None;
9223 
9224   // Claim: The correct solution is not some value between Min and Max.
9225   //
9226   // Justification: Assuming that Min and Max are different values, one of
9227   // them is when the first signed overflow happens, the other is when the
9228   // first unsigned overflow happens. Crossing the range boundary is only
9229   // possible via an overflow (treating 0 as a special case of it, modeling
9230   // an overflow as crossing k*2^W for some k).
9231   //
9232   // The interesting case here is when Min was eliminated as an invalid
9233   // solution, but Max was not. The argument is that if there was another
9234   // overflow between Min and Max, it would also have been eliminated if
9235   // it was considered.
9236   //
9237   // For a given boundary, it is possible to have two overflows of the same
9238   // type (signed/unsigned) without having the other type in between: this
9239   // can happen when the vertex of the parabola is between the iterations
9240   // corresponding to the overflows. This is only possible when the two
9241   // overflows cross k*2^W for the same k. In such case, if the second one
9242   // left the range (and was the first one to do so), the first overflow
9243   // would have to enter the range, which would mean that either we had left
9244   // the range before or that we started outside of it. Both of these cases
9245   // are contradictions.
9246   //
9247   // Claim: In the case where SolveForBoundary returns None, the correct
9248   // solution is not some value between the Max for this boundary and the
9249   // Min of the other boundary.
9250   //
9251   // Justification: Assume that we had such Max_A and Min_B corresponding
9252   // to range boundaries A and B and such that Max_A < Min_B. If there was
9253   // a solution between Max_A and Min_B, it would have to be caused by an
9254   // overflow corresponding to either A or B. It cannot correspond to B,
9255   // since Min_B is the first occurrence of such an overflow. If it
9256   // corresponded to A, it would have to be either a signed or an unsigned
9257   // overflow that is larger than both eliminated overflows for A. But
9258   // between the eliminated overflows and this overflow, the values would
9259   // cover the entire value space, thus crossing the other boundary, which
9260   // is a contradiction.
9261 
9262   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9263 }
9264 
9265 ScalarEvolution::ExitLimit
9266 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9267                               bool AllowPredicates) {
9268 
9269   // This is only used for loops with a "x != y" exit test. The exit condition
9270   // is now expressed as a single expression, V = x-y. So the exit test is
9271   // effectively V != 0.  We know and take advantage of the fact that this
9272   // expression only being used in a comparison by zero context.
9273 
9274   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9275   // If the value is a constant
9276   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9277     // If the value is already zero, the branch will execute zero times.
9278     if (C->getValue()->isZero()) return C;
9279     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9280   }
9281 
9282   const SCEVAddRecExpr *AddRec =
9283       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9284 
9285   if (!AddRec && AllowPredicates)
9286     // Try to make this an AddRec using runtime tests, in the first X
9287     // iterations of this loop, where X is the SCEV expression found by the
9288     // algorithm below.
9289     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9290 
9291   if (!AddRec || AddRec->getLoop() != L)
9292     return getCouldNotCompute();
9293 
9294   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9295   // the quadratic equation to solve it.
9296   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9297     // We can only use this value if the chrec ends up with an exact zero
9298     // value at this index.  When solving for "X*X != 5", for example, we
9299     // should not accept a root of 2.
9300     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9301       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9302       return ExitLimit(R, R, false, Predicates);
9303     }
9304     return getCouldNotCompute();
9305   }
9306 
9307   // Otherwise we can only handle this if it is affine.
9308   if (!AddRec->isAffine())
9309     return getCouldNotCompute();
9310 
9311   // If this is an affine expression, the execution count of this branch is
9312   // the minimum unsigned root of the following equation:
9313   //
9314   //     Start + Step*N = 0 (mod 2^BW)
9315   //
9316   // equivalent to:
9317   //
9318   //             Step*N = -Start (mod 2^BW)
9319   //
9320   // where BW is the common bit width of Start and Step.
9321 
9322   // Get the initial value for the loop.
9323   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9324   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9325 
9326   // For now we handle only constant steps.
9327   //
9328   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9329   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9330   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9331   // We have not yet seen any such cases.
9332   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9333   if (!StepC || StepC->getValue()->isZero())
9334     return getCouldNotCompute();
9335 
9336   // For positive steps (counting up until unsigned overflow):
9337   //   N = -Start/Step (as unsigned)
9338   // For negative steps (counting down to zero):
9339   //   N = Start/-Step
9340   // First compute the unsigned distance from zero in the direction of Step.
9341   bool CountDown = StepC->getAPInt().isNegative();
9342   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9343 
9344   // Handle unitary steps, which cannot wraparound.
9345   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9346   //   N = Distance (as unsigned)
9347   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9348     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9349     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9350     if (MaxBECountBase.ult(MaxBECount))
9351       MaxBECount = MaxBECountBase;
9352 
9353     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9354     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9355     // case, and see if we can improve the bound.
9356     //
9357     // Explicitly handling this here is necessary because getUnsignedRange
9358     // isn't context-sensitive; it doesn't know that we only care about the
9359     // range inside the loop.
9360     const SCEV *Zero = getZero(Distance->getType());
9361     const SCEV *One = getOne(Distance->getType());
9362     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9363     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9364       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9365       // as "unsigned_max(Distance + 1) - 1".
9366       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9367       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9368     }
9369     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9370   }
9371 
9372   // If the condition controls loop exit (the loop exits only if the expression
9373   // is true) and the addition is no-wrap we can use unsigned divide to
9374   // compute the backedge count.  In this case, the step may not divide the
9375   // distance, but we don't care because if the condition is "missed" the loop
9376   // will have undefined behavior due to wrapping.
9377   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9378       loopHasNoAbnormalExits(AddRec->getLoop())) {
9379     const SCEV *Exact =
9380         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9381     const SCEV *Max = getCouldNotCompute();
9382     if (Exact != getCouldNotCompute()) {
9383       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
9384       APInt BaseMaxInt = getUnsignedRangeMax(Exact);
9385       if (BaseMaxInt.ult(MaxInt))
9386         Max = getConstant(BaseMaxInt);
9387       else
9388         Max = getConstant(MaxInt);
9389     }
9390     return ExitLimit(Exact, Max, false, Predicates);
9391   }
9392 
9393   // Solve the general equation.
9394   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9395                                                getNegativeSCEV(Start), *this);
9396   const SCEV *M = E == getCouldNotCompute()
9397                       ? E
9398                       : getConstant(getUnsignedRangeMax(E));
9399   return ExitLimit(E, M, false, Predicates);
9400 }
9401 
9402 ScalarEvolution::ExitLimit
9403 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9404   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9405   // handle them yet except for the trivial case.  This could be expanded in the
9406   // future as needed.
9407 
9408   // If the value is a constant, check to see if it is known to be non-zero
9409   // already.  If so, the backedge will execute zero times.
9410   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9411     if (!C->getValue()->isZero())
9412       return getZero(C->getType());
9413     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9414   }
9415 
9416   // We could implement others, but I really doubt anyone writes loops like
9417   // this, and if they did, they would already be constant folded.
9418   return getCouldNotCompute();
9419 }
9420 
9421 std::pair<const BasicBlock *, const BasicBlock *>
9422 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9423     const {
9424   // If the block has a unique predecessor, then there is no path from the
9425   // predecessor to the block that does not go through the direct edge
9426   // from the predecessor to the block.
9427   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9428     return {Pred, BB};
9429 
9430   // A loop's header is defined to be a block that dominates the loop.
9431   // If the header has a unique predecessor outside the loop, it must be
9432   // a block that has exactly one successor that can reach the loop.
9433   if (const Loop *L = LI.getLoopFor(BB))
9434     return {L->getLoopPredecessor(), L->getHeader()};
9435 
9436   return {nullptr, nullptr};
9437 }
9438 
9439 /// SCEV structural equivalence is usually sufficient for testing whether two
9440 /// expressions are equal, however for the purposes of looking for a condition
9441 /// guarding a loop, it can be useful to be a little more general, since a
9442 /// front-end may have replicated the controlling expression.
9443 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9444   // Quick check to see if they are the same SCEV.
9445   if (A == B) return true;
9446 
9447   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9448     // Not all instructions that are "identical" compute the same value.  For
9449     // instance, two distinct alloca instructions allocating the same type are
9450     // identical and do not read memory; but compute distinct values.
9451     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9452   };
9453 
9454   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9455   // two different instructions with the same value. Check for this case.
9456   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9457     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9458       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9459         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9460           if (ComputesEqualValues(AI, BI))
9461             return true;
9462 
9463   // Otherwise assume they may have a different value.
9464   return false;
9465 }
9466 
9467 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9468                                            const SCEV *&LHS, const SCEV *&RHS,
9469                                            unsigned Depth) {
9470   bool Changed = false;
9471   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9472   // '0 != 0'.
9473   auto TrivialCase = [&](bool TriviallyTrue) {
9474     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9475     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9476     return true;
9477   };
9478   // If we hit the max recursion limit bail out.
9479   if (Depth >= 3)
9480     return false;
9481 
9482   // Canonicalize a constant to the right side.
9483   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9484     // Check for both operands constant.
9485     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9486       if (ConstantExpr::getICmp(Pred,
9487                                 LHSC->getValue(),
9488                                 RHSC->getValue())->isNullValue())
9489         return TrivialCase(false);
9490       else
9491         return TrivialCase(true);
9492     }
9493     // Otherwise swap the operands to put the constant on the right.
9494     std::swap(LHS, RHS);
9495     Pred = ICmpInst::getSwappedPredicate(Pred);
9496     Changed = true;
9497   }
9498 
9499   // If we're comparing an addrec with a value which is loop-invariant in the
9500   // addrec's loop, put the addrec on the left. Also make a dominance check,
9501   // as both operands could be addrecs loop-invariant in each other's loop.
9502   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9503     const Loop *L = AR->getLoop();
9504     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9505       std::swap(LHS, RHS);
9506       Pred = ICmpInst::getSwappedPredicate(Pred);
9507       Changed = true;
9508     }
9509   }
9510 
9511   // If there's a constant operand, canonicalize comparisons with boundary
9512   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9513   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9514     const APInt &RA = RC->getAPInt();
9515 
9516     bool SimplifiedByConstantRange = false;
9517 
9518     if (!ICmpInst::isEquality(Pred)) {
9519       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9520       if (ExactCR.isFullSet())
9521         return TrivialCase(true);
9522       else if (ExactCR.isEmptySet())
9523         return TrivialCase(false);
9524 
9525       APInt NewRHS;
9526       CmpInst::Predicate NewPred;
9527       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9528           ICmpInst::isEquality(NewPred)) {
9529         // We were able to convert an inequality to an equality.
9530         Pred = NewPred;
9531         RHS = getConstant(NewRHS);
9532         Changed = SimplifiedByConstantRange = true;
9533       }
9534     }
9535 
9536     if (!SimplifiedByConstantRange) {
9537       switch (Pred) {
9538       default:
9539         break;
9540       case ICmpInst::ICMP_EQ:
9541       case ICmpInst::ICMP_NE:
9542         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9543         if (!RA)
9544           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9545             if (const SCEVMulExpr *ME =
9546                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9547               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9548                   ME->getOperand(0)->isAllOnesValue()) {
9549                 RHS = AE->getOperand(1);
9550                 LHS = ME->getOperand(1);
9551                 Changed = true;
9552               }
9553         break;
9554 
9555 
9556         // The "Should have been caught earlier!" messages refer to the fact
9557         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9558         // should have fired on the corresponding cases, and canonicalized the
9559         // check to trivial case.
9560 
9561       case ICmpInst::ICMP_UGE:
9562         assert(!RA.isMinValue() && "Should have been caught earlier!");
9563         Pred = ICmpInst::ICMP_UGT;
9564         RHS = getConstant(RA - 1);
9565         Changed = true;
9566         break;
9567       case ICmpInst::ICMP_ULE:
9568         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9569         Pred = ICmpInst::ICMP_ULT;
9570         RHS = getConstant(RA + 1);
9571         Changed = true;
9572         break;
9573       case ICmpInst::ICMP_SGE:
9574         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9575         Pred = ICmpInst::ICMP_SGT;
9576         RHS = getConstant(RA - 1);
9577         Changed = true;
9578         break;
9579       case ICmpInst::ICMP_SLE:
9580         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9581         Pred = ICmpInst::ICMP_SLT;
9582         RHS = getConstant(RA + 1);
9583         Changed = true;
9584         break;
9585       }
9586     }
9587   }
9588 
9589   // Check for obvious equality.
9590   if (HasSameValue(LHS, RHS)) {
9591     if (ICmpInst::isTrueWhenEqual(Pred))
9592       return TrivialCase(true);
9593     if (ICmpInst::isFalseWhenEqual(Pred))
9594       return TrivialCase(false);
9595   }
9596 
9597   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9598   // adding or subtracting 1 from one of the operands.
9599   switch (Pred) {
9600   case ICmpInst::ICMP_SLE:
9601     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9602       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9603                        SCEV::FlagNSW);
9604       Pred = ICmpInst::ICMP_SLT;
9605       Changed = true;
9606     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9607       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9608                        SCEV::FlagNSW);
9609       Pred = ICmpInst::ICMP_SLT;
9610       Changed = true;
9611     }
9612     break;
9613   case ICmpInst::ICMP_SGE:
9614     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9615       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9616                        SCEV::FlagNSW);
9617       Pred = ICmpInst::ICMP_SGT;
9618       Changed = true;
9619     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9620       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9621                        SCEV::FlagNSW);
9622       Pred = ICmpInst::ICMP_SGT;
9623       Changed = true;
9624     }
9625     break;
9626   case ICmpInst::ICMP_ULE:
9627     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9628       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9629                        SCEV::FlagNUW);
9630       Pred = ICmpInst::ICMP_ULT;
9631       Changed = true;
9632     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9633       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9634       Pred = ICmpInst::ICMP_ULT;
9635       Changed = true;
9636     }
9637     break;
9638   case ICmpInst::ICMP_UGE:
9639     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9640       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9641       Pred = ICmpInst::ICMP_UGT;
9642       Changed = true;
9643     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9644       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9645                        SCEV::FlagNUW);
9646       Pred = ICmpInst::ICMP_UGT;
9647       Changed = true;
9648     }
9649     break;
9650   default:
9651     break;
9652   }
9653 
9654   // TODO: More simplifications are possible here.
9655 
9656   // Recursively simplify until we either hit a recursion limit or nothing
9657   // changes.
9658   if (Changed)
9659     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9660 
9661   return Changed;
9662 }
9663 
9664 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9665   return getSignedRangeMax(S).isNegative();
9666 }
9667 
9668 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9669   return getSignedRangeMin(S).isStrictlyPositive();
9670 }
9671 
9672 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9673   return !getSignedRangeMin(S).isNegative();
9674 }
9675 
9676 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9677   return !getSignedRangeMax(S).isStrictlyPositive();
9678 }
9679 
9680 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9681   return isKnownNegative(S) || isKnownPositive(S);
9682 }
9683 
9684 std::pair<const SCEV *, const SCEV *>
9685 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9686   // Compute SCEV on entry of loop L.
9687   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9688   if (Start == getCouldNotCompute())
9689     return { Start, Start };
9690   // Compute post increment SCEV for loop L.
9691   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9692   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9693   return { Start, PostInc };
9694 }
9695 
9696 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9697                                           const SCEV *LHS, const SCEV *RHS) {
9698   // First collect all loops.
9699   SmallPtrSet<const Loop *, 8> LoopsUsed;
9700   getUsedLoops(LHS, LoopsUsed);
9701   getUsedLoops(RHS, LoopsUsed);
9702 
9703   if (LoopsUsed.empty())
9704     return false;
9705 
9706   // Domination relationship must be a linear order on collected loops.
9707 #ifndef NDEBUG
9708   for (auto *L1 : LoopsUsed)
9709     for (auto *L2 : LoopsUsed)
9710       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9711               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9712              "Domination relationship is not a linear order");
9713 #endif
9714 
9715   const Loop *MDL =
9716       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9717                         [&](const Loop *L1, const Loop *L2) {
9718          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9719        });
9720 
9721   // Get init and post increment value for LHS.
9722   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9723   // if LHS contains unknown non-invariant SCEV then bail out.
9724   if (SplitLHS.first == getCouldNotCompute())
9725     return false;
9726   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9727   // Get init and post increment value for RHS.
9728   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9729   // if RHS contains unknown non-invariant SCEV then bail out.
9730   if (SplitRHS.first == getCouldNotCompute())
9731     return false;
9732   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9733   // It is possible that init SCEV contains an invariant load but it does
9734   // not dominate MDL and is not available at MDL loop entry, so we should
9735   // check it here.
9736   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9737       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9738     return false;
9739 
9740   // It seems backedge guard check is faster than entry one so in some cases
9741   // it can speed up whole estimation by short circuit
9742   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9743                                      SplitRHS.second) &&
9744          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9745 }
9746 
9747 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9748                                        const SCEV *LHS, const SCEV *RHS) {
9749   // Canonicalize the inputs first.
9750   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9751 
9752   if (isKnownViaInduction(Pred, LHS, RHS))
9753     return true;
9754 
9755   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9756     return true;
9757 
9758   // Otherwise see what can be done with some simple reasoning.
9759   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9760 }
9761 
9762 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
9763                                                   const SCEV *LHS,
9764                                                   const SCEV *RHS) {
9765   if (isKnownPredicate(Pred, LHS, RHS))
9766     return true;
9767   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
9768     return false;
9769   return None;
9770 }
9771 
9772 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9773                                          const SCEV *LHS, const SCEV *RHS,
9774                                          const Instruction *Context) {
9775   // TODO: Analyze guards and assumes from Context's block.
9776   return isKnownPredicate(Pred, LHS, RHS) ||
9777          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9778 }
9779 
9780 Optional<bool>
9781 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
9782                                      const SCEV *RHS,
9783                                      const Instruction *Context) {
9784   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
9785   if (KnownWithoutContext)
9786     return KnownWithoutContext;
9787 
9788   if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS))
9789     return true;
9790   else if (isBasicBlockEntryGuardedByCond(Context->getParent(),
9791                                           ICmpInst::getInversePredicate(Pred),
9792                                           LHS, RHS))
9793     return false;
9794   return None;
9795 }
9796 
9797 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9798                                               const SCEVAddRecExpr *LHS,
9799                                               const SCEV *RHS) {
9800   const Loop *L = LHS->getLoop();
9801   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9802          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9803 }
9804 
9805 Optional<ScalarEvolution::MonotonicPredicateType>
9806 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9807                                            ICmpInst::Predicate Pred) {
9808   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9809 
9810 #ifndef NDEBUG
9811   // Verify an invariant: inverting the predicate should turn a monotonically
9812   // increasing change to a monotonically decreasing one, and vice versa.
9813   if (Result) {
9814     auto ResultSwapped =
9815         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9816 
9817     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9818     assert(ResultSwapped.getValue() != Result.getValue() &&
9819            "monotonicity should flip as we flip the predicate");
9820   }
9821 #endif
9822 
9823   return Result;
9824 }
9825 
9826 Optional<ScalarEvolution::MonotonicPredicateType>
9827 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9828                                                ICmpInst::Predicate Pred) {
9829   // A zero step value for LHS means the induction variable is essentially a
9830   // loop invariant value. We don't really depend on the predicate actually
9831   // flipping from false to true (for increasing predicates, and the other way
9832   // around for decreasing predicates), all we care about is that *if* the
9833   // predicate changes then it only changes from false to true.
9834   //
9835   // A zero step value in itself is not very useful, but there may be places
9836   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9837   // as general as possible.
9838 
9839   // Only handle LE/LT/GE/GT predicates.
9840   if (!ICmpInst::isRelational(Pred))
9841     return None;
9842 
9843   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9844   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9845          "Should be greater or less!");
9846 
9847   // Check that AR does not wrap.
9848   if (ICmpInst::isUnsigned(Pred)) {
9849     if (!LHS->hasNoUnsignedWrap())
9850       return None;
9851     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9852   } else {
9853     assert(ICmpInst::isSigned(Pred) &&
9854            "Relational predicate is either signed or unsigned!");
9855     if (!LHS->hasNoSignedWrap())
9856       return None;
9857 
9858     const SCEV *Step = LHS->getStepRecurrence(*this);
9859 
9860     if (isKnownNonNegative(Step))
9861       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9862 
9863     if (isKnownNonPositive(Step))
9864       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9865 
9866     return None;
9867   }
9868 }
9869 
9870 Optional<ScalarEvolution::LoopInvariantPredicate>
9871 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9872                                            const SCEV *LHS, const SCEV *RHS,
9873                                            const Loop *L) {
9874 
9875   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9876   if (!isLoopInvariant(RHS, L)) {
9877     if (!isLoopInvariant(LHS, L))
9878       return None;
9879 
9880     std::swap(LHS, RHS);
9881     Pred = ICmpInst::getSwappedPredicate(Pred);
9882   }
9883 
9884   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9885   if (!ArLHS || ArLHS->getLoop() != L)
9886     return None;
9887 
9888   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9889   if (!MonotonicType)
9890     return None;
9891   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9892   // true as the loop iterates, and the backedge is control dependent on
9893   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9894   //
9895   //   * if the predicate was false in the first iteration then the predicate
9896   //     is never evaluated again, since the loop exits without taking the
9897   //     backedge.
9898   //   * if the predicate was true in the first iteration then it will
9899   //     continue to be true for all future iterations since it is
9900   //     monotonically increasing.
9901   //
9902   // For both the above possibilities, we can replace the loop varying
9903   // predicate with its value on the first iteration of the loop (which is
9904   // loop invariant).
9905   //
9906   // A similar reasoning applies for a monotonically decreasing predicate, by
9907   // replacing true with false and false with true in the above two bullets.
9908   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9909   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9910 
9911   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9912     return None;
9913 
9914   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9915 }
9916 
9917 Optional<ScalarEvolution::LoopInvariantPredicate>
9918 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9919     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9920     const Instruction *Context, const SCEV *MaxIter) {
9921   // Try to prove the following set of facts:
9922   // - The predicate is monotonic in the iteration space.
9923   // - If the check does not fail on the 1st iteration:
9924   //   - No overflow will happen during first MaxIter iterations;
9925   //   - It will not fail on the MaxIter'th iteration.
9926   // If the check does fail on the 1st iteration, we leave the loop and no
9927   // other checks matter.
9928 
9929   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9930   if (!isLoopInvariant(RHS, L)) {
9931     if (!isLoopInvariant(LHS, L))
9932       return None;
9933 
9934     std::swap(LHS, RHS);
9935     Pred = ICmpInst::getSwappedPredicate(Pred);
9936   }
9937 
9938   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9939   if (!AR || AR->getLoop() != L)
9940     return None;
9941 
9942   // The predicate must be relational (i.e. <, <=, >=, >).
9943   if (!ICmpInst::isRelational(Pred))
9944     return None;
9945 
9946   // TODO: Support steps other than +/- 1.
9947   const SCEV *Step = AR->getStepRecurrence(*this);
9948   auto *One = getOne(Step->getType());
9949   auto *MinusOne = getNegativeSCEV(One);
9950   if (Step != One && Step != MinusOne)
9951     return None;
9952 
9953   // Type mismatch here means that MaxIter is potentially larger than max
9954   // unsigned value in start type, which mean we cannot prove no wrap for the
9955   // indvar.
9956   if (AR->getType() != MaxIter->getType())
9957     return None;
9958 
9959   // Value of IV on suggested last iteration.
9960   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9961   // Does it still meet the requirement?
9962   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
9963     return None;
9964   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9965   // not exceed max unsigned value of this type), this effectively proves
9966   // that there is no wrap during the iteration. To prove that there is no
9967   // signed/unsigned wrap, we need to check that
9968   // Start <= Last for step = 1 or Start >= Last for step = -1.
9969   ICmpInst::Predicate NoOverflowPred =
9970       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9971   if (Step == MinusOne)
9972     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9973   const SCEV *Start = AR->getStart();
9974   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9975     return None;
9976 
9977   // Everything is fine.
9978   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
9979 }
9980 
9981 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9982     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9983   if (HasSameValue(LHS, RHS))
9984     return ICmpInst::isTrueWhenEqual(Pred);
9985 
9986   // This code is split out from isKnownPredicate because it is called from
9987   // within isLoopEntryGuardedByCond.
9988 
9989   auto CheckRanges = [&](const ConstantRange &RangeLHS,
9990                          const ConstantRange &RangeRHS) {
9991     return RangeLHS.icmp(Pred, RangeRHS);
9992   };
9993 
9994   // The check at the top of the function catches the case where the values are
9995   // known to be equal.
9996   if (Pred == CmpInst::ICMP_EQ)
9997     return false;
9998 
9999   if (Pred == CmpInst::ICMP_NE)
10000     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10001            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
10002            isKnownNonZero(getMinusSCEV(LHS, RHS));
10003 
10004   if (CmpInst::isSigned(Pred))
10005     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10006 
10007   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10008 }
10009 
10010 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10011                                                     const SCEV *LHS,
10012                                                     const SCEV *RHS) {
10013   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
10014   // Return Y via OutY.
10015   auto MatchBinaryAddToConst =
10016       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
10017              SCEV::NoWrapFlags ExpectedFlags) {
10018     const SCEV *NonConstOp, *ConstOp;
10019     SCEV::NoWrapFlags FlagsPresent;
10020 
10021     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
10022         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
10023       return false;
10024 
10025     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
10026     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
10027   };
10028 
10029   APInt C;
10030 
10031   switch (Pred) {
10032   default:
10033     break;
10034 
10035   case ICmpInst::ICMP_SGE:
10036     std::swap(LHS, RHS);
10037     LLVM_FALLTHROUGH;
10038   case ICmpInst::ICMP_SLE:
10039     // X s<= (X + C)<nsw> if C >= 0
10040     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
10041       return true;
10042 
10043     // (X + C)<nsw> s<= X if C <= 0
10044     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
10045         !C.isStrictlyPositive())
10046       return true;
10047     break;
10048 
10049   case ICmpInst::ICMP_SGT:
10050     std::swap(LHS, RHS);
10051     LLVM_FALLTHROUGH;
10052   case ICmpInst::ICMP_SLT:
10053     // X s< (X + C)<nsw> if C > 0
10054     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
10055         C.isStrictlyPositive())
10056       return true;
10057 
10058     // (X + C)<nsw> s< X if C < 0
10059     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
10060       return true;
10061     break;
10062 
10063   case ICmpInst::ICMP_UGE:
10064     std::swap(LHS, RHS);
10065     LLVM_FALLTHROUGH;
10066   case ICmpInst::ICMP_ULE:
10067     // X u<= (X + C)<nuw> for any C
10068     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
10069       return true;
10070     break;
10071 
10072   case ICmpInst::ICMP_UGT:
10073     std::swap(LHS, RHS);
10074     LLVM_FALLTHROUGH;
10075   case ICmpInst::ICMP_ULT:
10076     // X u< (X + C)<nuw> if C != 0
10077     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
10078       return true;
10079     break;
10080   }
10081 
10082   return false;
10083 }
10084 
10085 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10086                                                    const SCEV *LHS,
10087                                                    const SCEV *RHS) {
10088   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10089     return false;
10090 
10091   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10092   // the stack can result in exponential time complexity.
10093   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10094 
10095   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10096   //
10097   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10098   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10099   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10100   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10101   // use isKnownPredicate later if needed.
10102   return isKnownNonNegative(RHS) &&
10103          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10104          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10105 }
10106 
10107 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10108                                         ICmpInst::Predicate Pred,
10109                                         const SCEV *LHS, const SCEV *RHS) {
10110   // No need to even try if we know the module has no guards.
10111   if (!HasGuards)
10112     return false;
10113 
10114   return any_of(*BB, [&](const Instruction &I) {
10115     using namespace llvm::PatternMatch;
10116 
10117     Value *Condition;
10118     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10119                          m_Value(Condition))) &&
10120            isImpliedCond(Pred, LHS, RHS, Condition, false);
10121   });
10122 }
10123 
10124 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10125 /// protected by a conditional between LHS and RHS.  This is used to
10126 /// to eliminate casts.
10127 bool
10128 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10129                                              ICmpInst::Predicate Pred,
10130                                              const SCEV *LHS, const SCEV *RHS) {
10131   // Interpret a null as meaning no loop, where there is obviously no guard
10132   // (interprocedural conditions notwithstanding).
10133   if (!L) return true;
10134 
10135   if (VerifyIR)
10136     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10137            "This cannot be done on broken IR!");
10138 
10139 
10140   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10141     return true;
10142 
10143   BasicBlock *Latch = L->getLoopLatch();
10144   if (!Latch)
10145     return false;
10146 
10147   BranchInst *LoopContinuePredicate =
10148     dyn_cast<BranchInst>(Latch->getTerminator());
10149   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10150       isImpliedCond(Pred, LHS, RHS,
10151                     LoopContinuePredicate->getCondition(),
10152                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10153     return true;
10154 
10155   // We don't want more than one activation of the following loops on the stack
10156   // -- that can lead to O(n!) time complexity.
10157   if (WalkingBEDominatingConds)
10158     return false;
10159 
10160   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10161 
10162   // See if we can exploit a trip count to prove the predicate.
10163   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10164   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10165   if (LatchBECount != getCouldNotCompute()) {
10166     // We know that Latch branches back to the loop header exactly
10167     // LatchBECount times.  This means the backdege condition at Latch is
10168     // equivalent to  "{0,+,1} u< LatchBECount".
10169     Type *Ty = LatchBECount->getType();
10170     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10171     const SCEV *LoopCounter =
10172       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10173     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10174                       LatchBECount))
10175       return true;
10176   }
10177 
10178   // Check conditions due to any @llvm.assume intrinsics.
10179   for (auto &AssumeVH : AC.assumptions()) {
10180     if (!AssumeVH)
10181       continue;
10182     auto *CI = cast<CallInst>(AssumeVH);
10183     if (!DT.dominates(CI, Latch->getTerminator()))
10184       continue;
10185 
10186     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10187       return true;
10188   }
10189 
10190   // If the loop is not reachable from the entry block, we risk running into an
10191   // infinite loop as we walk up into the dom tree.  These loops do not matter
10192   // anyway, so we just return a conservative answer when we see them.
10193   if (!DT.isReachableFromEntry(L->getHeader()))
10194     return false;
10195 
10196   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10197     return true;
10198 
10199   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10200        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10201     assert(DTN && "should reach the loop header before reaching the root!");
10202 
10203     BasicBlock *BB = DTN->getBlock();
10204     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10205       return true;
10206 
10207     BasicBlock *PBB = BB->getSinglePredecessor();
10208     if (!PBB)
10209       continue;
10210 
10211     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10212     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10213       continue;
10214 
10215     Value *Condition = ContinuePredicate->getCondition();
10216 
10217     // If we have an edge `E` within the loop body that dominates the only
10218     // latch, the condition guarding `E` also guards the backedge.  This
10219     // reasoning works only for loops with a single latch.
10220 
10221     BasicBlockEdge DominatingEdge(PBB, BB);
10222     if (DominatingEdge.isSingleEdge()) {
10223       // We're constructively (and conservatively) enumerating edges within the
10224       // loop body that dominate the latch.  The dominator tree better agree
10225       // with us on this:
10226       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10227 
10228       if (isImpliedCond(Pred, LHS, RHS, Condition,
10229                         BB != ContinuePredicate->getSuccessor(0)))
10230         return true;
10231     }
10232   }
10233 
10234   return false;
10235 }
10236 
10237 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10238                                                      ICmpInst::Predicate Pred,
10239                                                      const SCEV *LHS,
10240                                                      const SCEV *RHS) {
10241   if (VerifyIR)
10242     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10243            "This cannot be done on broken IR!");
10244 
10245   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10246   // the facts (a >= b && a != b) separately. A typical situation is when the
10247   // non-strict comparison is known from ranges and non-equality is known from
10248   // dominating predicates. If we are proving strict comparison, we always try
10249   // to prove non-equality and non-strict comparison separately.
10250   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10251   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10252   bool ProvedNonStrictComparison = false;
10253   bool ProvedNonEquality = false;
10254 
10255   auto SplitAndProve =
10256     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10257     if (!ProvedNonStrictComparison)
10258       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10259     if (!ProvedNonEquality)
10260       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10261     if (ProvedNonStrictComparison && ProvedNonEquality)
10262       return true;
10263     return false;
10264   };
10265 
10266   if (ProvingStrictComparison) {
10267     auto ProofFn = [&](ICmpInst::Predicate P) {
10268       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10269     };
10270     if (SplitAndProve(ProofFn))
10271       return true;
10272   }
10273 
10274   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10275   auto ProveViaGuard = [&](const BasicBlock *Block) {
10276     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10277       return true;
10278     if (ProvingStrictComparison) {
10279       auto ProofFn = [&](ICmpInst::Predicate P) {
10280         return isImpliedViaGuard(Block, P, LHS, RHS);
10281       };
10282       if (SplitAndProve(ProofFn))
10283         return true;
10284     }
10285     return false;
10286   };
10287 
10288   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10289   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10290     const Instruction *Context = &BB->front();
10291     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10292       return true;
10293     if (ProvingStrictComparison) {
10294       auto ProofFn = [&](ICmpInst::Predicate P) {
10295         return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context);
10296       };
10297       if (SplitAndProve(ProofFn))
10298         return true;
10299     }
10300     return false;
10301   };
10302 
10303   // Starting at the block's predecessor, climb up the predecessor chain, as long
10304   // as there are predecessors that can be found that have unique successors
10305   // leading to the original block.
10306   const Loop *ContainingLoop = LI.getLoopFor(BB);
10307   const BasicBlock *PredBB;
10308   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10309     PredBB = ContainingLoop->getLoopPredecessor();
10310   else
10311     PredBB = BB->getSinglePredecessor();
10312   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10313        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10314     if (ProveViaGuard(Pair.first))
10315       return true;
10316 
10317     const BranchInst *LoopEntryPredicate =
10318         dyn_cast<BranchInst>(Pair.first->getTerminator());
10319     if (!LoopEntryPredicate ||
10320         LoopEntryPredicate->isUnconditional())
10321       continue;
10322 
10323     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10324                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10325       return true;
10326   }
10327 
10328   // Check conditions due to any @llvm.assume intrinsics.
10329   for (auto &AssumeVH : AC.assumptions()) {
10330     if (!AssumeVH)
10331       continue;
10332     auto *CI = cast<CallInst>(AssumeVH);
10333     if (!DT.dominates(CI, BB))
10334       continue;
10335 
10336     if (ProveViaCond(CI->getArgOperand(0), false))
10337       return true;
10338   }
10339 
10340   return false;
10341 }
10342 
10343 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10344                                                ICmpInst::Predicate Pred,
10345                                                const SCEV *LHS,
10346                                                const SCEV *RHS) {
10347   // Interpret a null as meaning no loop, where there is obviously no guard
10348   // (interprocedural conditions notwithstanding).
10349   if (!L)
10350     return false;
10351 
10352   // Both LHS and RHS must be available at loop entry.
10353   assert(isAvailableAtLoopEntry(LHS, L) &&
10354          "LHS is not available at Loop Entry");
10355   assert(isAvailableAtLoopEntry(RHS, L) &&
10356          "RHS is not available at Loop Entry");
10357 
10358   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10359     return true;
10360 
10361   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10362 }
10363 
10364 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10365                                     const SCEV *RHS,
10366                                     const Value *FoundCondValue, bool Inverse,
10367                                     const Instruction *Context) {
10368   // False conditions implies anything. Do not bother analyzing it further.
10369   if (FoundCondValue ==
10370       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10371     return true;
10372 
10373   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10374     return false;
10375 
10376   auto ClearOnExit =
10377       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10378 
10379   // Recursively handle And and Or conditions.
10380   const Value *Op0, *Op1;
10381   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10382     if (!Inverse)
10383       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10384               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10385   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10386     if (Inverse)
10387       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10388               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10389   }
10390 
10391   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10392   if (!ICI) return false;
10393 
10394   // Now that we found a conditional branch that dominates the loop or controls
10395   // the loop latch. Check to see if it is the comparison we are looking for.
10396   ICmpInst::Predicate FoundPred;
10397   if (Inverse)
10398     FoundPred = ICI->getInversePredicate();
10399   else
10400     FoundPred = ICI->getPredicate();
10401 
10402   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10403   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10404 
10405   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10406 }
10407 
10408 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10409                                     const SCEV *RHS,
10410                                     ICmpInst::Predicate FoundPred,
10411                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10412                                     const Instruction *Context) {
10413   // Balance the types.
10414   if (getTypeSizeInBits(LHS->getType()) <
10415       getTypeSizeInBits(FoundLHS->getType())) {
10416     // For unsigned and equality predicates, try to prove that both found
10417     // operands fit into narrow unsigned range. If so, try to prove facts in
10418     // narrow types.
10419     if (!CmpInst::isSigned(FoundPred)) {
10420       auto *NarrowType = LHS->getType();
10421       auto *WideType = FoundLHS->getType();
10422       auto BitWidth = getTypeSizeInBits(NarrowType);
10423       const SCEV *MaxValue = getZeroExtendExpr(
10424           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10425       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10426           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10427         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10428         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10429         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10430                                        TruncFoundRHS, Context))
10431           return true;
10432       }
10433     }
10434 
10435     if (CmpInst::isSigned(Pred)) {
10436       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10437       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10438     } else {
10439       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10440       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10441     }
10442   } else if (getTypeSizeInBits(LHS->getType()) >
10443       getTypeSizeInBits(FoundLHS->getType())) {
10444     if (CmpInst::isSigned(FoundPred)) {
10445       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10446       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10447     } else {
10448       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10449       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10450     }
10451   }
10452   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10453                                     FoundRHS, Context);
10454 }
10455 
10456 bool ScalarEvolution::isImpliedCondBalancedTypes(
10457     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10458     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10459     const Instruction *Context) {
10460   assert(getTypeSizeInBits(LHS->getType()) ==
10461              getTypeSizeInBits(FoundLHS->getType()) &&
10462          "Types should be balanced!");
10463   // Canonicalize the query to match the way instcombine will have
10464   // canonicalized the comparison.
10465   if (SimplifyICmpOperands(Pred, LHS, RHS))
10466     if (LHS == RHS)
10467       return CmpInst::isTrueWhenEqual(Pred);
10468   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10469     if (FoundLHS == FoundRHS)
10470       return CmpInst::isFalseWhenEqual(FoundPred);
10471 
10472   // Check to see if we can make the LHS or RHS match.
10473   if (LHS == FoundRHS || RHS == FoundLHS) {
10474     if (isa<SCEVConstant>(RHS)) {
10475       std::swap(FoundLHS, FoundRHS);
10476       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10477     } else {
10478       std::swap(LHS, RHS);
10479       Pred = ICmpInst::getSwappedPredicate(Pred);
10480     }
10481   }
10482 
10483   // Check whether the found predicate is the same as the desired predicate.
10484   if (FoundPred == Pred)
10485     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10486 
10487   // Check whether swapping the found predicate makes it the same as the
10488   // desired predicate.
10489   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10490     // We can write the implication
10491     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10492     // using one of the following ways:
10493     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10494     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10495     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10496     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10497     // Forms 1. and 2. require swapping the operands of one condition. Don't
10498     // do this if it would break canonical constant/addrec ordering.
10499     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10500       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10501                                    Context);
10502     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10503       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10504 
10505     // There's no clear preference between forms 3. and 4., try both.
10506     return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10507                                  FoundLHS, FoundRHS, Context) ||
10508            isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10509                                  getNotSCEV(FoundRHS), Context);
10510   }
10511 
10512   // Unsigned comparison is the same as signed comparison when both the operands
10513   // are non-negative.
10514   if (CmpInst::isUnsigned(FoundPred) &&
10515       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10516       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10517     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10518 
10519   // Check if we can make progress by sharpening ranges.
10520   if (FoundPred == ICmpInst::ICMP_NE &&
10521       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10522 
10523     const SCEVConstant *C = nullptr;
10524     const SCEV *V = nullptr;
10525 
10526     if (isa<SCEVConstant>(FoundLHS)) {
10527       C = cast<SCEVConstant>(FoundLHS);
10528       V = FoundRHS;
10529     } else {
10530       C = cast<SCEVConstant>(FoundRHS);
10531       V = FoundLHS;
10532     }
10533 
10534     // The guarding predicate tells us that C != V. If the known range
10535     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10536     // range we consider has to correspond to same signedness as the
10537     // predicate we're interested in folding.
10538 
10539     APInt Min = ICmpInst::isSigned(Pred) ?
10540         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10541 
10542     if (Min == C->getAPInt()) {
10543       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10544       // This is true even if (Min + 1) wraps around -- in case of
10545       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10546 
10547       APInt SharperMin = Min + 1;
10548 
10549       switch (Pred) {
10550         case ICmpInst::ICMP_SGE:
10551         case ICmpInst::ICMP_UGE:
10552           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10553           // RHS, we're done.
10554           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10555                                     Context))
10556             return true;
10557           LLVM_FALLTHROUGH;
10558 
10559         case ICmpInst::ICMP_SGT:
10560         case ICmpInst::ICMP_UGT:
10561           // We know from the range information that (V `Pred` Min ||
10562           // V == Min).  We know from the guarding condition that !(V
10563           // == Min).  This gives us
10564           //
10565           //       V `Pred` Min || V == Min && !(V == Min)
10566           //   =>  V `Pred` Min
10567           //
10568           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10569 
10570           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10571                                     Context))
10572             return true;
10573           break;
10574 
10575         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10576         case ICmpInst::ICMP_SLE:
10577         case ICmpInst::ICMP_ULE:
10578           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10579                                     LHS, V, getConstant(SharperMin), Context))
10580             return true;
10581           LLVM_FALLTHROUGH;
10582 
10583         case ICmpInst::ICMP_SLT:
10584         case ICmpInst::ICMP_ULT:
10585           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10586                                     LHS, V, getConstant(Min), Context))
10587             return true;
10588           break;
10589 
10590         default:
10591           // No change
10592           break;
10593       }
10594     }
10595   }
10596 
10597   // Check whether the actual condition is beyond sufficient.
10598   if (FoundPred == ICmpInst::ICMP_EQ)
10599     if (ICmpInst::isTrueWhenEqual(Pred))
10600       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10601         return true;
10602   if (Pred == ICmpInst::ICMP_NE)
10603     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10604       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10605                                 Context))
10606         return true;
10607 
10608   // Otherwise assume the worst.
10609   return false;
10610 }
10611 
10612 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10613                                      const SCEV *&L, const SCEV *&R,
10614                                      SCEV::NoWrapFlags &Flags) {
10615   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10616   if (!AE || AE->getNumOperands() != 2)
10617     return false;
10618 
10619   L = AE->getOperand(0);
10620   R = AE->getOperand(1);
10621   Flags = AE->getNoWrapFlags();
10622   return true;
10623 }
10624 
10625 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10626                                                            const SCEV *Less) {
10627   // We avoid subtracting expressions here because this function is usually
10628   // fairly deep in the call stack (i.e. is called many times).
10629 
10630   // X - X = 0.
10631   if (More == Less)
10632     return APInt(getTypeSizeInBits(More->getType()), 0);
10633 
10634   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10635     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10636     const auto *MAR = cast<SCEVAddRecExpr>(More);
10637 
10638     if (LAR->getLoop() != MAR->getLoop())
10639       return None;
10640 
10641     // We look at affine expressions only; not for correctness but to keep
10642     // getStepRecurrence cheap.
10643     if (!LAR->isAffine() || !MAR->isAffine())
10644       return None;
10645 
10646     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10647       return None;
10648 
10649     Less = LAR->getStart();
10650     More = MAR->getStart();
10651 
10652     // fall through
10653   }
10654 
10655   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10656     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10657     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10658     return M - L;
10659   }
10660 
10661   SCEV::NoWrapFlags Flags;
10662   const SCEV *LLess = nullptr, *RLess = nullptr;
10663   const SCEV *LMore = nullptr, *RMore = nullptr;
10664   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10665   // Compare (X + C1) vs X.
10666   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10667     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10668       if (RLess == More)
10669         return -(C1->getAPInt());
10670 
10671   // Compare X vs (X + C2).
10672   if (splitBinaryAdd(More, LMore, RMore, Flags))
10673     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10674       if (RMore == Less)
10675         return C2->getAPInt();
10676 
10677   // Compare (X + C1) vs (X + C2).
10678   if (C1 && C2 && RLess == RMore)
10679     return C2->getAPInt() - C1->getAPInt();
10680 
10681   return None;
10682 }
10683 
10684 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10685     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10686     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10687   // Try to recognize the following pattern:
10688   //
10689   //   FoundRHS = ...
10690   // ...
10691   // loop:
10692   //   FoundLHS = {Start,+,W}
10693   // context_bb: // Basic block from the same loop
10694   //   known(Pred, FoundLHS, FoundRHS)
10695   //
10696   // If some predicate is known in the context of a loop, it is also known on
10697   // each iteration of this loop, including the first iteration. Therefore, in
10698   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10699   // prove the original pred using this fact.
10700   if (!Context)
10701     return false;
10702   const BasicBlock *ContextBB = Context->getParent();
10703   // Make sure AR varies in the context block.
10704   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10705     const Loop *L = AR->getLoop();
10706     // Make sure that context belongs to the loop and executes on 1st iteration
10707     // (if it ever executes at all).
10708     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10709       return false;
10710     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10711       return false;
10712     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10713   }
10714 
10715   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10716     const Loop *L = AR->getLoop();
10717     // Make sure that context belongs to the loop and executes on 1st iteration
10718     // (if it ever executes at all).
10719     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10720       return false;
10721     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10722       return false;
10723     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10724   }
10725 
10726   return false;
10727 }
10728 
10729 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10730     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10731     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10732   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10733     return false;
10734 
10735   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10736   if (!AddRecLHS)
10737     return false;
10738 
10739   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10740   if (!AddRecFoundLHS)
10741     return false;
10742 
10743   // We'd like to let SCEV reason about control dependencies, so we constrain
10744   // both the inequalities to be about add recurrences on the same loop.  This
10745   // way we can use isLoopEntryGuardedByCond later.
10746 
10747   const Loop *L = AddRecFoundLHS->getLoop();
10748   if (L != AddRecLHS->getLoop())
10749     return false;
10750 
10751   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10752   //
10753   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10754   //                                                                  ... (2)
10755   //
10756   // Informal proof for (2), assuming (1) [*]:
10757   //
10758   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10759   //
10760   // Then
10761   //
10762   //       FoundLHS s< FoundRHS s< INT_MIN - C
10763   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10764   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10765   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10766   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10767   // <=>  FoundLHS + C s< FoundRHS + C
10768   //
10769   // [*]: (1) can be proved by ruling out overflow.
10770   //
10771   // [**]: This can be proved by analyzing all the four possibilities:
10772   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10773   //    (A s>= 0, B s>= 0).
10774   //
10775   // Note:
10776   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10777   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10778   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10779   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10780   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10781   // C)".
10782 
10783   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10784   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10785   if (!LDiff || !RDiff || *LDiff != *RDiff)
10786     return false;
10787 
10788   if (LDiff->isMinValue())
10789     return true;
10790 
10791   APInt FoundRHSLimit;
10792 
10793   if (Pred == CmpInst::ICMP_ULT) {
10794     FoundRHSLimit = -(*RDiff);
10795   } else {
10796     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10797     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10798   }
10799 
10800   // Try to prove (1) or (2), as needed.
10801   return isAvailableAtLoopEntry(FoundRHS, L) &&
10802          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10803                                   getConstant(FoundRHSLimit));
10804 }
10805 
10806 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10807                                         const SCEV *LHS, const SCEV *RHS,
10808                                         const SCEV *FoundLHS,
10809                                         const SCEV *FoundRHS, unsigned Depth) {
10810   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10811 
10812   auto ClearOnExit = make_scope_exit([&]() {
10813     if (LPhi) {
10814       bool Erased = PendingMerges.erase(LPhi);
10815       assert(Erased && "Failed to erase LPhi!");
10816       (void)Erased;
10817     }
10818     if (RPhi) {
10819       bool Erased = PendingMerges.erase(RPhi);
10820       assert(Erased && "Failed to erase RPhi!");
10821       (void)Erased;
10822     }
10823   });
10824 
10825   // Find respective Phis and check that they are not being pending.
10826   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10827     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10828       if (!PendingMerges.insert(Phi).second)
10829         return false;
10830       LPhi = Phi;
10831     }
10832   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10833     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10834       // If we detect a loop of Phi nodes being processed by this method, for
10835       // example:
10836       //
10837       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10838       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10839       //
10840       // we don't want to deal with a case that complex, so return conservative
10841       // answer false.
10842       if (!PendingMerges.insert(Phi).second)
10843         return false;
10844       RPhi = Phi;
10845     }
10846 
10847   // If none of LHS, RHS is a Phi, nothing to do here.
10848   if (!LPhi && !RPhi)
10849     return false;
10850 
10851   // If there is a SCEVUnknown Phi we are interested in, make it left.
10852   if (!LPhi) {
10853     std::swap(LHS, RHS);
10854     std::swap(FoundLHS, FoundRHS);
10855     std::swap(LPhi, RPhi);
10856     Pred = ICmpInst::getSwappedPredicate(Pred);
10857   }
10858 
10859   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10860   const BasicBlock *LBB = LPhi->getParent();
10861   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10862 
10863   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10864     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10865            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10866            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10867   };
10868 
10869   if (RPhi && RPhi->getParent() == LBB) {
10870     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10871     // If we compare two Phis from the same block, and for each entry block
10872     // the predicate is true for incoming values from this block, then the
10873     // predicate is also true for the Phis.
10874     for (const BasicBlock *IncBB : predecessors(LBB)) {
10875       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10876       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10877       if (!ProvedEasily(L, R))
10878         return false;
10879     }
10880   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10881     // Case two: RHS is also a Phi from the same basic block, and it is an
10882     // AddRec. It means that there is a loop which has both AddRec and Unknown
10883     // PHIs, for it we can compare incoming values of AddRec from above the loop
10884     // and latch with their respective incoming values of LPhi.
10885     // TODO: Generalize to handle loops with many inputs in a header.
10886     if (LPhi->getNumIncomingValues() != 2) return false;
10887 
10888     auto *RLoop = RAR->getLoop();
10889     auto *Predecessor = RLoop->getLoopPredecessor();
10890     assert(Predecessor && "Loop with AddRec with no predecessor?");
10891     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10892     if (!ProvedEasily(L1, RAR->getStart()))
10893       return false;
10894     auto *Latch = RLoop->getLoopLatch();
10895     assert(Latch && "Loop with AddRec with no latch?");
10896     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10897     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10898       return false;
10899   } else {
10900     // In all other cases go over inputs of LHS and compare each of them to RHS,
10901     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10902     // At this point RHS is either a non-Phi, or it is a Phi from some block
10903     // different from LBB.
10904     for (const BasicBlock *IncBB : predecessors(LBB)) {
10905       // Check that RHS is available in this block.
10906       if (!dominates(RHS, IncBB))
10907         return false;
10908       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10909       // Make sure L does not refer to a value from a potentially previous
10910       // iteration of a loop.
10911       if (!properlyDominates(L, IncBB))
10912         return false;
10913       if (!ProvedEasily(L, RHS))
10914         return false;
10915     }
10916   }
10917   return true;
10918 }
10919 
10920 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10921                                             const SCEV *LHS, const SCEV *RHS,
10922                                             const SCEV *FoundLHS,
10923                                             const SCEV *FoundRHS,
10924                                             const Instruction *Context) {
10925   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10926     return true;
10927 
10928   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10929     return true;
10930 
10931   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10932                                           Context))
10933     return true;
10934 
10935   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10936                                      FoundLHS, FoundRHS);
10937 }
10938 
10939 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10940 template <typename MinMaxExprType>
10941 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10942                                  const SCEV *Candidate) {
10943   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10944   if (!MinMaxExpr)
10945     return false;
10946 
10947   return is_contained(MinMaxExpr->operands(), Candidate);
10948 }
10949 
10950 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10951                                            ICmpInst::Predicate Pred,
10952                                            const SCEV *LHS, const SCEV *RHS) {
10953   // If both sides are affine addrecs for the same loop, with equal
10954   // steps, and we know the recurrences don't wrap, then we only
10955   // need to check the predicate on the starting values.
10956 
10957   if (!ICmpInst::isRelational(Pred))
10958     return false;
10959 
10960   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10961   if (!LAR)
10962     return false;
10963   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10964   if (!RAR)
10965     return false;
10966   if (LAR->getLoop() != RAR->getLoop())
10967     return false;
10968   if (!LAR->isAffine() || !RAR->isAffine())
10969     return false;
10970 
10971   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10972     return false;
10973 
10974   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10975                          SCEV::FlagNSW : SCEV::FlagNUW;
10976   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10977     return false;
10978 
10979   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10980 }
10981 
10982 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10983 /// expression?
10984 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10985                                         ICmpInst::Predicate Pred,
10986                                         const SCEV *LHS, const SCEV *RHS) {
10987   switch (Pred) {
10988   default:
10989     return false;
10990 
10991   case ICmpInst::ICMP_SGE:
10992     std::swap(LHS, RHS);
10993     LLVM_FALLTHROUGH;
10994   case ICmpInst::ICMP_SLE:
10995     return
10996         // min(A, ...) <= A
10997         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10998         // A <= max(A, ...)
10999         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11000 
11001   case ICmpInst::ICMP_UGE:
11002     std::swap(LHS, RHS);
11003     LLVM_FALLTHROUGH;
11004   case ICmpInst::ICMP_ULE:
11005     return
11006         // min(A, ...) <= A
11007         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11008         // A <= max(A, ...)
11009         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11010   }
11011 
11012   llvm_unreachable("covered switch fell through?!");
11013 }
11014 
11015 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11016                                              const SCEV *LHS, const SCEV *RHS,
11017                                              const SCEV *FoundLHS,
11018                                              const SCEV *FoundRHS,
11019                                              unsigned Depth) {
11020   assert(getTypeSizeInBits(LHS->getType()) ==
11021              getTypeSizeInBits(RHS->getType()) &&
11022          "LHS and RHS have different sizes?");
11023   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11024              getTypeSizeInBits(FoundRHS->getType()) &&
11025          "FoundLHS and FoundRHS have different sizes?");
11026   // We want to avoid hurting the compile time with analysis of too big trees.
11027   if (Depth > MaxSCEVOperationsImplicationDepth)
11028     return false;
11029 
11030   // We only want to work with GT comparison so far.
11031   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11032     Pred = CmpInst::getSwappedPredicate(Pred);
11033     std::swap(LHS, RHS);
11034     std::swap(FoundLHS, FoundRHS);
11035   }
11036 
11037   // For unsigned, try to reduce it to corresponding signed comparison.
11038   if (Pred == ICmpInst::ICMP_UGT)
11039     // We can replace unsigned predicate with its signed counterpart if all
11040     // involved values are non-negative.
11041     // TODO: We could have better support for unsigned.
11042     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11043       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11044       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11045       // use this fact to prove that LHS and RHS are non-negative.
11046       const SCEV *MinusOne = getMinusOne(LHS->getType());
11047       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11048                                 FoundRHS) &&
11049           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11050                                 FoundRHS))
11051         Pred = ICmpInst::ICMP_SGT;
11052     }
11053 
11054   if (Pred != ICmpInst::ICMP_SGT)
11055     return false;
11056 
11057   auto GetOpFromSExt = [&](const SCEV *S) {
11058     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11059       return Ext->getOperand();
11060     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11061     // the constant in some cases.
11062     return S;
11063   };
11064 
11065   // Acquire values from extensions.
11066   auto *OrigLHS = LHS;
11067   auto *OrigFoundLHS = FoundLHS;
11068   LHS = GetOpFromSExt(LHS);
11069   FoundLHS = GetOpFromSExt(FoundLHS);
11070 
11071   // Is the SGT predicate can be proved trivially or using the found context.
11072   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11073     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11074            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11075                                   FoundRHS, Depth + 1);
11076   };
11077 
11078   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11079     // We want to avoid creation of any new non-constant SCEV. Since we are
11080     // going to compare the operands to RHS, we should be certain that we don't
11081     // need any size extensions for this. So let's decline all cases when the
11082     // sizes of types of LHS and RHS do not match.
11083     // TODO: Maybe try to get RHS from sext to catch more cases?
11084     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11085       return false;
11086 
11087     // Should not overflow.
11088     if (!LHSAddExpr->hasNoSignedWrap())
11089       return false;
11090 
11091     auto *LL = LHSAddExpr->getOperand(0);
11092     auto *LR = LHSAddExpr->getOperand(1);
11093     auto *MinusOne = getMinusOne(RHS->getType());
11094 
11095     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11096     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11097       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11098     };
11099     // Try to prove the following rule:
11100     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11101     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11102     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11103       return true;
11104   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11105     Value *LL, *LR;
11106     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11107 
11108     using namespace llvm::PatternMatch;
11109 
11110     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11111       // Rules for division.
11112       // We are going to perform some comparisons with Denominator and its
11113       // derivative expressions. In general case, creating a SCEV for it may
11114       // lead to a complex analysis of the entire graph, and in particular it
11115       // can request trip count recalculation for the same loop. This would
11116       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11117       // this, we only want to create SCEVs that are constants in this section.
11118       // So we bail if Denominator is not a constant.
11119       if (!isa<ConstantInt>(LR))
11120         return false;
11121 
11122       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11123 
11124       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11125       // then a SCEV for the numerator already exists and matches with FoundLHS.
11126       auto *Numerator = getExistingSCEV(LL);
11127       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11128         return false;
11129 
11130       // Make sure that the numerator matches with FoundLHS and the denominator
11131       // is positive.
11132       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11133         return false;
11134 
11135       auto *DTy = Denominator->getType();
11136       auto *FRHSTy = FoundRHS->getType();
11137       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11138         // One of types is a pointer and another one is not. We cannot extend
11139         // them properly to a wider type, so let us just reject this case.
11140         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11141         // to avoid this check.
11142         return false;
11143 
11144       // Given that:
11145       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11146       auto *WTy = getWiderType(DTy, FRHSTy);
11147       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11148       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11149 
11150       // Try to prove the following rule:
11151       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11152       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11153       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11154       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11155       if (isKnownNonPositive(RHS) &&
11156           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11157         return true;
11158 
11159       // Try to prove the following rule:
11160       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11161       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11162       // If we divide it by Denominator > 2, then:
11163       // 1. If FoundLHS is negative, then the result is 0.
11164       // 2. If FoundLHS is non-negative, then the result is non-negative.
11165       // Anyways, the result is non-negative.
11166       auto *MinusOne = getMinusOne(WTy);
11167       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11168       if (isKnownNegative(RHS) &&
11169           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11170         return true;
11171     }
11172   }
11173 
11174   // If our expression contained SCEVUnknown Phis, and we split it down and now
11175   // need to prove something for them, try to prove the predicate for every
11176   // possible incoming values of those Phis.
11177   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11178     return true;
11179 
11180   return false;
11181 }
11182 
11183 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11184                                         const SCEV *LHS, const SCEV *RHS) {
11185   // zext x u<= sext x, sext x s<= zext x
11186   switch (Pred) {
11187   case ICmpInst::ICMP_SGE:
11188     std::swap(LHS, RHS);
11189     LLVM_FALLTHROUGH;
11190   case ICmpInst::ICMP_SLE: {
11191     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11192     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11193     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11194     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11195       return true;
11196     break;
11197   }
11198   case ICmpInst::ICMP_UGE:
11199     std::swap(LHS, RHS);
11200     LLVM_FALLTHROUGH;
11201   case ICmpInst::ICMP_ULE: {
11202     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11203     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11204     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11205     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11206       return true;
11207     break;
11208   }
11209   default:
11210     break;
11211   };
11212   return false;
11213 }
11214 
11215 bool
11216 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11217                                            const SCEV *LHS, const SCEV *RHS) {
11218   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11219          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11220          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11221          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11222          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11223 }
11224 
11225 bool
11226 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11227                                              const SCEV *LHS, const SCEV *RHS,
11228                                              const SCEV *FoundLHS,
11229                                              const SCEV *FoundRHS) {
11230   switch (Pred) {
11231   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11232   case ICmpInst::ICMP_EQ:
11233   case ICmpInst::ICMP_NE:
11234     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11235       return true;
11236     break;
11237   case ICmpInst::ICMP_SLT:
11238   case ICmpInst::ICMP_SLE:
11239     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11240         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11241       return true;
11242     break;
11243   case ICmpInst::ICMP_SGT:
11244   case ICmpInst::ICMP_SGE:
11245     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11246         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11247       return true;
11248     break;
11249   case ICmpInst::ICMP_ULT:
11250   case ICmpInst::ICMP_ULE:
11251     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11252         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11253       return true;
11254     break;
11255   case ICmpInst::ICMP_UGT:
11256   case ICmpInst::ICMP_UGE:
11257     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11258         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11259       return true;
11260     break;
11261   }
11262 
11263   // Maybe it can be proved via operations?
11264   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11265     return true;
11266 
11267   return false;
11268 }
11269 
11270 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11271                                                      const SCEV *LHS,
11272                                                      const SCEV *RHS,
11273                                                      const SCEV *FoundLHS,
11274                                                      const SCEV *FoundRHS) {
11275   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11276     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11277     // reduce the compile time impact of this optimization.
11278     return false;
11279 
11280   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11281   if (!Addend)
11282     return false;
11283 
11284   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11285 
11286   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11287   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11288   ConstantRange FoundLHSRange =
11289       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
11290 
11291   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11292   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11293 
11294   // We can also compute the range of values for `LHS` that satisfy the
11295   // consequent, "`LHS` `Pred` `RHS`":
11296   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11297   // The antecedent implies the consequent if every value of `LHS` that
11298   // satisfies the antecedent also satisfies the consequent.
11299   return LHSRange.icmp(Pred, ConstRHS);
11300 }
11301 
11302 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11303                                         bool IsSigned) {
11304   assert(isKnownPositive(Stride) && "Positive stride expected!");
11305 
11306   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11307   const SCEV *One = getOne(Stride->getType());
11308 
11309   if (IsSigned) {
11310     APInt MaxRHS = getSignedRangeMax(RHS);
11311     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11312     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11313 
11314     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11315     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11316   }
11317 
11318   APInt MaxRHS = getUnsignedRangeMax(RHS);
11319   APInt MaxValue = APInt::getMaxValue(BitWidth);
11320   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11321 
11322   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11323   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11324 }
11325 
11326 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11327                                         bool IsSigned) {
11328 
11329   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11330   const SCEV *One = getOne(Stride->getType());
11331 
11332   if (IsSigned) {
11333     APInt MinRHS = getSignedRangeMin(RHS);
11334     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11335     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11336 
11337     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11338     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11339   }
11340 
11341   APInt MinRHS = getUnsignedRangeMin(RHS);
11342   APInt MinValue = APInt::getMinValue(BitWidth);
11343   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11344 
11345   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11346   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11347 }
11348 
11349 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta,
11350                                             const SCEV *Step) {
11351   const SCEV *One = getOne(Step->getType());
11352   Delta = getAddExpr(Delta, getMinusSCEV(Step, One));
11353   return getUDivExpr(Delta, Step);
11354 }
11355 
11356 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11357                                                     const SCEV *Stride,
11358                                                     const SCEV *End,
11359                                                     unsigned BitWidth,
11360                                                     bool IsSigned) {
11361 
11362   assert(!isKnownNonPositive(Stride) &&
11363          "Stride is expected strictly positive!");
11364   // Calculate the maximum backedge count based on the range of values
11365   // permitted by Start, End, and Stride.
11366   const SCEV *MaxBECount;
11367   APInt MinStart =
11368       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11369 
11370   APInt StrideForMaxBECount =
11371       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11372 
11373   // We already know that the stride is positive, so we paper over conservatism
11374   // in our range computation by forcing StrideForMaxBECount to be at least one.
11375   // In theory this is unnecessary, but we expect MaxBECount to be a
11376   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11377   // is nothing to constant fold it to).
11378   APInt One(BitWidth, 1, IsSigned);
11379   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11380 
11381   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11382                             : APInt::getMaxValue(BitWidth);
11383   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11384 
11385   // Although End can be a MAX expression we estimate MaxEnd considering only
11386   // the case End = RHS of the loop termination condition. This is safe because
11387   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11388   // taken count.
11389   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11390                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11391 
11392   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11393                               getConstant(StrideForMaxBECount) /* Step */);
11394 
11395   return MaxBECount;
11396 }
11397 
11398 ScalarEvolution::ExitLimit
11399 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11400                                   const Loop *L, bool IsSigned,
11401                                   bool ControlsExit, bool AllowPredicates) {
11402   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11403 
11404   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11405   bool PredicatedIV = false;
11406 
11407   if (!IV && AllowPredicates) {
11408     // Try to make this an AddRec using runtime tests, in the first X
11409     // iterations of this loop, where X is the SCEV expression found by the
11410     // algorithm below.
11411     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11412     PredicatedIV = true;
11413   }
11414 
11415   // Avoid weird loops
11416   if (!IV || IV->getLoop() != L || !IV->isAffine())
11417     return getCouldNotCompute();
11418 
11419   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11420   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11421   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
11422 
11423   const SCEV *Stride = IV->getStepRecurrence(*this);
11424 
11425   bool PositiveStride = isKnownPositive(Stride);
11426 
11427   // Avoid negative or zero stride values.
11428   if (!PositiveStride) {
11429     // We can compute the correct backedge taken count for loops with unknown
11430     // strides if we can prove that the loop is not an infinite loop with side
11431     // effects. Here's the loop structure we are trying to handle -
11432     //
11433     // i = start
11434     // do {
11435     //   A[i] = i;
11436     //   i += s;
11437     // } while (i < end);
11438     //
11439     // The backedge taken count for such loops is evaluated as -
11440     // (max(end, start + stride) - start - 1) /u stride
11441     //
11442     // The additional preconditions that we need to check to prove correctness
11443     // of the above formula is as follows -
11444     //
11445     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11446     //    NoWrap flag).
11447     // b) loop is single exit with no side effects.
11448     //
11449     //
11450     // Precondition a) implies that if the stride is negative, this is a single
11451     // trip loop. The backedge taken count formula reduces to zero in this case.
11452     //
11453     // Precondition b) implies that the unknown stride cannot be zero otherwise
11454     // we have UB.
11455     //
11456     // The positive stride case is the same as isKnownPositive(Stride) returning
11457     // true (original behavior of the function).
11458     //
11459     // We want to make sure that the stride is truly unknown as there are edge
11460     // cases where ScalarEvolution propagates no wrap flags to the
11461     // post-increment/decrement IV even though the increment/decrement operation
11462     // itself is wrapping. The computed backedge taken count may be wrong in
11463     // such cases. This is prevented by checking that the stride is not known to
11464     // be either positive or non-positive. For example, no wrap flags are
11465     // propagated to the post-increment IV of this loop with a trip count of 2 -
11466     //
11467     // unsigned char i;
11468     // for(i=127; i<128; i+=129)
11469     //   A[i] = i;
11470     //
11471     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11472         !loopIsFiniteByAssumption(L))
11473       return getCouldNotCompute();
11474   } else if (!Stride->isOne() && !NoWrap) {
11475     auto isUBOnWrap = [&]() {
11476       // Can we prove this loop *must* be UB if overflow of IV occurs?
11477       // Reasoning goes as follows:
11478       // * Suppose the IV did self wrap.
11479       // * If Stride evenly divides the iteration space, then once wrap
11480       //   occurs, the loop must revisit the same values.
11481       // * We know that RHS is invariant, and that none of those values
11482       //   caused this exit to be taken previously.  Thus, this exit is
11483       //   dynamically dead.
11484       // * If this is the sole exit, then a dead exit implies the loop
11485       //   must be infinite if there are no abnormal exits.
11486       // * If the loop were infinite, then it must either not be mustprogress
11487       //   or have side effects. Otherwise, it must be UB.
11488       // * It can't (by assumption), be UB so we have contradicted our
11489       //   premise and can conclude the IV did not in fact self-wrap.
11490       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
11491       // follows trivially from the fact that every (un)signed-wrapped, but
11492       // not self-wrapped value must be LT than the last value before
11493       // (un)signed wrap.  Since we know that last value didn't exit, nor
11494       // will any smaller one.
11495 
11496       if (!isLoopInvariant(RHS, L))
11497         return false;
11498 
11499       auto *StrideC = dyn_cast<SCEVConstant>(Stride);
11500       if (!StrideC || !StrideC->getAPInt().isPowerOf2())
11501         return false;
11502 
11503       if (!ControlsExit || !loopHasNoAbnormalExits(L))
11504         return false;
11505 
11506       return loopIsFiniteByAssumption(L);
11507     };
11508 
11509     // Avoid proven overflow cases: this will ensure that the backedge taken
11510     // count will not generate any unsigned overflow. Relaxed no-overflow
11511     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11512     // undefined behaviors like the case of C language.
11513     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
11514       return getCouldNotCompute();
11515   }
11516 
11517   const SCEV *Start = IV->getStart();
11518   const SCEV *End = RHS;
11519   // When the RHS is not invariant, we do not know the end bound of the loop and
11520   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11521   // calculate the MaxBECount, given the start, stride and max value for the end
11522   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11523   // checked above).
11524   if (!isLoopInvariant(RHS, L)) {
11525     const SCEV *MaxBECount = computeMaxBECountForLT(
11526         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11527     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11528                      false /*MaxOrZero*/, Predicates);
11529   }
11530   // If the backedge is taken at least once, then it will be taken
11531   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11532   // is the LHS value of the less-than comparison the first time it is evaluated
11533   // and End is the RHS.
11534   const SCEV *BECountIfBackedgeTaken =
11535     computeBECount(getMinusSCEV(End, Start), Stride);
11536   // If the loop entry is guarded by the result of the backedge test of the
11537   // first loop iteration, then we know the backedge will be taken at least
11538   // once and so the backedge taken count is as above. If not then we use the
11539   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11540   // as if the backedge is taken at least once max(End,Start) is End and so the
11541   // result is as above, and if not max(End,Start) is Start so we get a backedge
11542   // count of zero.
11543   const SCEV *BECount;
11544   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11545     BECount = BECountIfBackedgeTaken;
11546   else {
11547     // If we know that RHS >= Start in the context of loop, then we know that
11548     // max(RHS, Start) = RHS at this point.
11549     if (isLoopEntryGuardedByCond(
11550             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11551       End = RHS;
11552     else
11553       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11554     BECount = computeBECount(getMinusSCEV(End, Start), Stride);
11555   }
11556 
11557   const SCEV *MaxBECount;
11558   bool MaxOrZero = false;
11559   if (isa<SCEVConstant>(BECount))
11560     MaxBECount = BECount;
11561   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11562     // If we know exactly how many times the backedge will be taken if it's
11563     // taken at least once, then the backedge count will either be that or
11564     // zero.
11565     MaxBECount = BECountIfBackedgeTaken;
11566     MaxOrZero = true;
11567   } else {
11568     MaxBECount = computeMaxBECountForLT(
11569         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11570   }
11571 
11572   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11573       !isa<SCEVCouldNotCompute>(BECount))
11574     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11575 
11576   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11577 }
11578 
11579 ScalarEvolution::ExitLimit
11580 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11581                                      const Loop *L, bool IsSigned,
11582                                      bool ControlsExit, bool AllowPredicates) {
11583   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11584   // We handle only IV > Invariant
11585   if (!isLoopInvariant(RHS, L))
11586     return getCouldNotCompute();
11587 
11588   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11589   if (!IV && AllowPredicates)
11590     // Try to make this an AddRec using runtime tests, in the first X
11591     // iterations of this loop, where X is the SCEV expression found by the
11592     // algorithm below.
11593     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11594 
11595   // Avoid weird loops
11596   if (!IV || IV->getLoop() != L || !IV->isAffine())
11597     return getCouldNotCompute();
11598 
11599   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11600   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11601   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
11602 
11603   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11604 
11605   // Avoid negative or zero stride values
11606   if (!isKnownPositive(Stride))
11607     return getCouldNotCompute();
11608 
11609   // Avoid proven overflow cases: this will ensure that the backedge taken count
11610   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11611   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11612   // behaviors like the case of C language.
11613   if (!Stride->isOne() && !NoWrap)
11614     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
11615       return getCouldNotCompute();
11616 
11617   const SCEV *Start = IV->getStart();
11618   const SCEV *End = RHS;
11619   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11620     // If we know that Start >= RHS in the context of loop, then we know that
11621     // min(RHS, Start) = RHS at this point.
11622     if (isLoopEntryGuardedByCond(
11623             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11624       End = RHS;
11625     else
11626       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11627   }
11628 
11629   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride);
11630 
11631   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11632                             : getUnsignedRangeMax(Start);
11633 
11634   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11635                              : getUnsignedRangeMin(Stride);
11636 
11637   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11638   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11639                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11640 
11641   // Although End can be a MIN expression we estimate MinEnd considering only
11642   // the case End = RHS. This is safe because in the other case (Start - End)
11643   // is zero, leading to a zero maximum backedge taken count.
11644   APInt MinEnd =
11645     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11646              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11647 
11648   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11649                                ? BECount
11650                                : computeBECount(getConstant(MaxStart - MinEnd),
11651                                                 getConstant(MinStride));
11652 
11653   if (isa<SCEVCouldNotCompute>(MaxBECount))
11654     MaxBECount = BECount;
11655 
11656   return ExitLimit(BECount, MaxBECount, false, Predicates);
11657 }
11658 
11659 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11660                                                     ScalarEvolution &SE) const {
11661   if (Range.isFullSet())  // Infinite loop.
11662     return SE.getCouldNotCompute();
11663 
11664   // If the start is a non-zero constant, shift the range to simplify things.
11665   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11666     if (!SC->getValue()->isZero()) {
11667       SmallVector<const SCEV *, 4> Operands(operands());
11668       Operands[0] = SE.getZero(SC->getType());
11669       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11670                                              getNoWrapFlags(FlagNW));
11671       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11672         return ShiftedAddRec->getNumIterationsInRange(
11673             Range.subtract(SC->getAPInt()), SE);
11674       // This is strange and shouldn't happen.
11675       return SE.getCouldNotCompute();
11676     }
11677 
11678   // The only time we can solve this is when we have all constant indices.
11679   // Otherwise, we cannot determine the overflow conditions.
11680   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11681     return SE.getCouldNotCompute();
11682 
11683   // Okay at this point we know that all elements of the chrec are constants and
11684   // that the start element is zero.
11685 
11686   // First check to see if the range contains zero.  If not, the first
11687   // iteration exits.
11688   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11689   if (!Range.contains(APInt(BitWidth, 0)))
11690     return SE.getZero(getType());
11691 
11692   if (isAffine()) {
11693     // If this is an affine expression then we have this situation:
11694     //   Solve {0,+,A} in Range  ===  Ax in Range
11695 
11696     // We know that zero is in the range.  If A is positive then we know that
11697     // the upper value of the range must be the first possible exit value.
11698     // If A is negative then the lower of the range is the last possible loop
11699     // value.  Also note that we already checked for a full range.
11700     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11701     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11702 
11703     // The exit value should be (End+A)/A.
11704     APInt ExitVal = (End + A).udiv(A);
11705     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11706 
11707     // Evaluate at the exit value.  If we really did fall out of the valid
11708     // range, then we computed our trip count, otherwise wrap around or other
11709     // things must have happened.
11710     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11711     if (Range.contains(Val->getValue()))
11712       return SE.getCouldNotCompute();  // Something strange happened
11713 
11714     // Ensure that the previous value is in the range.  This is a sanity check.
11715     assert(Range.contains(
11716            EvaluateConstantChrecAtConstant(this,
11717            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11718            "Linear scev computation is off in a bad way!");
11719     return SE.getConstant(ExitValue);
11720   }
11721 
11722   if (isQuadratic()) {
11723     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11724       return SE.getConstant(S.getValue());
11725   }
11726 
11727   return SE.getCouldNotCompute();
11728 }
11729 
11730 const SCEVAddRecExpr *
11731 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11732   assert(getNumOperands() > 1 && "AddRec with zero step?");
11733   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11734   // but in this case we cannot guarantee that the value returned will be an
11735   // AddRec because SCEV does not have a fixed point where it stops
11736   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11737   // may happen if we reach arithmetic depth limit while simplifying. So we
11738   // construct the returned value explicitly.
11739   SmallVector<const SCEV *, 3> Ops;
11740   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11741   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11742   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11743     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11744   // We know that the last operand is not a constant zero (otherwise it would
11745   // have been popped out earlier). This guarantees us that if the result has
11746   // the same last operand, then it will also not be popped out, meaning that
11747   // the returned value will be an AddRec.
11748   const SCEV *Last = getOperand(getNumOperands() - 1);
11749   assert(!Last->isZero() && "Recurrency with zero step?");
11750   Ops.push_back(Last);
11751   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11752                                                SCEV::FlagAnyWrap));
11753 }
11754 
11755 // Return true when S contains at least an undef value.
11756 static inline bool containsUndefs(const SCEV *S) {
11757   return SCEVExprContains(S, [](const SCEV *S) {
11758     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11759       return isa<UndefValue>(SU->getValue());
11760     return false;
11761   });
11762 }
11763 
11764 namespace {
11765 
11766 // Collect all steps of SCEV expressions.
11767 struct SCEVCollectStrides {
11768   ScalarEvolution &SE;
11769   SmallVectorImpl<const SCEV *> &Strides;
11770 
11771   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11772       : SE(SE), Strides(S) {}
11773 
11774   bool follow(const SCEV *S) {
11775     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11776       Strides.push_back(AR->getStepRecurrence(SE));
11777     return true;
11778   }
11779 
11780   bool isDone() const { return false; }
11781 };
11782 
11783 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11784 struct SCEVCollectTerms {
11785   SmallVectorImpl<const SCEV *> &Terms;
11786 
11787   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11788 
11789   bool follow(const SCEV *S) {
11790     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11791         isa<SCEVSignExtendExpr>(S)) {
11792       if (!containsUndefs(S))
11793         Terms.push_back(S);
11794 
11795       // Stop recursion: once we collected a term, do not walk its operands.
11796       return false;
11797     }
11798 
11799     // Keep looking.
11800     return true;
11801   }
11802 
11803   bool isDone() const { return false; }
11804 };
11805 
11806 // Check if a SCEV contains an AddRecExpr.
11807 struct SCEVHasAddRec {
11808   bool &ContainsAddRec;
11809 
11810   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11811     ContainsAddRec = false;
11812   }
11813 
11814   bool follow(const SCEV *S) {
11815     if (isa<SCEVAddRecExpr>(S)) {
11816       ContainsAddRec = true;
11817 
11818       // Stop recursion: once we collected a term, do not walk its operands.
11819       return false;
11820     }
11821 
11822     // Keep looking.
11823     return true;
11824   }
11825 
11826   bool isDone() const { return false; }
11827 };
11828 
11829 // Find factors that are multiplied with an expression that (possibly as a
11830 // subexpression) contains an AddRecExpr. In the expression:
11831 //
11832 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11833 //
11834 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11835 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11836 // parameters as they form a product with an induction variable.
11837 //
11838 // This collector expects all array size parameters to be in the same MulExpr.
11839 // It might be necessary to later add support for collecting parameters that are
11840 // spread over different nested MulExpr.
11841 struct SCEVCollectAddRecMultiplies {
11842   SmallVectorImpl<const SCEV *> &Terms;
11843   ScalarEvolution &SE;
11844 
11845   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11846       : Terms(T), SE(SE) {}
11847 
11848   bool follow(const SCEV *S) {
11849     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11850       bool HasAddRec = false;
11851       SmallVector<const SCEV *, 0> Operands;
11852       for (auto Op : Mul->operands()) {
11853         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11854         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11855           Operands.push_back(Op);
11856         } else if (Unknown) {
11857           HasAddRec = true;
11858         } else {
11859           bool ContainsAddRec = false;
11860           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11861           visitAll(Op, ContiansAddRec);
11862           HasAddRec |= ContainsAddRec;
11863         }
11864       }
11865       if (Operands.size() == 0)
11866         return true;
11867 
11868       if (!HasAddRec)
11869         return false;
11870 
11871       Terms.push_back(SE.getMulExpr(Operands));
11872       // Stop recursion: once we collected a term, do not walk its operands.
11873       return false;
11874     }
11875 
11876     // Keep looking.
11877     return true;
11878   }
11879 
11880   bool isDone() const { return false; }
11881 };
11882 
11883 } // end anonymous namespace
11884 
11885 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11886 /// two places:
11887 ///   1) The strides of AddRec expressions.
11888 ///   2) Unknowns that are multiplied with AddRec expressions.
11889 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11890     SmallVectorImpl<const SCEV *> &Terms) {
11891   SmallVector<const SCEV *, 4> Strides;
11892   SCEVCollectStrides StrideCollector(*this, Strides);
11893   visitAll(Expr, StrideCollector);
11894 
11895   LLVM_DEBUG({
11896     dbgs() << "Strides:\n";
11897     for (const SCEV *S : Strides)
11898       dbgs() << *S << "\n";
11899   });
11900 
11901   for (const SCEV *S : Strides) {
11902     SCEVCollectTerms TermCollector(Terms);
11903     visitAll(S, TermCollector);
11904   }
11905 
11906   LLVM_DEBUG({
11907     dbgs() << "Terms:\n";
11908     for (const SCEV *T : Terms)
11909       dbgs() << *T << "\n";
11910   });
11911 
11912   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11913   visitAll(Expr, MulCollector);
11914 }
11915 
11916 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11917                                    SmallVectorImpl<const SCEV *> &Terms,
11918                                    SmallVectorImpl<const SCEV *> &Sizes) {
11919   int Last = Terms.size() - 1;
11920   const SCEV *Step = Terms[Last];
11921 
11922   // End of recursion.
11923   if (Last == 0) {
11924     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11925       SmallVector<const SCEV *, 2> Qs;
11926       for (const SCEV *Op : M->operands())
11927         if (!isa<SCEVConstant>(Op))
11928           Qs.push_back(Op);
11929 
11930       Step = SE.getMulExpr(Qs);
11931     }
11932 
11933     Sizes.push_back(Step);
11934     return true;
11935   }
11936 
11937   for (const SCEV *&Term : Terms) {
11938     // Normalize the terms before the next call to findArrayDimensionsRec.
11939     const SCEV *Q, *R;
11940     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11941 
11942     // Bail out when GCD does not evenly divide one of the terms.
11943     if (!R->isZero())
11944       return false;
11945 
11946     Term = Q;
11947   }
11948 
11949   // Remove all SCEVConstants.
11950   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
11951 
11952   if (Terms.size() > 0)
11953     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11954       return false;
11955 
11956   Sizes.push_back(Step);
11957   return true;
11958 }
11959 
11960 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11961 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11962   for (const SCEV *T : Terms)
11963     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11964       return true;
11965 
11966   return false;
11967 }
11968 
11969 // Return the number of product terms in S.
11970 static inline int numberOfTerms(const SCEV *S) {
11971   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11972     return Expr->getNumOperands();
11973   return 1;
11974 }
11975 
11976 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11977   if (isa<SCEVConstant>(T))
11978     return nullptr;
11979 
11980   if (isa<SCEVUnknown>(T))
11981     return T;
11982 
11983   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11984     SmallVector<const SCEV *, 2> Factors;
11985     for (const SCEV *Op : M->operands())
11986       if (!isa<SCEVConstant>(Op))
11987         Factors.push_back(Op);
11988 
11989     return SE.getMulExpr(Factors);
11990   }
11991 
11992   return T;
11993 }
11994 
11995 /// Return the size of an element read or written by Inst.
11996 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11997   Type *Ty;
11998   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11999     Ty = Store->getValueOperand()->getType();
12000   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12001     Ty = Load->getType();
12002   else
12003     return nullptr;
12004 
12005   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12006   return getSizeOfExpr(ETy, Ty);
12007 }
12008 
12009 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
12010                                           SmallVectorImpl<const SCEV *> &Sizes,
12011                                           const SCEV *ElementSize) {
12012   if (Terms.size() < 1 || !ElementSize)
12013     return;
12014 
12015   // Early return when Terms do not contain parameters: we do not delinearize
12016   // non parametric SCEVs.
12017   if (!containsParameters(Terms))
12018     return;
12019 
12020   LLVM_DEBUG({
12021     dbgs() << "Terms:\n";
12022     for (const SCEV *T : Terms)
12023       dbgs() << *T << "\n";
12024   });
12025 
12026   // Remove duplicates.
12027   array_pod_sort(Terms.begin(), Terms.end());
12028   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
12029 
12030   // Put larger terms first.
12031   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
12032     return numberOfTerms(LHS) > numberOfTerms(RHS);
12033   });
12034 
12035   // Try to divide all terms by the element size. If term is not divisible by
12036   // element size, proceed with the original term.
12037   for (const SCEV *&Term : Terms) {
12038     const SCEV *Q, *R;
12039     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
12040     if (!Q->isZero())
12041       Term = Q;
12042   }
12043 
12044   SmallVector<const SCEV *, 4> NewTerms;
12045 
12046   // Remove constant factors.
12047   for (const SCEV *T : Terms)
12048     if (const SCEV *NewT = removeConstantFactors(*this, T))
12049       NewTerms.push_back(NewT);
12050 
12051   LLVM_DEBUG({
12052     dbgs() << "Terms after sorting:\n";
12053     for (const SCEV *T : NewTerms)
12054       dbgs() << *T << "\n";
12055   });
12056 
12057   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
12058     Sizes.clear();
12059     return;
12060   }
12061 
12062   // The last element to be pushed into Sizes is the size of an element.
12063   Sizes.push_back(ElementSize);
12064 
12065   LLVM_DEBUG({
12066     dbgs() << "Sizes:\n";
12067     for (const SCEV *S : Sizes)
12068       dbgs() << *S << "\n";
12069   });
12070 }
12071 
12072 void ScalarEvolution::computeAccessFunctions(
12073     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
12074     SmallVectorImpl<const SCEV *> &Sizes) {
12075   // Early exit in case this SCEV is not an affine multivariate function.
12076   if (Sizes.empty())
12077     return;
12078 
12079   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
12080     if (!AR->isAffine())
12081       return;
12082 
12083   const SCEV *Res = Expr;
12084   int Last = Sizes.size() - 1;
12085   for (int i = Last; i >= 0; i--) {
12086     const SCEV *Q, *R;
12087     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
12088 
12089     LLVM_DEBUG({
12090       dbgs() << "Res: " << *Res << "\n";
12091       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
12092       dbgs() << "Res divided by Sizes[i]:\n";
12093       dbgs() << "Quotient: " << *Q << "\n";
12094       dbgs() << "Remainder: " << *R << "\n";
12095     });
12096 
12097     Res = Q;
12098 
12099     // Do not record the last subscript corresponding to the size of elements in
12100     // the array.
12101     if (i == Last) {
12102 
12103       // Bail out if the remainder is too complex.
12104       if (isa<SCEVAddRecExpr>(R)) {
12105         Subscripts.clear();
12106         Sizes.clear();
12107         return;
12108       }
12109 
12110       continue;
12111     }
12112 
12113     // Record the access function for the current subscript.
12114     Subscripts.push_back(R);
12115   }
12116 
12117   // Also push in last position the remainder of the last division: it will be
12118   // the access function of the innermost dimension.
12119   Subscripts.push_back(Res);
12120 
12121   std::reverse(Subscripts.begin(), Subscripts.end());
12122 
12123   LLVM_DEBUG({
12124     dbgs() << "Subscripts:\n";
12125     for (const SCEV *S : Subscripts)
12126       dbgs() << *S << "\n";
12127   });
12128 }
12129 
12130 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
12131 /// sizes of an array access. Returns the remainder of the delinearization that
12132 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
12133 /// the multiples of SCEV coefficients: that is a pattern matching of sub
12134 /// expressions in the stride and base of a SCEV corresponding to the
12135 /// computation of a GCD (greatest common divisor) of base and stride.  When
12136 /// SCEV->delinearize fails, it returns the SCEV unchanged.
12137 ///
12138 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
12139 ///
12140 ///  void foo(long n, long m, long o, double A[n][m][o]) {
12141 ///
12142 ///    for (long i = 0; i < n; i++)
12143 ///      for (long j = 0; j < m; j++)
12144 ///        for (long k = 0; k < o; k++)
12145 ///          A[i][j][k] = 1.0;
12146 ///  }
12147 ///
12148 /// the delinearization input is the following AddRec SCEV:
12149 ///
12150 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
12151 ///
12152 /// From this SCEV, we are able to say that the base offset of the access is %A
12153 /// because it appears as an offset that does not divide any of the strides in
12154 /// the loops:
12155 ///
12156 ///  CHECK: Base offset: %A
12157 ///
12158 /// and then SCEV->delinearize determines the size of some of the dimensions of
12159 /// the array as these are the multiples by which the strides are happening:
12160 ///
12161 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
12162 ///
12163 /// Note that the outermost dimension remains of UnknownSize because there are
12164 /// no strides that would help identifying the size of the last dimension: when
12165 /// the array has been statically allocated, one could compute the size of that
12166 /// dimension by dividing the overall size of the array by the size of the known
12167 /// dimensions: %m * %o * 8.
12168 ///
12169 /// Finally delinearize provides the access functions for the array reference
12170 /// that does correspond to A[i][j][k] of the above C testcase:
12171 ///
12172 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
12173 ///
12174 /// The testcases are checking the output of a function pass:
12175 /// DelinearizationPass that walks through all loads and stores of a function
12176 /// asking for the SCEV of the memory access with respect to all enclosing
12177 /// loops, calling SCEV->delinearize on that and printing the results.
12178 void ScalarEvolution::delinearize(const SCEV *Expr,
12179                                  SmallVectorImpl<const SCEV *> &Subscripts,
12180                                  SmallVectorImpl<const SCEV *> &Sizes,
12181                                  const SCEV *ElementSize) {
12182   // First step: collect parametric terms.
12183   SmallVector<const SCEV *, 4> Terms;
12184   collectParametricTerms(Expr, Terms);
12185 
12186   if (Terms.empty())
12187     return;
12188 
12189   // Second step: find subscript sizes.
12190   findArrayDimensions(Terms, Sizes, ElementSize);
12191 
12192   if (Sizes.empty())
12193     return;
12194 
12195   // Third step: compute the access functions for each subscript.
12196   computeAccessFunctions(Expr, Subscripts, Sizes);
12197 
12198   if (Subscripts.empty())
12199     return;
12200 
12201   LLVM_DEBUG({
12202     dbgs() << "succeeded to delinearize " << *Expr << "\n";
12203     dbgs() << "ArrayDecl[UnknownSize]";
12204     for (const SCEV *S : Sizes)
12205       dbgs() << "[" << *S << "]";
12206 
12207     dbgs() << "\nArrayRef";
12208     for (const SCEV *S : Subscripts)
12209       dbgs() << "[" << *S << "]";
12210     dbgs() << "\n";
12211   });
12212 }
12213 
12214 bool ScalarEvolution::getIndexExpressionsFromGEP(
12215     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
12216     SmallVectorImpl<int> &Sizes) {
12217   assert(Subscripts.empty() && Sizes.empty() &&
12218          "Expected output lists to be empty on entry to this function.");
12219   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
12220   Type *Ty = GEP->getPointerOperandType();
12221   bool DroppedFirstDim = false;
12222   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
12223     const SCEV *Expr = getSCEV(GEP->getOperand(i));
12224     if (i == 1) {
12225       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
12226         Ty = PtrTy->getElementType();
12227       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
12228         Ty = ArrayTy->getElementType();
12229       } else {
12230         Subscripts.clear();
12231         Sizes.clear();
12232         return false;
12233       }
12234       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
12235         if (Const->getValue()->isZero()) {
12236           DroppedFirstDim = true;
12237           continue;
12238         }
12239       Subscripts.push_back(Expr);
12240       continue;
12241     }
12242 
12243     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
12244     if (!ArrayTy) {
12245       Subscripts.clear();
12246       Sizes.clear();
12247       return false;
12248     }
12249 
12250     Subscripts.push_back(Expr);
12251     if (!(DroppedFirstDim && i == 2))
12252       Sizes.push_back(ArrayTy->getNumElements());
12253 
12254     Ty = ArrayTy->getElementType();
12255   }
12256   return !Subscripts.empty();
12257 }
12258 
12259 //===----------------------------------------------------------------------===//
12260 //                   SCEVCallbackVH Class Implementation
12261 //===----------------------------------------------------------------------===//
12262 
12263 void ScalarEvolution::SCEVCallbackVH::deleted() {
12264   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12265   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12266     SE->ConstantEvolutionLoopExitValue.erase(PN);
12267   SE->eraseValueFromMap(getValPtr());
12268   // this now dangles!
12269 }
12270 
12271 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12272   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12273 
12274   // Forget all the expressions associated with users of the old value,
12275   // so that future queries will recompute the expressions using the new
12276   // value.
12277   Value *Old = getValPtr();
12278   SmallVector<User *, 16> Worklist(Old->users());
12279   SmallPtrSet<User *, 8> Visited;
12280   while (!Worklist.empty()) {
12281     User *U = Worklist.pop_back_val();
12282     // Deleting the Old value will cause this to dangle. Postpone
12283     // that until everything else is done.
12284     if (U == Old)
12285       continue;
12286     if (!Visited.insert(U).second)
12287       continue;
12288     if (PHINode *PN = dyn_cast<PHINode>(U))
12289       SE->ConstantEvolutionLoopExitValue.erase(PN);
12290     SE->eraseValueFromMap(U);
12291     llvm::append_range(Worklist, U->users());
12292   }
12293   // Delete the Old value.
12294   if (PHINode *PN = dyn_cast<PHINode>(Old))
12295     SE->ConstantEvolutionLoopExitValue.erase(PN);
12296   SE->eraseValueFromMap(Old);
12297   // this now dangles!
12298 }
12299 
12300 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12301   : CallbackVH(V), SE(se) {}
12302 
12303 //===----------------------------------------------------------------------===//
12304 //                   ScalarEvolution Class Implementation
12305 //===----------------------------------------------------------------------===//
12306 
12307 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12308                                  AssumptionCache &AC, DominatorTree &DT,
12309                                  LoopInfo &LI)
12310     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12311       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12312       LoopDispositions(64), BlockDispositions(64) {
12313   // To use guards for proving predicates, we need to scan every instruction in
12314   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12315   // time if the IR does not actually contain any calls to
12316   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12317   //
12318   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12319   // to _add_ guards to the module when there weren't any before, and wants
12320   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12321   // efficient in lieu of being smart in that rather obscure case.
12322 
12323   auto *GuardDecl = F.getParent()->getFunction(
12324       Intrinsic::getName(Intrinsic::experimental_guard));
12325   HasGuards = GuardDecl && !GuardDecl->use_empty();
12326 }
12327 
12328 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12329     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12330       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12331       ValueExprMap(std::move(Arg.ValueExprMap)),
12332       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12333       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12334       PendingMerges(std::move(Arg.PendingMerges)),
12335       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12336       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12337       PredicatedBackedgeTakenCounts(
12338           std::move(Arg.PredicatedBackedgeTakenCounts)),
12339       ConstantEvolutionLoopExitValue(
12340           std::move(Arg.ConstantEvolutionLoopExitValue)),
12341       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12342       LoopDispositions(std::move(Arg.LoopDispositions)),
12343       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12344       BlockDispositions(std::move(Arg.BlockDispositions)),
12345       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12346       SignedRanges(std::move(Arg.SignedRanges)),
12347       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12348       UniquePreds(std::move(Arg.UniquePreds)),
12349       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12350       LoopUsers(std::move(Arg.LoopUsers)),
12351       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12352       FirstUnknown(Arg.FirstUnknown) {
12353   Arg.FirstUnknown = nullptr;
12354 }
12355 
12356 ScalarEvolution::~ScalarEvolution() {
12357   // Iterate through all the SCEVUnknown instances and call their
12358   // destructors, so that they release their references to their values.
12359   for (SCEVUnknown *U = FirstUnknown; U;) {
12360     SCEVUnknown *Tmp = U;
12361     U = U->Next;
12362     Tmp->~SCEVUnknown();
12363   }
12364   FirstUnknown = nullptr;
12365 
12366   ExprValueMap.clear();
12367   ValueExprMap.clear();
12368   HasRecMap.clear();
12369   BackedgeTakenCounts.clear();
12370   PredicatedBackedgeTakenCounts.clear();
12371 
12372   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12373   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12374   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12375   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12376   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12377 }
12378 
12379 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12380   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12381 }
12382 
12383 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12384                           const Loop *L) {
12385   // Print all inner loops first
12386   for (Loop *I : *L)
12387     PrintLoopInfo(OS, SE, I);
12388 
12389   OS << "Loop ";
12390   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12391   OS << ": ";
12392 
12393   SmallVector<BasicBlock *, 8> ExitingBlocks;
12394   L->getExitingBlocks(ExitingBlocks);
12395   if (ExitingBlocks.size() != 1)
12396     OS << "<multiple exits> ";
12397 
12398   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12399     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12400   else
12401     OS << "Unpredictable backedge-taken count.\n";
12402 
12403   if (ExitingBlocks.size() > 1)
12404     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12405       OS << "  exit count for " << ExitingBlock->getName() << ": "
12406          << *SE->getExitCount(L, ExitingBlock) << "\n";
12407     }
12408 
12409   OS << "Loop ";
12410   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12411   OS << ": ";
12412 
12413   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12414     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12415     if (SE->isBackedgeTakenCountMaxOrZero(L))
12416       OS << ", actual taken count either this or zero.";
12417   } else {
12418     OS << "Unpredictable max backedge-taken count. ";
12419   }
12420 
12421   OS << "\n"
12422         "Loop ";
12423   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12424   OS << ": ";
12425 
12426   SCEVUnionPredicate Pred;
12427   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12428   if (!isa<SCEVCouldNotCompute>(PBT)) {
12429     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12430     OS << " Predicates:\n";
12431     Pred.print(OS, 4);
12432   } else {
12433     OS << "Unpredictable predicated backedge-taken count. ";
12434   }
12435   OS << "\n";
12436 
12437   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12438     OS << "Loop ";
12439     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12440     OS << ": ";
12441     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12442   }
12443 }
12444 
12445 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12446   switch (LD) {
12447   case ScalarEvolution::LoopVariant:
12448     return "Variant";
12449   case ScalarEvolution::LoopInvariant:
12450     return "Invariant";
12451   case ScalarEvolution::LoopComputable:
12452     return "Computable";
12453   }
12454   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12455 }
12456 
12457 void ScalarEvolution::print(raw_ostream &OS) const {
12458   // ScalarEvolution's implementation of the print method is to print
12459   // out SCEV values of all instructions that are interesting. Doing
12460   // this potentially causes it to create new SCEV objects though,
12461   // which technically conflicts with the const qualifier. This isn't
12462   // observable from outside the class though, so casting away the
12463   // const isn't dangerous.
12464   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12465 
12466   if (ClassifyExpressions) {
12467     OS << "Classifying expressions for: ";
12468     F.printAsOperand(OS, /*PrintType=*/false);
12469     OS << "\n";
12470     for (Instruction &I : instructions(F))
12471       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12472         OS << I << '\n';
12473         OS << "  -->  ";
12474         const SCEV *SV = SE.getSCEV(&I);
12475         SV->print(OS);
12476         if (!isa<SCEVCouldNotCompute>(SV)) {
12477           OS << " U: ";
12478           SE.getUnsignedRange(SV).print(OS);
12479           OS << " S: ";
12480           SE.getSignedRange(SV).print(OS);
12481         }
12482 
12483         const Loop *L = LI.getLoopFor(I.getParent());
12484 
12485         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12486         if (AtUse != SV) {
12487           OS << "  -->  ";
12488           AtUse->print(OS);
12489           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12490             OS << " U: ";
12491             SE.getUnsignedRange(AtUse).print(OS);
12492             OS << " S: ";
12493             SE.getSignedRange(AtUse).print(OS);
12494           }
12495         }
12496 
12497         if (L) {
12498           OS << "\t\t" "Exits: ";
12499           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12500           if (!SE.isLoopInvariant(ExitValue, L)) {
12501             OS << "<<Unknown>>";
12502           } else {
12503             OS << *ExitValue;
12504           }
12505 
12506           bool First = true;
12507           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12508             if (First) {
12509               OS << "\t\t" "LoopDispositions: { ";
12510               First = false;
12511             } else {
12512               OS << ", ";
12513             }
12514 
12515             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12516             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12517           }
12518 
12519           for (auto *InnerL : depth_first(L)) {
12520             if (InnerL == L)
12521               continue;
12522             if (First) {
12523               OS << "\t\t" "LoopDispositions: { ";
12524               First = false;
12525             } else {
12526               OS << ", ";
12527             }
12528 
12529             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12530             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12531           }
12532 
12533           OS << " }";
12534         }
12535 
12536         OS << "\n";
12537       }
12538   }
12539 
12540   OS << "Determining loop execution counts for: ";
12541   F.printAsOperand(OS, /*PrintType=*/false);
12542   OS << "\n";
12543   for (Loop *I : LI)
12544     PrintLoopInfo(OS, &SE, I);
12545 }
12546 
12547 ScalarEvolution::LoopDisposition
12548 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12549   auto &Values = LoopDispositions[S];
12550   for (auto &V : Values) {
12551     if (V.getPointer() == L)
12552       return V.getInt();
12553   }
12554   Values.emplace_back(L, LoopVariant);
12555   LoopDisposition D = computeLoopDisposition(S, L);
12556   auto &Values2 = LoopDispositions[S];
12557   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12558     if (V.getPointer() == L) {
12559       V.setInt(D);
12560       break;
12561     }
12562   }
12563   return D;
12564 }
12565 
12566 ScalarEvolution::LoopDisposition
12567 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12568   switch (S->getSCEVType()) {
12569   case scConstant:
12570     return LoopInvariant;
12571   case scPtrToInt:
12572   case scTruncate:
12573   case scZeroExtend:
12574   case scSignExtend:
12575     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12576   case scAddRecExpr: {
12577     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12578 
12579     // If L is the addrec's loop, it's computable.
12580     if (AR->getLoop() == L)
12581       return LoopComputable;
12582 
12583     // Add recurrences are never invariant in the function-body (null loop).
12584     if (!L)
12585       return LoopVariant;
12586 
12587     // Everything that is not defined at loop entry is variant.
12588     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12589       return LoopVariant;
12590     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12591            " dominate the contained loop's header?");
12592 
12593     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12594     if (AR->getLoop()->contains(L))
12595       return LoopInvariant;
12596 
12597     // This recurrence is variant w.r.t. L if any of its operands
12598     // are variant.
12599     for (auto *Op : AR->operands())
12600       if (!isLoopInvariant(Op, L))
12601         return LoopVariant;
12602 
12603     // Otherwise it's loop-invariant.
12604     return LoopInvariant;
12605   }
12606   case scAddExpr:
12607   case scMulExpr:
12608   case scUMaxExpr:
12609   case scSMaxExpr:
12610   case scUMinExpr:
12611   case scSMinExpr: {
12612     bool HasVarying = false;
12613     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12614       LoopDisposition D = getLoopDisposition(Op, L);
12615       if (D == LoopVariant)
12616         return LoopVariant;
12617       if (D == LoopComputable)
12618         HasVarying = true;
12619     }
12620     return HasVarying ? LoopComputable : LoopInvariant;
12621   }
12622   case scUDivExpr: {
12623     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12624     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12625     if (LD == LoopVariant)
12626       return LoopVariant;
12627     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12628     if (RD == LoopVariant)
12629       return LoopVariant;
12630     return (LD == LoopInvariant && RD == LoopInvariant) ?
12631            LoopInvariant : LoopComputable;
12632   }
12633   case scUnknown:
12634     // All non-instruction values are loop invariant.  All instructions are loop
12635     // invariant if they are not contained in the specified loop.
12636     // Instructions are never considered invariant in the function body
12637     // (null loop) because they are defined within the "loop".
12638     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12639       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12640     return LoopInvariant;
12641   case scCouldNotCompute:
12642     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12643   }
12644   llvm_unreachable("Unknown SCEV kind!");
12645 }
12646 
12647 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12648   return getLoopDisposition(S, L) == LoopInvariant;
12649 }
12650 
12651 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12652   return getLoopDisposition(S, L) == LoopComputable;
12653 }
12654 
12655 ScalarEvolution::BlockDisposition
12656 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12657   auto &Values = BlockDispositions[S];
12658   for (auto &V : Values) {
12659     if (V.getPointer() == BB)
12660       return V.getInt();
12661   }
12662   Values.emplace_back(BB, DoesNotDominateBlock);
12663   BlockDisposition D = computeBlockDisposition(S, BB);
12664   auto &Values2 = BlockDispositions[S];
12665   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12666     if (V.getPointer() == BB) {
12667       V.setInt(D);
12668       break;
12669     }
12670   }
12671   return D;
12672 }
12673 
12674 ScalarEvolution::BlockDisposition
12675 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12676   switch (S->getSCEVType()) {
12677   case scConstant:
12678     return ProperlyDominatesBlock;
12679   case scPtrToInt:
12680   case scTruncate:
12681   case scZeroExtend:
12682   case scSignExtend:
12683     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12684   case scAddRecExpr: {
12685     // This uses a "dominates" query instead of "properly dominates" query
12686     // to test for proper dominance too, because the instruction which
12687     // produces the addrec's value is a PHI, and a PHI effectively properly
12688     // dominates its entire containing block.
12689     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12690     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12691       return DoesNotDominateBlock;
12692 
12693     // Fall through into SCEVNAryExpr handling.
12694     LLVM_FALLTHROUGH;
12695   }
12696   case scAddExpr:
12697   case scMulExpr:
12698   case scUMaxExpr:
12699   case scSMaxExpr:
12700   case scUMinExpr:
12701   case scSMinExpr: {
12702     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12703     bool Proper = true;
12704     for (const SCEV *NAryOp : NAry->operands()) {
12705       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12706       if (D == DoesNotDominateBlock)
12707         return DoesNotDominateBlock;
12708       if (D == DominatesBlock)
12709         Proper = false;
12710     }
12711     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12712   }
12713   case scUDivExpr: {
12714     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12715     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12716     BlockDisposition LD = getBlockDisposition(LHS, BB);
12717     if (LD == DoesNotDominateBlock)
12718       return DoesNotDominateBlock;
12719     BlockDisposition RD = getBlockDisposition(RHS, BB);
12720     if (RD == DoesNotDominateBlock)
12721       return DoesNotDominateBlock;
12722     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12723       ProperlyDominatesBlock : DominatesBlock;
12724   }
12725   case scUnknown:
12726     if (Instruction *I =
12727           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12728       if (I->getParent() == BB)
12729         return DominatesBlock;
12730       if (DT.properlyDominates(I->getParent(), BB))
12731         return ProperlyDominatesBlock;
12732       return DoesNotDominateBlock;
12733     }
12734     return ProperlyDominatesBlock;
12735   case scCouldNotCompute:
12736     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12737   }
12738   llvm_unreachable("Unknown SCEV kind!");
12739 }
12740 
12741 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12742   return getBlockDisposition(S, BB) >= DominatesBlock;
12743 }
12744 
12745 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12746   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12747 }
12748 
12749 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12750   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12751 }
12752 
12753 void
12754 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12755   ValuesAtScopes.erase(S);
12756   LoopDispositions.erase(S);
12757   BlockDispositions.erase(S);
12758   UnsignedRanges.erase(S);
12759   SignedRanges.erase(S);
12760   ExprValueMap.erase(S);
12761   HasRecMap.erase(S);
12762   MinTrailingZerosCache.erase(S);
12763 
12764   for (auto I = PredicatedSCEVRewrites.begin();
12765        I != PredicatedSCEVRewrites.end();) {
12766     std::pair<const SCEV *, const Loop *> Entry = I->first;
12767     if (Entry.first == S)
12768       PredicatedSCEVRewrites.erase(I++);
12769     else
12770       ++I;
12771   }
12772 
12773   auto RemoveSCEVFromBackedgeMap =
12774       [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12775         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12776           BackedgeTakenInfo &BEInfo = I->second;
12777           if (BEInfo.hasOperand(S))
12778             Map.erase(I++);
12779           else
12780             ++I;
12781         }
12782       };
12783 
12784   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12785   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12786 }
12787 
12788 void
12789 ScalarEvolution::getUsedLoops(const SCEV *S,
12790                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12791   struct FindUsedLoops {
12792     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12793         : LoopsUsed(LoopsUsed) {}
12794     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12795     bool follow(const SCEV *S) {
12796       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12797         LoopsUsed.insert(AR->getLoop());
12798       return true;
12799     }
12800 
12801     bool isDone() const { return false; }
12802   };
12803 
12804   FindUsedLoops F(LoopsUsed);
12805   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12806 }
12807 
12808 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12809   SmallPtrSet<const Loop *, 8> LoopsUsed;
12810   getUsedLoops(S, LoopsUsed);
12811   for (auto *L : LoopsUsed)
12812     LoopUsers[L].push_back(S);
12813 }
12814 
12815 void ScalarEvolution::verify() const {
12816   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12817   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12818 
12819   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12820 
12821   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12822   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12823     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12824 
12825     const SCEV *visitConstant(const SCEVConstant *Constant) {
12826       return SE.getConstant(Constant->getAPInt());
12827     }
12828 
12829     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12830       return SE.getUnknown(Expr->getValue());
12831     }
12832 
12833     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12834       return SE.getCouldNotCompute();
12835     }
12836   };
12837 
12838   SCEVMapper SCM(SE2);
12839 
12840   while (!LoopStack.empty()) {
12841     auto *L = LoopStack.pop_back_val();
12842     llvm::append_range(LoopStack, *L);
12843 
12844     auto *CurBECount = SCM.visit(
12845         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12846     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12847 
12848     if (CurBECount == SE2.getCouldNotCompute() ||
12849         NewBECount == SE2.getCouldNotCompute()) {
12850       // NB! This situation is legal, but is very suspicious -- whatever pass
12851       // change the loop to make a trip count go from could not compute to
12852       // computable or vice-versa *should have* invalidated SCEV.  However, we
12853       // choose not to assert here (for now) since we don't want false
12854       // positives.
12855       continue;
12856     }
12857 
12858     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12859       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12860       // not propagate undef aggressively).  This means we can (and do) fail
12861       // verification in cases where a transform makes the trip count of a loop
12862       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12863       // both cases the loop iterates "undef" times, but SCEV thinks we
12864       // increased the trip count of the loop by 1 incorrectly.
12865       continue;
12866     }
12867 
12868     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12869         SE.getTypeSizeInBits(NewBECount->getType()))
12870       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12871     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12872              SE.getTypeSizeInBits(NewBECount->getType()))
12873       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12874 
12875     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12876 
12877     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12878     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12879       dbgs() << "Trip Count for " << *L << " Changed!\n";
12880       dbgs() << "Old: " << *CurBECount << "\n";
12881       dbgs() << "New: " << *NewBECount << "\n";
12882       dbgs() << "Delta: " << *Delta << "\n";
12883       std::abort();
12884     }
12885   }
12886 
12887   // Collect all valid loops currently in LoopInfo.
12888   SmallPtrSet<Loop *, 32> ValidLoops;
12889   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12890   while (!Worklist.empty()) {
12891     Loop *L = Worklist.pop_back_val();
12892     if (ValidLoops.contains(L))
12893       continue;
12894     ValidLoops.insert(L);
12895     Worklist.append(L->begin(), L->end());
12896   }
12897   // Check for SCEV expressions referencing invalid/deleted loops.
12898   for (auto &KV : ValueExprMap) {
12899     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12900     if (!AR)
12901       continue;
12902     assert(ValidLoops.contains(AR->getLoop()) &&
12903            "AddRec references invalid loop");
12904   }
12905 }
12906 
12907 bool ScalarEvolution::invalidate(
12908     Function &F, const PreservedAnalyses &PA,
12909     FunctionAnalysisManager::Invalidator &Inv) {
12910   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12911   // of its dependencies is invalidated.
12912   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12913   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12914          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12915          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12916          Inv.invalidate<LoopAnalysis>(F, PA);
12917 }
12918 
12919 AnalysisKey ScalarEvolutionAnalysis::Key;
12920 
12921 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12922                                              FunctionAnalysisManager &AM) {
12923   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12924                          AM.getResult<AssumptionAnalysis>(F),
12925                          AM.getResult<DominatorTreeAnalysis>(F),
12926                          AM.getResult<LoopAnalysis>(F));
12927 }
12928 
12929 PreservedAnalyses
12930 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12931   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12932   return PreservedAnalyses::all();
12933 }
12934 
12935 PreservedAnalyses
12936 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12937   // For compatibility with opt's -analyze feature under legacy pass manager
12938   // which was not ported to NPM. This keeps tests using
12939   // update_analyze_test_checks.py working.
12940   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12941      << F.getName() << "':\n";
12942   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12943   return PreservedAnalyses::all();
12944 }
12945 
12946 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12947                       "Scalar Evolution Analysis", false, true)
12948 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12949 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12950 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12951 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12952 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12953                     "Scalar Evolution Analysis", false, true)
12954 
12955 char ScalarEvolutionWrapperPass::ID = 0;
12956 
12957 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12958   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12959 }
12960 
12961 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12962   SE.reset(new ScalarEvolution(
12963       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12964       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12965       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12966       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12967   return false;
12968 }
12969 
12970 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12971 
12972 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12973   SE->print(OS);
12974 }
12975 
12976 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12977   if (!VerifySCEV)
12978     return;
12979 
12980   SE->verify();
12981 }
12982 
12983 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12984   AU.setPreservesAll();
12985   AU.addRequiredTransitive<AssumptionCacheTracker>();
12986   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12987   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12988   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12989 }
12990 
12991 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12992                                                         const SCEV *RHS) {
12993   FoldingSetNodeID ID;
12994   assert(LHS->getType() == RHS->getType() &&
12995          "Type mismatch between LHS and RHS");
12996   // Unique this node based on the arguments
12997   ID.AddInteger(SCEVPredicate::P_Equal);
12998   ID.AddPointer(LHS);
12999   ID.AddPointer(RHS);
13000   void *IP = nullptr;
13001   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13002     return S;
13003   SCEVEqualPredicate *Eq = new (SCEVAllocator)
13004       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
13005   UniquePreds.InsertNode(Eq, IP);
13006   return Eq;
13007 }
13008 
13009 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13010     const SCEVAddRecExpr *AR,
13011     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13012   FoldingSetNodeID ID;
13013   // Unique this node based on the arguments
13014   ID.AddInteger(SCEVPredicate::P_Wrap);
13015   ID.AddPointer(AR);
13016   ID.AddInteger(AddedFlags);
13017   void *IP = nullptr;
13018   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13019     return S;
13020   auto *OF = new (SCEVAllocator)
13021       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13022   UniquePreds.InsertNode(OF, IP);
13023   return OF;
13024 }
13025 
13026 namespace {
13027 
13028 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13029 public:
13030 
13031   /// Rewrites \p S in the context of a loop L and the SCEV predication
13032   /// infrastructure.
13033   ///
13034   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13035   /// equivalences present in \p Pred.
13036   ///
13037   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13038   /// \p NewPreds such that the result will be an AddRecExpr.
13039   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13040                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13041                              SCEVUnionPredicate *Pred) {
13042     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13043     return Rewriter.visit(S);
13044   }
13045 
13046   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13047     if (Pred) {
13048       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
13049       for (auto *Pred : ExprPreds)
13050         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
13051           if (IPred->getLHS() == Expr)
13052             return IPred->getRHS();
13053     }
13054     return convertToAddRecWithPreds(Expr);
13055   }
13056 
13057   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13058     const SCEV *Operand = visit(Expr->getOperand());
13059     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13060     if (AR && AR->getLoop() == L && AR->isAffine()) {
13061       // This couldn't be folded because the operand didn't have the nuw
13062       // flag. Add the nusw flag as an assumption that we could make.
13063       const SCEV *Step = AR->getStepRecurrence(SE);
13064       Type *Ty = Expr->getType();
13065       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13066         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13067                                 SE.getSignExtendExpr(Step, Ty), L,
13068                                 AR->getNoWrapFlags());
13069     }
13070     return SE.getZeroExtendExpr(Operand, Expr->getType());
13071   }
13072 
13073   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13074     const SCEV *Operand = visit(Expr->getOperand());
13075     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13076     if (AR && AR->getLoop() == L && AR->isAffine()) {
13077       // This couldn't be folded because the operand didn't have the nsw
13078       // flag. Add the nssw flag as an assumption that we could make.
13079       const SCEV *Step = AR->getStepRecurrence(SE);
13080       Type *Ty = Expr->getType();
13081       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13082         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13083                                 SE.getSignExtendExpr(Step, Ty), L,
13084                                 AR->getNoWrapFlags());
13085     }
13086     return SE.getSignExtendExpr(Operand, Expr->getType());
13087   }
13088 
13089 private:
13090   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13091                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13092                         SCEVUnionPredicate *Pred)
13093       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13094 
13095   bool addOverflowAssumption(const SCEVPredicate *P) {
13096     if (!NewPreds) {
13097       // Check if we've already made this assumption.
13098       return Pred && Pred->implies(P);
13099     }
13100     NewPreds->insert(P);
13101     return true;
13102   }
13103 
13104   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13105                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13106     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13107     return addOverflowAssumption(A);
13108   }
13109 
13110   // If \p Expr represents a PHINode, we try to see if it can be represented
13111   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13112   // to add this predicate as a runtime overflow check, we return the AddRec.
13113   // If \p Expr does not meet these conditions (is not a PHI node, or we
13114   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13115   // return \p Expr.
13116   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13117     if (!isa<PHINode>(Expr->getValue()))
13118       return Expr;
13119     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13120     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13121     if (!PredicatedRewrite)
13122       return Expr;
13123     for (auto *P : PredicatedRewrite->second){
13124       // Wrap predicates from outer loops are not supported.
13125       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13126         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
13127         if (L != AR->getLoop())
13128           return Expr;
13129       }
13130       if (!addOverflowAssumption(P))
13131         return Expr;
13132     }
13133     return PredicatedRewrite->first;
13134   }
13135 
13136   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13137   SCEVUnionPredicate *Pred;
13138   const Loop *L;
13139 };
13140 
13141 } // end anonymous namespace
13142 
13143 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13144                                                    SCEVUnionPredicate &Preds) {
13145   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13146 }
13147 
13148 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13149     const SCEV *S, const Loop *L,
13150     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13151   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13152   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13153   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13154 
13155   if (!AddRec)
13156     return nullptr;
13157 
13158   // Since the transformation was successful, we can now transfer the SCEV
13159   // predicates.
13160   for (auto *P : TransformPreds)
13161     Preds.insert(P);
13162 
13163   return AddRec;
13164 }
13165 
13166 /// SCEV predicates
13167 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13168                              SCEVPredicateKind Kind)
13169     : FastID(ID), Kind(Kind) {}
13170 
13171 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13172                                        const SCEV *LHS, const SCEV *RHS)
13173     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13174   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13175   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13176 }
13177 
13178 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13179   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13180 
13181   if (!Op)
13182     return false;
13183 
13184   return Op->LHS == LHS && Op->RHS == RHS;
13185 }
13186 
13187 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13188 
13189 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13190 
13191 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13192   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13193 }
13194 
13195 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13196                                      const SCEVAddRecExpr *AR,
13197                                      IncrementWrapFlags Flags)
13198     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13199 
13200 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13201 
13202 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13203   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13204 
13205   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13206 }
13207 
13208 bool SCEVWrapPredicate::isAlwaysTrue() const {
13209   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13210   IncrementWrapFlags IFlags = Flags;
13211 
13212   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13213     IFlags = clearFlags(IFlags, IncrementNSSW);
13214 
13215   return IFlags == IncrementAnyWrap;
13216 }
13217 
13218 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13219   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13220   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13221     OS << "<nusw>";
13222   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13223     OS << "<nssw>";
13224   OS << "\n";
13225 }
13226 
13227 SCEVWrapPredicate::IncrementWrapFlags
13228 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13229                                    ScalarEvolution &SE) {
13230   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13231   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13232 
13233   // We can safely transfer the NSW flag as NSSW.
13234   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13235     ImpliedFlags = IncrementNSSW;
13236 
13237   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13238     // If the increment is positive, the SCEV NUW flag will also imply the
13239     // WrapPredicate NUSW flag.
13240     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13241       if (Step->getValue()->getValue().isNonNegative())
13242         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13243   }
13244 
13245   return ImpliedFlags;
13246 }
13247 
13248 /// Union predicates don't get cached so create a dummy set ID for it.
13249 SCEVUnionPredicate::SCEVUnionPredicate()
13250     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13251 
13252 bool SCEVUnionPredicate::isAlwaysTrue() const {
13253   return all_of(Preds,
13254                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13255 }
13256 
13257 ArrayRef<const SCEVPredicate *>
13258 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13259   auto I = SCEVToPreds.find(Expr);
13260   if (I == SCEVToPreds.end())
13261     return ArrayRef<const SCEVPredicate *>();
13262   return I->second;
13263 }
13264 
13265 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13266   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13267     return all_of(Set->Preds,
13268                   [this](const SCEVPredicate *I) { return this->implies(I); });
13269 
13270   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13271   if (ScevPredsIt == SCEVToPreds.end())
13272     return false;
13273   auto &SCEVPreds = ScevPredsIt->second;
13274 
13275   return any_of(SCEVPreds,
13276                 [N](const SCEVPredicate *I) { return I->implies(N); });
13277 }
13278 
13279 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13280 
13281 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13282   for (auto Pred : Preds)
13283     Pred->print(OS, Depth);
13284 }
13285 
13286 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13287   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13288     for (auto Pred : Set->Preds)
13289       add(Pred);
13290     return;
13291   }
13292 
13293   if (implies(N))
13294     return;
13295 
13296   const SCEV *Key = N->getExpr();
13297   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13298                 " associated expression!");
13299 
13300   SCEVToPreds[Key].push_back(N);
13301   Preds.push_back(N);
13302 }
13303 
13304 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13305                                                      Loop &L)
13306     : SE(SE), L(L) {}
13307 
13308 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13309   const SCEV *Expr = SE.getSCEV(V);
13310   RewriteEntry &Entry = RewriteMap[Expr];
13311 
13312   // If we already have an entry and the version matches, return it.
13313   if (Entry.second && Generation == Entry.first)
13314     return Entry.second;
13315 
13316   // We found an entry but it's stale. Rewrite the stale entry
13317   // according to the current predicate.
13318   if (Entry.second)
13319     Expr = Entry.second;
13320 
13321   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13322   Entry = {Generation, NewSCEV};
13323 
13324   return NewSCEV;
13325 }
13326 
13327 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13328   if (!BackedgeCount) {
13329     SCEVUnionPredicate BackedgePred;
13330     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13331     addPredicate(BackedgePred);
13332   }
13333   return BackedgeCount;
13334 }
13335 
13336 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13337   if (Preds.implies(&Pred))
13338     return;
13339   Preds.add(&Pred);
13340   updateGeneration();
13341 }
13342 
13343 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13344   return Preds;
13345 }
13346 
13347 void PredicatedScalarEvolution::updateGeneration() {
13348   // If the generation number wrapped recompute everything.
13349   if (++Generation == 0) {
13350     for (auto &II : RewriteMap) {
13351       const SCEV *Rewritten = II.second.second;
13352       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13353     }
13354   }
13355 }
13356 
13357 void PredicatedScalarEvolution::setNoOverflow(
13358     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13359   const SCEV *Expr = getSCEV(V);
13360   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13361 
13362   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13363 
13364   // Clear the statically implied flags.
13365   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13366   addPredicate(*SE.getWrapPredicate(AR, Flags));
13367 
13368   auto II = FlagsMap.insert({V, Flags});
13369   if (!II.second)
13370     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13371 }
13372 
13373 bool PredicatedScalarEvolution::hasNoOverflow(
13374     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13375   const SCEV *Expr = getSCEV(V);
13376   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13377 
13378   Flags = SCEVWrapPredicate::clearFlags(
13379       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13380 
13381   auto II = FlagsMap.find(V);
13382 
13383   if (II != FlagsMap.end())
13384     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13385 
13386   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13387 }
13388 
13389 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13390   const SCEV *Expr = this->getSCEV(V);
13391   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13392   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13393 
13394   if (!New)
13395     return nullptr;
13396 
13397   for (auto *P : NewPreds)
13398     Preds.add(P);
13399 
13400   updateGeneration();
13401   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13402   return New;
13403 }
13404 
13405 PredicatedScalarEvolution::PredicatedScalarEvolution(
13406     const PredicatedScalarEvolution &Init)
13407     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13408       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13409   for (auto I : Init.FlagsMap)
13410     FlagsMap.insert(I);
13411 }
13412 
13413 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13414   // For each block.
13415   for (auto *BB : L.getBlocks())
13416     for (auto &I : *BB) {
13417       if (!SE.isSCEVable(I.getType()))
13418         continue;
13419 
13420       auto *Expr = SE.getSCEV(&I);
13421       auto II = RewriteMap.find(Expr);
13422 
13423       if (II == RewriteMap.end())
13424         continue;
13425 
13426       // Don't print things that are not interesting.
13427       if (II->second.second == Expr)
13428         continue;
13429 
13430       OS.indent(Depth) << "[PSE]" << I << ":\n";
13431       OS.indent(Depth + 2) << *Expr << "\n";
13432       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13433     }
13434 }
13435 
13436 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13437 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13438 // for URem with constant power-of-2 second operands.
13439 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13440 // 4, A / B becomes X / 8).
13441 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13442                                 const SCEV *&RHS) {
13443   // Try to match 'zext (trunc A to iB) to iY', which is used
13444   // for URem with constant power-of-2 second operands. Make sure the size of
13445   // the operand A matches the size of the whole expressions.
13446   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13447     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13448       LHS = Trunc->getOperand();
13449       // Bail out if the type of the LHS is larger than the type of the
13450       // expression for now.
13451       if (getTypeSizeInBits(LHS->getType()) >
13452           getTypeSizeInBits(Expr->getType()))
13453         return false;
13454       if (LHS->getType() != Expr->getType())
13455         LHS = getZeroExtendExpr(LHS, Expr->getType());
13456       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13457                         << getTypeSizeInBits(Trunc->getType()));
13458       return true;
13459     }
13460   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13461   if (Add == nullptr || Add->getNumOperands() != 2)
13462     return false;
13463 
13464   const SCEV *A = Add->getOperand(1);
13465   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13466 
13467   if (Mul == nullptr)
13468     return false;
13469 
13470   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13471     // (SomeExpr + (-(SomeExpr / B) * B)).
13472     if (Expr == getURemExpr(A, B)) {
13473       LHS = A;
13474       RHS = B;
13475       return true;
13476     }
13477     return false;
13478   };
13479 
13480   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13481   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13482     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13483            MatchURemWithDivisor(Mul->getOperand(2));
13484 
13485   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13486   if (Mul->getNumOperands() == 2)
13487     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13488            MatchURemWithDivisor(Mul->getOperand(0)) ||
13489            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13490            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13491   return false;
13492 }
13493 
13494 const SCEV *
13495 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13496   SmallVector<BasicBlock*, 16> ExitingBlocks;
13497   L->getExitingBlocks(ExitingBlocks);
13498 
13499   // Form an expression for the maximum exit count possible for this loop. We
13500   // merge the max and exact information to approximate a version of
13501   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13502   SmallVector<const SCEV*, 4> ExitCounts;
13503   for (BasicBlock *ExitingBB : ExitingBlocks) {
13504     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13505     if (isa<SCEVCouldNotCompute>(ExitCount))
13506       ExitCount = getExitCount(L, ExitingBB,
13507                                   ScalarEvolution::ConstantMaximum);
13508     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13509       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13510              "We should only have known counts for exiting blocks that "
13511              "dominate latch!");
13512       ExitCounts.push_back(ExitCount);
13513     }
13514   }
13515   if (ExitCounts.empty())
13516     return getCouldNotCompute();
13517   return getUMinFromMismatchedTypes(ExitCounts);
13518 }
13519 
13520 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13521 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13522 /// we cannot guarantee that the replacement is loop invariant in the loop of
13523 /// the AddRec.
13524 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13525   ValueToSCEVMapTy &Map;
13526 
13527 public:
13528   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13529       : SCEVRewriteVisitor(SE), Map(M) {}
13530 
13531   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13532 
13533   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13534     auto I = Map.find(Expr->getValue());
13535     if (I == Map.end())
13536       return Expr;
13537     return I->second;
13538   }
13539 };
13540 
13541 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13542   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13543                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13544     // If we have LHS == 0, check if LHS is computing a property of some unknown
13545     // SCEV %v which we can rewrite %v to express explicitly.
13546     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13547     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13548         RHSC->getValue()->isNullValue()) {
13549       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13550       // explicitly express that.
13551       const SCEV *URemLHS = nullptr;
13552       const SCEV *URemRHS = nullptr;
13553       if (matchURem(LHS, URemLHS, URemRHS)) {
13554         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13555           Value *V = LHSUnknown->getValue();
13556           auto Multiple =
13557               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13558                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13559           RewriteMap[V] = Multiple;
13560           return;
13561         }
13562       }
13563     }
13564 
13565     if (!isa<SCEVUnknown>(LHS)) {
13566       std::swap(LHS, RHS);
13567       Predicate = CmpInst::getSwappedPredicate(Predicate);
13568     }
13569 
13570     // For now, limit to conditions that provide information about unknown
13571     // expressions.
13572     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13573     if (!LHSUnknown)
13574       return;
13575 
13576     // Check whether LHS has already been rewritten. In that case we want to
13577     // chain further rewrites onto the already rewritten value.
13578     auto I = RewriteMap.find(LHSUnknown->getValue());
13579     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13580 
13581     // TODO: use information from more predicates.
13582     switch (Predicate) {
13583     case CmpInst::ICMP_ULT:
13584       if (!containsAddRecurrence(RHS))
13585         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(
13586             RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13587       break;
13588     case CmpInst::ICMP_ULE:
13589       if (!containsAddRecurrence(RHS))
13590         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(RewrittenLHS, RHS);
13591       break;
13592     case CmpInst::ICMP_UGT:
13593       if (!containsAddRecurrence(RHS))
13594         RewriteMap[LHSUnknown->getValue()] =
13595             getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13596       break;
13597     case CmpInst::ICMP_UGE:
13598       if (!containsAddRecurrence(RHS))
13599         RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(RewrittenLHS, RHS);
13600       break;
13601     case CmpInst::ICMP_EQ:
13602       if (isa<SCEVConstant>(RHS))
13603         RewriteMap[LHSUnknown->getValue()] = RHS;
13604       break;
13605     case CmpInst::ICMP_NE:
13606       if (isa<SCEVConstant>(RHS) &&
13607           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13608         RewriteMap[LHSUnknown->getValue()] =
13609             getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
13610       break;
13611     default:
13612       break;
13613     }
13614   };
13615   // Starting at the loop predecessor, climb up the predecessor chain, as long
13616   // as there are predecessors that can be found that have unique successors
13617   // leading to the original header.
13618   // TODO: share this logic with isLoopEntryGuardedByCond.
13619   ValueToSCEVMapTy RewriteMap;
13620   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13621            L->getLoopPredecessor(), L->getHeader());
13622        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13623 
13624     const BranchInst *LoopEntryPredicate =
13625         dyn_cast<BranchInst>(Pair.first->getTerminator());
13626     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13627       continue;
13628 
13629     bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second;
13630     SmallVector<Value *, 8> Worklist;
13631     SmallPtrSet<Value *, 8> Visited;
13632     Worklist.push_back(LoopEntryPredicate->getCondition());
13633     while (!Worklist.empty()) {
13634       Value *Cond = Worklist.pop_back_val();
13635       if (!Visited.insert(Cond).second)
13636         continue;
13637 
13638       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13639         auto Predicate =
13640             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
13641         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13642                          getSCEV(Cmp->getOperand(1)), RewriteMap);
13643         continue;
13644       }
13645 
13646       Value *L, *R;
13647       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
13648                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
13649         Worklist.push_back(L);
13650         Worklist.push_back(R);
13651       }
13652     }
13653   }
13654 
13655   // Also collect information from assumptions dominating the loop.
13656   for (auto &AssumeVH : AC.assumptions()) {
13657     if (!AssumeVH)
13658       continue;
13659     auto *AssumeI = cast<CallInst>(AssumeVH);
13660     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13661     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13662       continue;
13663     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13664                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13665   }
13666 
13667   if (RewriteMap.empty())
13668     return Expr;
13669   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13670   return Rewriter.visit(Expr);
13671 }
13672