xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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(NumTripCountsComputed,
143           "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed,
145           "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147           "Number of loops with trip counts computed by force");
148 
149 static cl::opt<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151                         cl::ZeroOrMore,
152                         cl::desc("Maximum number of iterations SCEV will "
153                                  "symbolically execute a constant "
154                                  "derived loop"),
155                         cl::init(100));
156 
157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
158 static cl::opt<bool> VerifySCEV(
159     "verify-scev", cl::Hidden,
160     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
161 static cl::opt<bool> VerifySCEVStrict(
162     "verify-scev-strict", cl::Hidden,
163     cl::desc("Enable stricter verification with -verify-scev is passed"));
164 static cl::opt<bool>
165     VerifySCEVMap("verify-scev-maps", cl::Hidden,
166                   cl::desc("Verify no dangling value in ScalarEvolution's "
167                            "ExprValueMap (slow)"));
168 
169 static cl::opt<bool> VerifyIR(
170     "scev-verify-ir", cl::Hidden,
171     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
172     cl::init(false));
173 
174 static cl::opt<unsigned> MulOpsInlineThreshold(
175     "scev-mulops-inline-threshold", cl::Hidden,
176     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
177     cl::init(32));
178 
179 static cl::opt<unsigned> AddOpsInlineThreshold(
180     "scev-addops-inline-threshold", cl::Hidden,
181     cl::desc("Threshold for inlining addition operands into a SCEV"),
182     cl::init(500));
183 
184 static cl::opt<unsigned> MaxSCEVCompareDepth(
185     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
187     cl::init(32));
188 
189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
190     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
191     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
192     cl::init(2));
193 
194 static cl::opt<unsigned> MaxValueCompareDepth(
195     "scalar-evolution-max-value-compare-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive value complexity comparisons"),
197     cl::init(2));
198 
199 static cl::opt<unsigned>
200     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
201                   cl::desc("Maximum depth of recursive arithmetics"),
202                   cl::init(32));
203 
204 static cl::opt<unsigned> MaxConstantEvolvingDepth(
205     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
206     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
207 
208 static cl::opt<unsigned>
209     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
210                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
211                  cl::init(8));
212 
213 static cl::opt<unsigned>
214     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
215                   cl::desc("Max coefficients in AddRec during evolving"),
216                   cl::init(8));
217 
218 static cl::opt<unsigned>
219     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
220                   cl::desc("Size of the expression which is considered huge"),
221                   cl::init(4096));
222 
223 static cl::opt<bool>
224 ClassifyExpressions("scalar-evolution-classify-expressions",
225     cl::Hidden, cl::init(true),
226     cl::desc("When printing analysis, include information on every instruction"));
227 
228 static cl::opt<bool> UseExpensiveRangeSharpening(
229     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
230     cl::init(false),
231     cl::desc("Use more powerful methods of sharpening expression ranges. May "
232              "be costly in terms of compile time"));
233 
234 //===----------------------------------------------------------------------===//
235 //                           SCEV class definitions
236 //===----------------------------------------------------------------------===//
237 
238 //===----------------------------------------------------------------------===//
239 // Implementation of the SCEV class.
240 //
241 
242 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
243 LLVM_DUMP_METHOD void SCEV::dump() const {
244   print(dbgs());
245   dbgs() << '\n';
246 }
247 #endif
248 
249 void SCEV::print(raw_ostream &OS) const {
250   switch (getSCEVType()) {
251   case scConstant:
252     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
253     return;
254   case scPtrToInt: {
255     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
256     const SCEV *Op = PtrToInt->getOperand();
257     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
258        << *PtrToInt->getType() << ")";
259     return;
260   }
261   case scTruncate: {
262     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
263     const SCEV *Op = Trunc->getOperand();
264     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
265        << *Trunc->getType() << ")";
266     return;
267   }
268   case scZeroExtend: {
269     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
270     const SCEV *Op = ZExt->getOperand();
271     OS << "(zext " << *Op->getType() << " " << *Op << " to "
272        << *ZExt->getType() << ")";
273     return;
274   }
275   case scSignExtend: {
276     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
277     const SCEV *Op = SExt->getOperand();
278     OS << "(sext " << *Op->getType() << " " << *Op << " to "
279        << *SExt->getType() << ")";
280     return;
281   }
282   case scAddRecExpr: {
283     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
284     OS << "{" << *AR->getOperand(0);
285     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
286       OS << ",+," << *AR->getOperand(i);
287     OS << "}<";
288     if (AR->hasNoUnsignedWrap())
289       OS << "nuw><";
290     if (AR->hasNoSignedWrap())
291       OS << "nsw><";
292     if (AR->hasNoSelfWrap() &&
293         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
294       OS << "nw><";
295     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
296     OS << ">";
297     return;
298   }
299   case scAddExpr:
300   case scMulExpr:
301   case scUMaxExpr:
302   case scSMaxExpr:
303   case scUMinExpr:
304   case scSMinExpr: {
305     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
306     const char *OpStr = nullptr;
307     switch (NAry->getSCEVType()) {
308     case scAddExpr: OpStr = " + "; break;
309     case scMulExpr: OpStr = " * "; break;
310     case scUMaxExpr: OpStr = " umax "; break;
311     case scSMaxExpr: OpStr = " smax "; break;
312     case scUMinExpr:
313       OpStr = " umin ";
314       break;
315     case scSMinExpr:
316       OpStr = " smin ";
317       break;
318     default:
319       llvm_unreachable("There are no other nary expression types.");
320     }
321     OS << "(";
322     ListSeparator LS(OpStr);
323     for (const SCEV *Op : NAry->operands())
324       OS << LS << *Op;
325     OS << ")";
326     switch (NAry->getSCEVType()) {
327     case scAddExpr:
328     case scMulExpr:
329       if (NAry->hasNoUnsignedWrap())
330         OS << "<nuw>";
331       if (NAry->hasNoSignedWrap())
332         OS << "<nsw>";
333       break;
334     default:
335       // Nothing to print for other nary expressions.
336       break;
337     }
338     return;
339   }
340   case scUDivExpr: {
341     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
342     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
343     return;
344   }
345   case scUnknown: {
346     const SCEVUnknown *U = cast<SCEVUnknown>(this);
347     Type *AllocTy;
348     if (U->isSizeOf(AllocTy)) {
349       OS << "sizeof(" << *AllocTy << ")";
350       return;
351     }
352     if (U->isAlignOf(AllocTy)) {
353       OS << "alignof(" << *AllocTy << ")";
354       return;
355     }
356 
357     Type *CTy;
358     Constant *FieldNo;
359     if (U->isOffsetOf(CTy, FieldNo)) {
360       OS << "offsetof(" << *CTy << ", ";
361       FieldNo->printAsOperand(OS, false);
362       OS << ")";
363       return;
364     }
365 
366     // Otherwise just print it normally.
367     U->getValue()->printAsOperand(OS, false);
368     return;
369   }
370   case scCouldNotCompute:
371     OS << "***COULDNOTCOMPUTE***";
372     return;
373   }
374   llvm_unreachable("Unknown SCEV kind!");
375 }
376 
377 Type *SCEV::getType() const {
378   switch (getSCEVType()) {
379   case scConstant:
380     return cast<SCEVConstant>(this)->getType();
381   case scPtrToInt:
382   case scTruncate:
383   case scZeroExtend:
384   case scSignExtend:
385     return cast<SCEVCastExpr>(this)->getType();
386   case scAddRecExpr:
387     return cast<SCEVAddRecExpr>(this)->getType();
388   case scMulExpr:
389     return cast<SCEVMulExpr>(this)->getType();
390   case scUMaxExpr:
391   case scSMaxExpr:
392   case scUMinExpr:
393   case scSMinExpr:
394     return cast<SCEVMinMaxExpr>(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<GEPOperator>(CE)->getSourceElementType();
535               return true;
536             }
537 
538   return false;
539 }
540 
541 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
542   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
543     if (VCE->getOpcode() == Instruction::PtrToInt)
544       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
545         if (CE->getOpcode() == Instruction::GetElementPtr &&
546             CE->getOperand(0)->isNullValue()) {
547           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
548           if (StructType *STy = dyn_cast<StructType>(Ty))
549             if (!STy->isPacked() &&
550                 CE->getNumOperands() == 3 &&
551                 CE->getOperand(1)->isNullValue()) {
552               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
553                 if (CI->isOne() &&
554                     STy->getNumElements() == 2 &&
555                     STy->getElementType(0)->isIntegerTy(1)) {
556                   AllocTy = STy->getElementType(1);
557                   return true;
558                 }
559             }
560         }
561 
562   return false;
563 }
564 
565 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
566   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
567     if (VCE->getOpcode() == Instruction::PtrToInt)
568       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
569         if (CE->getOpcode() == Instruction::GetElementPtr &&
570             CE->getNumOperands() == 3 &&
571             CE->getOperand(0)->isNullValue() &&
572             CE->getOperand(1)->isNullValue()) {
573           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
574           // Ignore vector types here so that ScalarEvolutionExpander doesn't
575           // emit getelementptrs that index into vectors.
576           if (Ty->isStructTy() || Ty->isArrayTy()) {
577             CTy = Ty;
578             FieldNo = CE->getOperand(2);
579             return true;
580           }
581         }
582 
583   return false;
584 }
585 
586 //===----------------------------------------------------------------------===//
587 //                               SCEV Utilities
588 //===----------------------------------------------------------------------===//
589 
590 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
591 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
592 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
593 /// have been previously deemed to be "equally complex" by this routine.  It is
594 /// intended to avoid exponential time complexity in cases like:
595 ///
596 ///   %a = f(%x, %y)
597 ///   %b = f(%a, %a)
598 ///   %c = f(%b, %b)
599 ///
600 ///   %d = f(%x, %y)
601 ///   %e = f(%d, %d)
602 ///   %f = f(%e, %e)
603 ///
604 ///   CompareValueComplexity(%f, %c)
605 ///
606 /// Since we do not continue running this routine on expression trees once we
607 /// have seen unequal values, there is no need to track them in the cache.
608 static int
609 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
610                        const LoopInfo *const LI, Value *LV, Value *RV,
611                        unsigned Depth) {
612   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
613     return 0;
614 
615   // Order pointer values after integer values. This helps SCEVExpander form
616   // GEPs.
617   bool LIsPointer = LV->getType()->isPointerTy(),
618        RIsPointer = RV->getType()->isPointerTy();
619   if (LIsPointer != RIsPointer)
620     return (int)LIsPointer - (int)RIsPointer;
621 
622   // Compare getValueID values.
623   unsigned LID = LV->getValueID(), RID = RV->getValueID();
624   if (LID != RID)
625     return (int)LID - (int)RID;
626 
627   // Sort arguments by their position.
628   if (const auto *LA = dyn_cast<Argument>(LV)) {
629     const auto *RA = cast<Argument>(RV);
630     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
631     return (int)LArgNo - (int)RArgNo;
632   }
633 
634   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
635     const auto *RGV = cast<GlobalValue>(RV);
636 
637     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
638       auto LT = GV->getLinkage();
639       return !(GlobalValue::isPrivateLinkage(LT) ||
640                GlobalValue::isInternalLinkage(LT));
641     };
642 
643     // Use the names to distinguish the two values, but only if the
644     // names are semantically important.
645     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
646       return LGV->getName().compare(RGV->getName());
647   }
648 
649   // For instructions, compare their loop depth, and their operand count.  This
650   // is pretty loose.
651   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
652     const auto *RInst = cast<Instruction>(RV);
653 
654     // Compare loop depths.
655     const BasicBlock *LParent = LInst->getParent(),
656                      *RParent = RInst->getParent();
657     if (LParent != RParent) {
658       unsigned LDepth = LI->getLoopDepth(LParent),
659                RDepth = LI->getLoopDepth(RParent);
660       if (LDepth != RDepth)
661         return (int)LDepth - (int)RDepth;
662     }
663 
664     // Compare the number of operands.
665     unsigned LNumOps = LInst->getNumOperands(),
666              RNumOps = RInst->getNumOperands();
667     if (LNumOps != RNumOps)
668       return (int)LNumOps - (int)RNumOps;
669 
670     for (unsigned Idx : seq(0u, LNumOps)) {
671       int Result =
672           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
673                                  RInst->getOperand(Idx), Depth + 1);
674       if (Result != 0)
675         return Result;
676     }
677   }
678 
679   EqCacheValue.unionSets(LV, RV);
680   return 0;
681 }
682 
683 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
684 // than RHS, respectively. A three-way result allows recursive comparisons to be
685 // more efficient.
686 // If the max analysis depth was reached, return None, assuming we do not know
687 // if they are equivalent for sure.
688 static Optional<int>
689 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
690                       EquivalenceClasses<const Value *> &EqCacheValue,
691                       const LoopInfo *const LI, const SCEV *LHS,
692                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
693   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
694   if (LHS == RHS)
695     return 0;
696 
697   // Primarily, sort the SCEVs by their getSCEVType().
698   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
699   if (LType != RType)
700     return (int)LType - (int)RType;
701 
702   if (EqCacheSCEV.isEquivalent(LHS, RHS))
703     return 0;
704 
705   if (Depth > MaxSCEVCompareDepth)
706     return None;
707 
708   // Aside from the getSCEVType() ordering, the particular ordering
709   // isn't very important except that it's beneficial to be consistent,
710   // so that (a + b) and (b + a) don't end up as different expressions.
711   switch (LType) {
712   case scUnknown: {
713     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
714     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
715 
716     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
717                                    RU->getValue(), Depth + 1);
718     if (X == 0)
719       EqCacheSCEV.unionSets(LHS, RHS);
720     return X;
721   }
722 
723   case scConstant: {
724     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
725     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
726 
727     // Compare constant values.
728     const APInt &LA = LC->getAPInt();
729     const APInt &RA = RC->getAPInt();
730     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
731     if (LBitWidth != RBitWidth)
732       return (int)LBitWidth - (int)RBitWidth;
733     return LA.ult(RA) ? -1 : 1;
734   }
735 
736   case scAddRecExpr: {
737     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
738     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
739 
740     // There is always a dominance between two recs that are used by one SCEV,
741     // so we can safely sort recs by loop header dominance. We require such
742     // order in getAddExpr.
743     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
744     if (LLoop != RLoop) {
745       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
746       assert(LHead != RHead && "Two loops share the same header?");
747       if (DT.dominates(LHead, RHead))
748         return 1;
749       else
750         assert(DT.dominates(RHead, LHead) &&
751                "No dominance between recurrences used by one SCEV?");
752       return -1;
753     }
754 
755     // Addrec complexity grows with operand count.
756     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
757     if (LNumOps != RNumOps)
758       return (int)LNumOps - (int)RNumOps;
759 
760     // Lexicographically compare.
761     for (unsigned i = 0; i != LNumOps; ++i) {
762       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
763                                      LA->getOperand(i), RA->getOperand(i), DT,
764                                      Depth + 1);
765       if (X != 0)
766         return X;
767     }
768     EqCacheSCEV.unionSets(LHS, RHS);
769     return 0;
770   }
771 
772   case scAddExpr:
773   case scMulExpr:
774   case scSMaxExpr:
775   case scUMaxExpr:
776   case scSMinExpr:
777   case scUMinExpr: {
778     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
779     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
780 
781     // Lexicographically compare n-ary expressions.
782     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
783     if (LNumOps != RNumOps)
784       return (int)LNumOps - (int)RNumOps;
785 
786     for (unsigned i = 0; i != LNumOps; ++i) {
787       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
788                                      LC->getOperand(i), RC->getOperand(i), DT,
789                                      Depth + 1);
790       if (X != 0)
791         return X;
792     }
793     EqCacheSCEV.unionSets(LHS, RHS);
794     return 0;
795   }
796 
797   case scUDivExpr: {
798     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
799     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
800 
801     // Lexicographically compare udiv expressions.
802     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
803                                    RC->getLHS(), DT, Depth + 1);
804     if (X != 0)
805       return X;
806     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
807                               RC->getRHS(), DT, Depth + 1);
808     if (X == 0)
809       EqCacheSCEV.unionSets(LHS, RHS);
810     return X;
811   }
812 
813   case scPtrToInt:
814   case scTruncate:
815   case scZeroExtend:
816   case scSignExtend: {
817     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
818     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
819 
820     // Compare cast expressions by operand.
821     auto X =
822         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
823                               RC->getOperand(), DT, Depth + 1);
824     if (X == 0)
825       EqCacheSCEV.unionSets(LHS, RHS);
826     return X;
827   }
828 
829   case scCouldNotCompute:
830     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
831   }
832   llvm_unreachable("Unknown SCEV kind!");
833 }
834 
835 /// Given a list of SCEV objects, order them by their complexity, and group
836 /// objects of the same complexity together by value.  When this routine is
837 /// finished, we know that any duplicates in the vector are consecutive and that
838 /// complexity is monotonically increasing.
839 ///
840 /// Note that we go take special precautions to ensure that we get deterministic
841 /// results from this routine.  In other words, we don't want the results of
842 /// this to depend on where the addresses of various SCEV objects happened to
843 /// land in memory.
844 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
845                               LoopInfo *LI, DominatorTree &DT) {
846   if (Ops.size() < 2) return;  // Noop
847 
848   EquivalenceClasses<const SCEV *> EqCacheSCEV;
849   EquivalenceClasses<const Value *> EqCacheValue;
850 
851   // Whether LHS has provably less complexity than RHS.
852   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
853     auto Complexity =
854         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
855     return Complexity && *Complexity < 0;
856   };
857   if (Ops.size() == 2) {
858     // This is the common case, which also happens to be trivially simple.
859     // Special case it.
860     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
861     if (IsLessComplex(RHS, LHS))
862       std::swap(LHS, RHS);
863     return;
864   }
865 
866   // Do the rough sort by complexity.
867   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
868     return IsLessComplex(LHS, RHS);
869   });
870 
871   // Now that we are sorted by complexity, group elements of the same
872   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
873   // be extremely short in practice.  Note that we take this approach because we
874   // do not want to depend on the addresses of the objects we are grouping.
875   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
876     const SCEV *S = Ops[i];
877     unsigned Complexity = S->getSCEVType();
878 
879     // If there are any objects of the same complexity and same value as this
880     // one, group them.
881     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
882       if (Ops[j] == S) { // Found a duplicate.
883         // Move it to immediately after i'th element.
884         std::swap(Ops[i+1], Ops[j]);
885         ++i;   // no need to rescan it.
886         if (i == e-2) return;  // Done!
887       }
888     }
889   }
890 }
891 
892 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
893 /// least HugeExprThreshold nodes).
894 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
895   return any_of(Ops, [](const SCEV *S) {
896     return S->getExpressionSize() >= HugeExprThreshold;
897   });
898 }
899 
900 //===----------------------------------------------------------------------===//
901 //                      Simple SCEV method implementations
902 //===----------------------------------------------------------------------===//
903 
904 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
905 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
906                                        ScalarEvolution &SE,
907                                        Type *ResultTy) {
908   // Handle the simplest case efficiently.
909   if (K == 1)
910     return SE.getTruncateOrZeroExtend(It, ResultTy);
911 
912   // We are using the following formula for BC(It, K):
913   //
914   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
915   //
916   // Suppose, W is the bitwidth of the return value.  We must be prepared for
917   // overflow.  Hence, we must assure that the result of our computation is
918   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
919   // safe in modular arithmetic.
920   //
921   // However, this code doesn't use exactly that formula; the formula it uses
922   // is something like the following, where T is the number of factors of 2 in
923   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
924   // exponentiation:
925   //
926   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
927   //
928   // This formula is trivially equivalent to the previous formula.  However,
929   // this formula can be implemented much more efficiently.  The trick is that
930   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
931   // arithmetic.  To do exact division in modular arithmetic, all we have
932   // to do is multiply by the inverse.  Therefore, this step can be done at
933   // width W.
934   //
935   // The next issue is how to safely do the division by 2^T.  The way this
936   // is done is by doing the multiplication step at a width of at least W + T
937   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
938   // when we perform the division by 2^T (which is equivalent to a right shift
939   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
940   // truncated out after the division by 2^T.
941   //
942   // In comparison to just directly using the first formula, this technique
943   // is much more efficient; using the first formula requires W * K bits,
944   // but this formula less than W + K bits. Also, the first formula requires
945   // a division step, whereas this formula only requires multiplies and shifts.
946   //
947   // It doesn't matter whether the subtraction step is done in the calculation
948   // width or the input iteration count's width; if the subtraction overflows,
949   // the result must be zero anyway.  We prefer here to do it in the width of
950   // the induction variable because it helps a lot for certain cases; CodeGen
951   // isn't smart enough to ignore the overflow, which leads to much less
952   // efficient code if the width of the subtraction is wider than the native
953   // register width.
954   //
955   // (It's possible to not widen at all by pulling out factors of 2 before
956   // the multiplication; for example, K=2 can be calculated as
957   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
958   // extra arithmetic, so it's not an obvious win, and it gets
959   // much more complicated for K > 3.)
960 
961   // Protection from insane SCEVs; this bound is conservative,
962   // but it probably doesn't matter.
963   if (K > 1000)
964     return SE.getCouldNotCompute();
965 
966   unsigned W = SE.getTypeSizeInBits(ResultTy);
967 
968   // Calculate K! / 2^T and T; we divide out the factors of two before
969   // multiplying for calculating K! / 2^T to avoid overflow.
970   // Other overflow doesn't matter because we only care about the bottom
971   // W bits of the result.
972   APInt OddFactorial(W, 1);
973   unsigned T = 1;
974   for (unsigned i = 3; i <= K; ++i) {
975     APInt Mult(W, i);
976     unsigned TwoFactors = Mult.countTrailingZeros();
977     T += TwoFactors;
978     Mult.lshrInPlace(TwoFactors);
979     OddFactorial *= Mult;
980   }
981 
982   // We need at least W + T bits for the multiplication step
983   unsigned CalculationBits = W + T;
984 
985   // Calculate 2^T, at width T+W.
986   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
987 
988   // Calculate the multiplicative inverse of K! / 2^T;
989   // this multiplication factor will perform the exact division by
990   // K! / 2^T.
991   APInt Mod = APInt::getSignedMinValue(W+1);
992   APInt MultiplyFactor = OddFactorial.zext(W+1);
993   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
994   MultiplyFactor = MultiplyFactor.trunc(W);
995 
996   // Calculate the product, at width T+W
997   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
998                                                       CalculationBits);
999   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1000   for (unsigned i = 1; i != K; ++i) {
1001     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1002     Dividend = SE.getMulExpr(Dividend,
1003                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1004   }
1005 
1006   // Divide by 2^T
1007   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1008 
1009   // Truncate the result, and divide by K! / 2^T.
1010 
1011   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1012                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1013 }
1014 
1015 /// Return the value of this chain of recurrences at the specified iteration
1016 /// number.  We can evaluate this recurrence by multiplying each element in the
1017 /// chain by the binomial coefficient corresponding to it.  In other words, we
1018 /// can evaluate {A,+,B,+,C,+,D} as:
1019 ///
1020 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1021 ///
1022 /// where BC(It, k) stands for binomial coefficient.
1023 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1024                                                 ScalarEvolution &SE) const {
1025   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1026 }
1027 
1028 const SCEV *
1029 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1030                                     const SCEV *It, ScalarEvolution &SE) {
1031   assert(Operands.size() > 0);
1032   const SCEV *Result = Operands[0];
1033   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1034     // The computation is correct in the face of overflow provided that the
1035     // multiplication is performed _after_ the evaluation of the binomial
1036     // coefficient.
1037     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1038     if (isa<SCEVCouldNotCompute>(Coeff))
1039       return Coeff;
1040 
1041     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1042   }
1043   return Result;
1044 }
1045 
1046 //===----------------------------------------------------------------------===//
1047 //                    SCEV Expression folder implementations
1048 //===----------------------------------------------------------------------===//
1049 
1050 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1051                                                      unsigned Depth) {
1052   assert(Depth <= 1 &&
1053          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1054 
1055   // We could be called with an integer-typed operands during SCEV rewrites.
1056   // Since the operand is an integer already, just perform zext/trunc/self cast.
1057   if (!Op->getType()->isPointerTy())
1058     return Op;
1059 
1060   // What would be an ID for such a SCEV cast expression?
1061   FoldingSetNodeID ID;
1062   ID.AddInteger(scPtrToInt);
1063   ID.AddPointer(Op);
1064 
1065   void *IP = nullptr;
1066 
1067   // Is there already an expression for such a cast?
1068   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1069     return S;
1070 
1071   // It isn't legal for optimizations to construct new ptrtoint expressions
1072   // for non-integral pointers.
1073   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1074     return getCouldNotCompute();
1075 
1076   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1077 
1078   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1079   // is sufficiently wide to represent all possible pointer values.
1080   // We could theoretically teach SCEV to truncate wider pointers, but
1081   // that isn't implemented for now.
1082   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1083       getDataLayout().getTypeSizeInBits(IntPtrTy))
1084     return getCouldNotCompute();
1085 
1086   // If not, is this expression something we can't reduce any further?
1087   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1088     // Perform some basic constant folding. If the operand of the ptr2int cast
1089     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1090     // left as-is), but produce a zero constant.
1091     // NOTE: We could handle a more general case, but lack motivational cases.
1092     if (isa<ConstantPointerNull>(U->getValue()))
1093       return getZero(IntPtrTy);
1094 
1095     // Create an explicit cast node.
1096     // We can reuse the existing insert position since if we get here,
1097     // we won't have made any changes which would invalidate it.
1098     SCEV *S = new (SCEVAllocator)
1099         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1100     UniqueSCEVs.InsertNode(S, IP);
1101     registerUser(S, Op);
1102     return S;
1103   }
1104 
1105   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1106                        "non-SCEVUnknown's.");
1107 
1108   // Otherwise, we've got some expression that is more complex than just a
1109   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1110   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1111   // only, and the expressions must otherwise be integer-typed.
1112   // So sink the cast down to the SCEVUnknown's.
1113 
1114   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1115   /// which computes a pointer-typed value, and rewrites the whole expression
1116   /// tree so that *all* the computations are done on integers, and the only
1117   /// pointer-typed operands in the expression are SCEVUnknown.
1118   class SCEVPtrToIntSinkingRewriter
1119       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1120     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1121 
1122   public:
1123     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1124 
1125     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1126       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1127       return Rewriter.visit(Scev);
1128     }
1129 
1130     const SCEV *visit(const SCEV *S) {
1131       Type *STy = S->getType();
1132       // If the expression is not pointer-typed, just keep it as-is.
1133       if (!STy->isPointerTy())
1134         return S;
1135       // Else, recursively sink the cast down into it.
1136       return Base::visit(S);
1137     }
1138 
1139     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1140       SmallVector<const SCEV *, 2> Operands;
1141       bool Changed = false;
1142       for (auto *Op : Expr->operands()) {
1143         Operands.push_back(visit(Op));
1144         Changed |= Op != Operands.back();
1145       }
1146       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1147     }
1148 
1149     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1150       SmallVector<const SCEV *, 2> Operands;
1151       bool Changed = false;
1152       for (auto *Op : Expr->operands()) {
1153         Operands.push_back(visit(Op));
1154         Changed |= Op != Operands.back();
1155       }
1156       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1157     }
1158 
1159     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1160       assert(Expr->getType()->isPointerTy() &&
1161              "Should only reach pointer-typed SCEVUnknown's.");
1162       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1163     }
1164   };
1165 
1166   // And actually perform the cast sinking.
1167   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1168   assert(IntOp->getType()->isIntegerTy() &&
1169          "We must have succeeded in sinking the cast, "
1170          "and ending up with an integer-typed expression!");
1171   return IntOp;
1172 }
1173 
1174 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1175   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1176 
1177   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1178   if (isa<SCEVCouldNotCompute>(IntOp))
1179     return IntOp;
1180 
1181   return getTruncateOrZeroExtend(IntOp, Ty);
1182 }
1183 
1184 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1185                                              unsigned Depth) {
1186   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1187          "This is not a truncating conversion!");
1188   assert(isSCEVable(Ty) &&
1189          "This is not a conversion to a SCEVable type!");
1190   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1191   Ty = getEffectiveSCEVType(Ty);
1192 
1193   FoldingSetNodeID ID;
1194   ID.AddInteger(scTruncate);
1195   ID.AddPointer(Op);
1196   ID.AddPointer(Ty);
1197   void *IP = nullptr;
1198   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1199 
1200   // Fold if the operand is constant.
1201   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1202     return getConstant(
1203       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1204 
1205   // trunc(trunc(x)) --> trunc(x)
1206   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1207     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1208 
1209   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1210   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1211     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1212 
1213   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1214   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1215     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1216 
1217   if (Depth > MaxCastDepth) {
1218     SCEV *S =
1219         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1220     UniqueSCEVs.InsertNode(S, IP);
1221     registerUser(S, Op);
1222     return S;
1223   }
1224 
1225   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1226   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1227   // if after transforming we have at most one truncate, not counting truncates
1228   // that replace other casts.
1229   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1230     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1231     SmallVector<const SCEV *, 4> Operands;
1232     unsigned numTruncs = 0;
1233     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1234          ++i) {
1235       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1236       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1237           isa<SCEVTruncateExpr>(S))
1238         numTruncs++;
1239       Operands.push_back(S);
1240     }
1241     if (numTruncs < 2) {
1242       if (isa<SCEVAddExpr>(Op))
1243         return getAddExpr(Operands);
1244       else if (isa<SCEVMulExpr>(Op))
1245         return getMulExpr(Operands);
1246       else
1247         llvm_unreachable("Unexpected SCEV type for Op.");
1248     }
1249     // Although we checked in the beginning that ID is not in the cache, it is
1250     // possible that during recursion and different modification ID was inserted
1251     // into the cache. So if we find it, just return it.
1252     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1253       return S;
1254   }
1255 
1256   // If the input value is a chrec scev, truncate the chrec's operands.
1257   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1258     SmallVector<const SCEV *, 4> Operands;
1259     for (const SCEV *Op : AddRec->operands())
1260       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1261     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1262   }
1263 
1264   // Return zero if truncating to known zeros.
1265   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1266   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1267     return getZero(Ty);
1268 
1269   // The cast wasn't folded; create an explicit cast node. We can reuse
1270   // the existing insert position since if we get here, we won't have
1271   // made any changes which would invalidate it.
1272   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1273                                                  Op, Ty);
1274   UniqueSCEVs.InsertNode(S, IP);
1275   registerUser(S, Op);
1276   return S;
1277 }
1278 
1279 // Get the limit of a recurrence such that incrementing by Step cannot cause
1280 // signed overflow as long as the value of the recurrence within the
1281 // loop does not exceed this limit before incrementing.
1282 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1283                                                  ICmpInst::Predicate *Pred,
1284                                                  ScalarEvolution *SE) {
1285   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1286   if (SE->isKnownPositive(Step)) {
1287     *Pred = ICmpInst::ICMP_SLT;
1288     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1289                            SE->getSignedRangeMax(Step));
1290   }
1291   if (SE->isKnownNegative(Step)) {
1292     *Pred = ICmpInst::ICMP_SGT;
1293     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1294                            SE->getSignedRangeMin(Step));
1295   }
1296   return nullptr;
1297 }
1298 
1299 // Get the limit of a recurrence such that incrementing by Step cannot cause
1300 // unsigned overflow as long as the value of the recurrence within the loop does
1301 // not exceed this limit before incrementing.
1302 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1303                                                    ICmpInst::Predicate *Pred,
1304                                                    ScalarEvolution *SE) {
1305   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1306   *Pred = ICmpInst::ICMP_ULT;
1307 
1308   return SE->getConstant(APInt::getMinValue(BitWidth) -
1309                          SE->getUnsignedRangeMax(Step));
1310 }
1311 
1312 namespace {
1313 
1314 struct ExtendOpTraitsBase {
1315   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1316                                                           unsigned);
1317 };
1318 
1319 // Used to make code generic over signed and unsigned overflow.
1320 template <typename ExtendOp> struct ExtendOpTraits {
1321   // Members present:
1322   //
1323   // static const SCEV::NoWrapFlags WrapType;
1324   //
1325   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1326   //
1327   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1328   //                                           ICmpInst::Predicate *Pred,
1329   //                                           ScalarEvolution *SE);
1330 };
1331 
1332 template <>
1333 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1334   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1335 
1336   static const GetExtendExprTy GetExtendExpr;
1337 
1338   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1339                                              ICmpInst::Predicate *Pred,
1340                                              ScalarEvolution *SE) {
1341     return getSignedOverflowLimitForStep(Step, Pred, SE);
1342   }
1343 };
1344 
1345 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1346     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1347 
1348 template <>
1349 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1350   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1351 
1352   static const GetExtendExprTy GetExtendExpr;
1353 
1354   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1355                                              ICmpInst::Predicate *Pred,
1356                                              ScalarEvolution *SE) {
1357     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1358   }
1359 };
1360 
1361 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1362     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1363 
1364 } // end anonymous namespace
1365 
1366 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1367 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1368 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1369 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1370 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1371 // expression "Step + sext/zext(PreIncAR)" is congruent with
1372 // "sext/zext(PostIncAR)"
1373 template <typename ExtendOpTy>
1374 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1375                                         ScalarEvolution *SE, unsigned Depth) {
1376   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1377   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1378 
1379   const Loop *L = AR->getLoop();
1380   const SCEV *Start = AR->getStart();
1381   const SCEV *Step = AR->getStepRecurrence(*SE);
1382 
1383   // Check for a simple looking step prior to loop entry.
1384   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1385   if (!SA)
1386     return nullptr;
1387 
1388   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1389   // subtraction is expensive. For this purpose, perform a quick and dirty
1390   // difference, by checking for Step in the operand list.
1391   SmallVector<const SCEV *, 4> DiffOps;
1392   for (const SCEV *Op : SA->operands())
1393     if (Op != Step)
1394       DiffOps.push_back(Op);
1395 
1396   if (DiffOps.size() == SA->getNumOperands())
1397     return nullptr;
1398 
1399   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1400   // `Step`:
1401 
1402   // 1. NSW/NUW flags on the step increment.
1403   auto PreStartFlags =
1404     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1405   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1406   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1407       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1408 
1409   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1410   // "S+X does not sign/unsign-overflow".
1411   //
1412 
1413   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1414   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1415       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1416     return PreStart;
1417 
1418   // 2. Direct overflow check on the step operation's expression.
1419   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1420   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1421   const SCEV *OperandExtendedStart =
1422       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1423                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1424   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1425     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1426       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1427       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1428       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1429       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1430     }
1431     return PreStart;
1432   }
1433 
1434   // 3. Loop precondition.
1435   ICmpInst::Predicate Pred;
1436   const SCEV *OverflowLimit =
1437       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1438 
1439   if (OverflowLimit &&
1440       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1441     return PreStart;
1442 
1443   return nullptr;
1444 }
1445 
1446 // Get the normalized zero or sign extended expression for this AddRec's Start.
1447 template <typename ExtendOpTy>
1448 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1449                                         ScalarEvolution *SE,
1450                                         unsigned Depth) {
1451   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1452 
1453   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1454   if (!PreStart)
1455     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1456 
1457   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1458                                              Depth),
1459                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1460 }
1461 
1462 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1463 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1464 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1465 //
1466 // Formally:
1467 //
1468 //     {S,+,X} == {S-T,+,X} + T
1469 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1470 //
1471 // If ({S-T,+,X} + T) does not overflow  ... (1)
1472 //
1473 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1474 //
1475 // If {S-T,+,X} does not overflow  ... (2)
1476 //
1477 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1478 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1479 //
1480 // If (S-T)+T does not overflow  ... (3)
1481 //
1482 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1483 //      == {Ext(S),+,Ext(X)} == LHS
1484 //
1485 // Thus, if (1), (2) and (3) are true for some T, then
1486 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1487 //
1488 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1489 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1490 // to check for (1) and (2).
1491 //
1492 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1493 // is `Delta` (defined below).
1494 template <typename ExtendOpTy>
1495 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1496                                                 const SCEV *Step,
1497                                                 const Loop *L) {
1498   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1499 
1500   // We restrict `Start` to a constant to prevent SCEV from spending too much
1501   // time here.  It is correct (but more expensive) to continue with a
1502   // non-constant `Start` and do a general SCEV subtraction to compute
1503   // `PreStart` below.
1504   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1505   if (!StartC)
1506     return false;
1507 
1508   APInt StartAI = StartC->getAPInt();
1509 
1510   for (unsigned Delta : {-2, -1, 1, 2}) {
1511     const SCEV *PreStart = getConstant(StartAI - Delta);
1512 
1513     FoldingSetNodeID ID;
1514     ID.AddInteger(scAddRecExpr);
1515     ID.AddPointer(PreStart);
1516     ID.AddPointer(Step);
1517     ID.AddPointer(L);
1518     void *IP = nullptr;
1519     const auto *PreAR =
1520       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1521 
1522     // Give up if we don't already have the add recurrence we need because
1523     // actually constructing an add recurrence is relatively expensive.
1524     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1525       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1526       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1527       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1528           DeltaS, &Pred, this);
1529       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1530         return true;
1531     }
1532   }
1533 
1534   return false;
1535 }
1536 
1537 // Finds an integer D for an expression (C + x + y + ...) such that the top
1538 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1539 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1540 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1541 // the (C + x + y + ...) expression is \p WholeAddExpr.
1542 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1543                                             const SCEVConstant *ConstantTerm,
1544                                             const SCEVAddExpr *WholeAddExpr) {
1545   const APInt &C = ConstantTerm->getAPInt();
1546   const unsigned BitWidth = C.getBitWidth();
1547   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1548   uint32_t TZ = BitWidth;
1549   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1550     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1551   if (TZ) {
1552     // Set D to be as many least significant bits of C as possible while still
1553     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1554     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1555   }
1556   return APInt(BitWidth, 0);
1557 }
1558 
1559 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1560 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1561 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1562 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1563 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1564                                             const APInt &ConstantStart,
1565                                             const SCEV *Step) {
1566   const unsigned BitWidth = ConstantStart.getBitWidth();
1567   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1568   if (TZ)
1569     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1570                          : ConstantStart;
1571   return APInt(BitWidth, 0);
1572 }
1573 
1574 const SCEV *
1575 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1576   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1577          "This is not an extending conversion!");
1578   assert(isSCEVable(Ty) &&
1579          "This is not a conversion to a SCEVable type!");
1580   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1581   Ty = getEffectiveSCEVType(Ty);
1582 
1583   // Fold if the operand is constant.
1584   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1585     return getConstant(
1586       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1587 
1588   // zext(zext(x)) --> zext(x)
1589   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1590     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1591 
1592   // Before doing any expensive analysis, check to see if we've already
1593   // computed a SCEV for this Op and Ty.
1594   FoldingSetNodeID ID;
1595   ID.AddInteger(scZeroExtend);
1596   ID.AddPointer(Op);
1597   ID.AddPointer(Ty);
1598   void *IP = nullptr;
1599   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1600   if (Depth > MaxCastDepth) {
1601     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1602                                                      Op, Ty);
1603     UniqueSCEVs.InsertNode(S, IP);
1604     registerUser(S, Op);
1605     return S;
1606   }
1607 
1608   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1609   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1610     // It's possible the bits taken off by the truncate were all zero bits. If
1611     // so, we should be able to simplify this further.
1612     const SCEV *X = ST->getOperand();
1613     ConstantRange CR = getUnsignedRange(X);
1614     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1615     unsigned NewBits = getTypeSizeInBits(Ty);
1616     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1617             CR.zextOrTrunc(NewBits)))
1618       return getTruncateOrZeroExtend(X, Ty, Depth);
1619   }
1620 
1621   // If the input value is a chrec scev, and we can prove that the value
1622   // did not overflow the old, smaller, value, we can zero extend all of the
1623   // operands (often constants).  This allows analysis of something like
1624   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1625   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1626     if (AR->isAffine()) {
1627       const SCEV *Start = AR->getStart();
1628       const SCEV *Step = AR->getStepRecurrence(*this);
1629       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1630       const Loop *L = AR->getLoop();
1631 
1632       if (!AR->hasNoUnsignedWrap()) {
1633         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1634         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1635       }
1636 
1637       // If we have special knowledge that this addrec won't overflow,
1638       // we don't need to do any further analysis.
1639       if (AR->hasNoUnsignedWrap())
1640         return getAddRecExpr(
1641             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1642             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1643 
1644       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1645       // Note that this serves two purposes: It filters out loops that are
1646       // simply not analyzable, and it covers the case where this code is
1647       // being called from within backedge-taken count analysis, such that
1648       // attempting to ask for the backedge-taken count would likely result
1649       // in infinite recursion. In the later case, the analysis code will
1650       // cope with a conservative value, and it will take care to purge
1651       // that value once it has finished.
1652       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1653       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1654         // Manually compute the final value for AR, checking for overflow.
1655 
1656         // Check whether the backedge-taken count can be losslessly casted to
1657         // the addrec's type. The count is always unsigned.
1658         const SCEV *CastedMaxBECount =
1659             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1660         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1661             CastedMaxBECount, MaxBECount->getType(), Depth);
1662         if (MaxBECount == RecastedMaxBECount) {
1663           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1664           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1665           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1666                                         SCEV::FlagAnyWrap, Depth + 1);
1667           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1668                                                           SCEV::FlagAnyWrap,
1669                                                           Depth + 1),
1670                                                WideTy, Depth + 1);
1671           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1672           const SCEV *WideMaxBECount =
1673             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1674           const SCEV *OperandExtendedAdd =
1675             getAddExpr(WideStart,
1676                        getMulExpr(WideMaxBECount,
1677                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1678                                   SCEV::FlagAnyWrap, Depth + 1),
1679                        SCEV::FlagAnyWrap, Depth + 1);
1680           if (ZAdd == OperandExtendedAdd) {
1681             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1682             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1683             // Return the expression with the addrec on the outside.
1684             return getAddRecExpr(
1685                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1686                                                          Depth + 1),
1687                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1688                 AR->getNoWrapFlags());
1689           }
1690           // Similar to above, only this time treat the step value as signed.
1691           // This covers loops that count down.
1692           OperandExtendedAdd =
1693             getAddExpr(WideStart,
1694                        getMulExpr(WideMaxBECount,
1695                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1696                                   SCEV::FlagAnyWrap, Depth + 1),
1697                        SCEV::FlagAnyWrap, Depth + 1);
1698           if (ZAdd == OperandExtendedAdd) {
1699             // Cache knowledge of AR NW, which is propagated to this AddRec.
1700             // Negative step causes unsigned wrap, but it still can't self-wrap.
1701             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1702             // Return the expression with the addrec on the outside.
1703             return getAddRecExpr(
1704                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1705                                                          Depth + 1),
1706                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1707                 AR->getNoWrapFlags());
1708           }
1709         }
1710       }
1711 
1712       // Normally, in the cases we can prove no-overflow via a
1713       // backedge guarding condition, we can also compute a backedge
1714       // taken count for the loop.  The exceptions are assumptions and
1715       // guards present in the loop -- SCEV is not great at exploiting
1716       // these to compute max backedge taken counts, but can still use
1717       // these to prove lack of overflow.  Use this fact to avoid
1718       // doing extra work that may not pay off.
1719       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1720           !AC.assumptions().empty()) {
1721 
1722         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1723         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1724         if (AR->hasNoUnsignedWrap()) {
1725           // Same as nuw case above - duplicated here to avoid a compile time
1726           // issue.  It's not clear that the order of checks does matter, but
1727           // it's one of two issue possible causes for a change which was
1728           // reverted.  Be conservative for the moment.
1729           return getAddRecExpr(
1730                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1731                                                          Depth + 1),
1732                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1733                 AR->getNoWrapFlags());
1734         }
1735 
1736         // For a negative step, we can extend the operands iff doing so only
1737         // traverses values in the range zext([0,UINT_MAX]).
1738         if (isKnownNegative(Step)) {
1739           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1740                                       getSignedRangeMin(Step));
1741           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1742               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1743             // Cache knowledge of AR NW, which is propagated to this
1744             // AddRec.  Negative step causes unsigned wrap, but it
1745             // still can't self-wrap.
1746             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1747             // Return the expression with the addrec on the outside.
1748             return getAddRecExpr(
1749                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1750                                                          Depth + 1),
1751                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1752                 AR->getNoWrapFlags());
1753           }
1754         }
1755       }
1756 
1757       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1758       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1759       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1760       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1761         const APInt &C = SC->getAPInt();
1762         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1763         if (D != 0) {
1764           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1765           const SCEV *SResidual =
1766               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1767           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1768           return getAddExpr(SZExtD, SZExtR,
1769                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1770                             Depth + 1);
1771         }
1772       }
1773 
1774       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1775         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1776         return getAddRecExpr(
1777             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1778             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1779       }
1780     }
1781 
1782   // zext(A % B) --> zext(A) % zext(B)
1783   {
1784     const SCEV *LHS;
1785     const SCEV *RHS;
1786     if (matchURem(Op, LHS, RHS))
1787       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1788                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1789   }
1790 
1791   // zext(A / B) --> zext(A) / zext(B).
1792   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1793     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1794                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1795 
1796   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1797     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1798     if (SA->hasNoUnsignedWrap()) {
1799       // If the addition does not unsign overflow then we can, by definition,
1800       // commute the zero extension with the addition operation.
1801       SmallVector<const SCEV *, 4> Ops;
1802       for (const auto *Op : SA->operands())
1803         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1804       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1805     }
1806 
1807     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1808     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1809     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1810     //
1811     // Often address arithmetics contain expressions like
1812     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1813     // This transformation is useful while proving that such expressions are
1814     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1815     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1816       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1817       if (D != 0) {
1818         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1819         const SCEV *SResidual =
1820             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1821         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1822         return getAddExpr(SZExtD, SZExtR,
1823                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1824                           Depth + 1);
1825       }
1826     }
1827   }
1828 
1829   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1830     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1831     if (SM->hasNoUnsignedWrap()) {
1832       // If the multiply does not unsign overflow then we can, by definition,
1833       // commute the zero extension with the multiply operation.
1834       SmallVector<const SCEV *, 4> Ops;
1835       for (const auto *Op : SM->operands())
1836         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1837       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1838     }
1839 
1840     // zext(2^K * (trunc X to iN)) to iM ->
1841     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1842     //
1843     // Proof:
1844     //
1845     //     zext(2^K * (trunc X to iN)) to iM
1846     //   = zext((trunc X to iN) << K) to iM
1847     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1848     //     (because shl removes the top K bits)
1849     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1850     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1851     //
1852     if (SM->getNumOperands() == 2)
1853       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1854         if (MulLHS->getAPInt().isPowerOf2())
1855           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1856             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1857                                MulLHS->getAPInt().logBase2();
1858             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1859             return getMulExpr(
1860                 getZeroExtendExpr(MulLHS, Ty),
1861                 getZeroExtendExpr(
1862                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1863                 SCEV::FlagNUW, Depth + 1);
1864           }
1865   }
1866 
1867   // The cast wasn't folded; create an explicit cast node.
1868   // Recompute the insert position, as it may have been invalidated.
1869   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1870   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1871                                                    Op, Ty);
1872   UniqueSCEVs.InsertNode(S, IP);
1873   registerUser(S, Op);
1874   return S;
1875 }
1876 
1877 const SCEV *
1878 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1879   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1880          "This is not an extending conversion!");
1881   assert(isSCEVable(Ty) &&
1882          "This is not a conversion to a SCEVable type!");
1883   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1884   Ty = getEffectiveSCEVType(Ty);
1885 
1886   // Fold if the operand is constant.
1887   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1888     return getConstant(
1889       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1890 
1891   // sext(sext(x)) --> sext(x)
1892   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1893     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1894 
1895   // sext(zext(x)) --> zext(x)
1896   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1897     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1898 
1899   // Before doing any expensive analysis, check to see if we've already
1900   // computed a SCEV for this Op and Ty.
1901   FoldingSetNodeID ID;
1902   ID.AddInteger(scSignExtend);
1903   ID.AddPointer(Op);
1904   ID.AddPointer(Ty);
1905   void *IP = nullptr;
1906   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1907   // Limit recursion depth.
1908   if (Depth > MaxCastDepth) {
1909     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1910                                                      Op, Ty);
1911     UniqueSCEVs.InsertNode(S, IP);
1912     registerUser(S, Op);
1913     return S;
1914   }
1915 
1916   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1917   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1918     // It's possible the bits taken off by the truncate were all sign bits. If
1919     // so, we should be able to simplify this further.
1920     const SCEV *X = ST->getOperand();
1921     ConstantRange CR = getSignedRange(X);
1922     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1923     unsigned NewBits = getTypeSizeInBits(Ty);
1924     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1925             CR.sextOrTrunc(NewBits)))
1926       return getTruncateOrSignExtend(X, Ty, Depth);
1927   }
1928 
1929   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1930     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1931     if (SA->hasNoSignedWrap()) {
1932       // If the addition does not sign overflow then we can, by definition,
1933       // commute the sign extension with the addition operation.
1934       SmallVector<const SCEV *, 4> Ops;
1935       for (const auto *Op : SA->operands())
1936         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1937       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1938     }
1939 
1940     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1941     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1942     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1943     //
1944     // For instance, this will bring two seemingly different expressions:
1945     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1946     //         sext(6 + 20 * %x + 24 * %y)
1947     // to the same form:
1948     //     2 + sext(4 + 20 * %x + 24 * %y)
1949     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1950       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1951       if (D != 0) {
1952         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1953         const SCEV *SResidual =
1954             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1955         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1956         return getAddExpr(SSExtD, SSExtR,
1957                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1958                           Depth + 1);
1959       }
1960     }
1961   }
1962   // If the input value is a chrec scev, and we can prove that the value
1963   // did not overflow the old, smaller, value, we can sign extend all of the
1964   // operands (often constants).  This allows analysis of something like
1965   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1966   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1967     if (AR->isAffine()) {
1968       const SCEV *Start = AR->getStart();
1969       const SCEV *Step = AR->getStepRecurrence(*this);
1970       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1971       const Loop *L = AR->getLoop();
1972 
1973       if (!AR->hasNoSignedWrap()) {
1974         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1975         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1976       }
1977 
1978       // If we have special knowledge that this addrec won't overflow,
1979       // we don't need to do any further analysis.
1980       if (AR->hasNoSignedWrap())
1981         return getAddRecExpr(
1982             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1983             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1984 
1985       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1986       // Note that this serves two purposes: It filters out loops that are
1987       // simply not analyzable, and it covers the case where this code is
1988       // being called from within backedge-taken count analysis, such that
1989       // attempting to ask for the backedge-taken count would likely result
1990       // in infinite recursion. In the later case, the analysis code will
1991       // cope with a conservative value, and it will take care to purge
1992       // that value once it has finished.
1993       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1994       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1995         // Manually compute the final value for AR, checking for
1996         // overflow.
1997 
1998         // Check whether the backedge-taken count can be losslessly casted to
1999         // the addrec's type. The count is always unsigned.
2000         const SCEV *CastedMaxBECount =
2001             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2002         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2003             CastedMaxBECount, MaxBECount->getType(), Depth);
2004         if (MaxBECount == RecastedMaxBECount) {
2005           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2006           // Check whether Start+Step*MaxBECount has no signed overflow.
2007           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2008                                         SCEV::FlagAnyWrap, Depth + 1);
2009           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2010                                                           SCEV::FlagAnyWrap,
2011                                                           Depth + 1),
2012                                                WideTy, Depth + 1);
2013           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2014           const SCEV *WideMaxBECount =
2015             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2016           const SCEV *OperandExtendedAdd =
2017             getAddExpr(WideStart,
2018                        getMulExpr(WideMaxBECount,
2019                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2020                                   SCEV::FlagAnyWrap, Depth + 1),
2021                        SCEV::FlagAnyWrap, Depth + 1);
2022           if (SAdd == OperandExtendedAdd) {
2023             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2024             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2025             // Return the expression with the addrec on the outside.
2026             return getAddRecExpr(
2027                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2028                                                          Depth + 1),
2029                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2030                 AR->getNoWrapFlags());
2031           }
2032           // Similar to above, only this time treat the step value as unsigned.
2033           // This covers loops that count up with an unsigned step.
2034           OperandExtendedAdd =
2035             getAddExpr(WideStart,
2036                        getMulExpr(WideMaxBECount,
2037                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2038                                   SCEV::FlagAnyWrap, Depth + 1),
2039                        SCEV::FlagAnyWrap, Depth + 1);
2040           if (SAdd == OperandExtendedAdd) {
2041             // If AR wraps around then
2042             //
2043             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2044             // => SAdd != OperandExtendedAdd
2045             //
2046             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2047             // (SAdd == OperandExtendedAdd => AR is NW)
2048 
2049             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2050 
2051             // Return the expression with the addrec on the outside.
2052             return getAddRecExpr(
2053                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2054                                                          Depth + 1),
2055                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2056                 AR->getNoWrapFlags());
2057           }
2058         }
2059       }
2060 
2061       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2062       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2063       if (AR->hasNoSignedWrap()) {
2064         // Same as nsw case above - duplicated here to avoid a compile time
2065         // issue.  It's not clear that the order of checks does matter, but
2066         // it's one of two issue possible causes for a change which was
2067         // reverted.  Be conservative for the moment.
2068         return getAddRecExpr(
2069             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2070             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2071       }
2072 
2073       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2074       // if D + (C - D + Step * n) could be proven to not signed wrap
2075       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2076       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2077         const APInt &C = SC->getAPInt();
2078         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2079         if (D != 0) {
2080           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2081           const SCEV *SResidual =
2082               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2083           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2084           return getAddExpr(SSExtD, SSExtR,
2085                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2086                             Depth + 1);
2087         }
2088       }
2089 
2090       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2091         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2092         return getAddRecExpr(
2093             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2094             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2095       }
2096     }
2097 
2098   // If the input value is provably positive and we could not simplify
2099   // away the sext build a zext instead.
2100   if (isKnownNonNegative(Op))
2101     return getZeroExtendExpr(Op, Ty, Depth + 1);
2102 
2103   // The cast wasn't folded; create an explicit cast node.
2104   // Recompute the insert position, as it may have been invalidated.
2105   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2106   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2107                                                    Op, Ty);
2108   UniqueSCEVs.InsertNode(S, IP);
2109   registerUser(S, { Op });
2110   return S;
2111 }
2112 
2113 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2114 /// unspecified bits out to the given type.
2115 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2116                                               Type *Ty) {
2117   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2118          "This is not an extending conversion!");
2119   assert(isSCEVable(Ty) &&
2120          "This is not a conversion to a SCEVable type!");
2121   Ty = getEffectiveSCEVType(Ty);
2122 
2123   // Sign-extend negative constants.
2124   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2125     if (SC->getAPInt().isNegative())
2126       return getSignExtendExpr(Op, Ty);
2127 
2128   // Peel off a truncate cast.
2129   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2130     const SCEV *NewOp = T->getOperand();
2131     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2132       return getAnyExtendExpr(NewOp, Ty);
2133     return getTruncateOrNoop(NewOp, Ty);
2134   }
2135 
2136   // Next try a zext cast. If the cast is folded, use it.
2137   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2138   if (!isa<SCEVZeroExtendExpr>(ZExt))
2139     return ZExt;
2140 
2141   // Next try a sext cast. If the cast is folded, use it.
2142   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2143   if (!isa<SCEVSignExtendExpr>(SExt))
2144     return SExt;
2145 
2146   // Force the cast to be folded into the operands of an addrec.
2147   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2148     SmallVector<const SCEV *, 4> Ops;
2149     for (const SCEV *Op : AR->operands())
2150       Ops.push_back(getAnyExtendExpr(Op, Ty));
2151     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2152   }
2153 
2154   // If the expression is obviously signed, use the sext cast value.
2155   if (isa<SCEVSMaxExpr>(Op))
2156     return SExt;
2157 
2158   // Absent any other information, use the zext cast value.
2159   return ZExt;
2160 }
2161 
2162 /// Process the given Ops list, which is a list of operands to be added under
2163 /// the given scale, update the given map. This is a helper function for
2164 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2165 /// that would form an add expression like this:
2166 ///
2167 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2168 ///
2169 /// where A and B are constants, update the map with these values:
2170 ///
2171 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2172 ///
2173 /// and add 13 + A*B*29 to AccumulatedConstant.
2174 /// This will allow getAddRecExpr to produce this:
2175 ///
2176 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2177 ///
2178 /// This form often exposes folding opportunities that are hidden in
2179 /// the original operand list.
2180 ///
2181 /// Return true iff it appears that any interesting folding opportunities
2182 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2183 /// the common case where no interesting opportunities are present, and
2184 /// is also used as a check to avoid infinite recursion.
2185 static bool
2186 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2187                              SmallVectorImpl<const SCEV *> &NewOps,
2188                              APInt &AccumulatedConstant,
2189                              const SCEV *const *Ops, size_t NumOperands,
2190                              const APInt &Scale,
2191                              ScalarEvolution &SE) {
2192   bool Interesting = false;
2193 
2194   // Iterate over the add operands. They are sorted, with constants first.
2195   unsigned i = 0;
2196   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2197     ++i;
2198     // Pull a buried constant out to the outside.
2199     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2200       Interesting = true;
2201     AccumulatedConstant += Scale * C->getAPInt();
2202   }
2203 
2204   // Next comes everything else. We're especially interested in multiplies
2205   // here, but they're in the middle, so just visit the rest with one loop.
2206   for (; i != NumOperands; ++i) {
2207     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2208     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2209       APInt NewScale =
2210           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2211       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2212         // A multiplication of a constant with another add; recurse.
2213         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2214         Interesting |=
2215           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2216                                        Add->op_begin(), Add->getNumOperands(),
2217                                        NewScale, SE);
2218       } else {
2219         // A multiplication of a constant with some other value. Update
2220         // the map.
2221         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2222         const SCEV *Key = SE.getMulExpr(MulOps);
2223         auto Pair = M.insert({Key, NewScale});
2224         if (Pair.second) {
2225           NewOps.push_back(Pair.first->first);
2226         } else {
2227           Pair.first->second += NewScale;
2228           // The map already had an entry for this value, which may indicate
2229           // a folding opportunity.
2230           Interesting = true;
2231         }
2232       }
2233     } else {
2234       // An ordinary operand. Update the map.
2235       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2236           M.insert({Ops[i], Scale});
2237       if (Pair.second) {
2238         NewOps.push_back(Pair.first->first);
2239       } else {
2240         Pair.first->second += Scale;
2241         // The map already had an entry for this value, which may indicate
2242         // a folding opportunity.
2243         Interesting = true;
2244       }
2245     }
2246   }
2247 
2248   return Interesting;
2249 }
2250 
2251 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2252                                       const SCEV *LHS, const SCEV *RHS) {
2253   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2254                                             SCEV::NoWrapFlags, unsigned);
2255   switch (BinOp) {
2256   default:
2257     llvm_unreachable("Unsupported binary op");
2258   case Instruction::Add:
2259     Operation = &ScalarEvolution::getAddExpr;
2260     break;
2261   case Instruction::Sub:
2262     Operation = &ScalarEvolution::getMinusSCEV;
2263     break;
2264   case Instruction::Mul:
2265     Operation = &ScalarEvolution::getMulExpr;
2266     break;
2267   }
2268 
2269   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2270       Signed ? &ScalarEvolution::getSignExtendExpr
2271              : &ScalarEvolution::getZeroExtendExpr;
2272 
2273   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2274   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2275   auto *WideTy =
2276       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2277 
2278   const SCEV *A = (this->*Extension)(
2279       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2280   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2281                                      (this->*Extension)(RHS, WideTy, 0),
2282                                      SCEV::FlagAnyWrap, 0);
2283   return A == B;
2284 }
2285 
2286 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2287 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2288     const OverflowingBinaryOperator *OBO) {
2289   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2290 
2291   if (OBO->hasNoUnsignedWrap())
2292     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2293   if (OBO->hasNoSignedWrap())
2294     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2295 
2296   bool Deduced = false;
2297 
2298   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2299     return {Flags, Deduced};
2300 
2301   if (OBO->getOpcode() != Instruction::Add &&
2302       OBO->getOpcode() != Instruction::Sub &&
2303       OBO->getOpcode() != Instruction::Mul)
2304     return {Flags, Deduced};
2305 
2306   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2307   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2308 
2309   if (!OBO->hasNoUnsignedWrap() &&
2310       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2311                       /* Signed */ false, LHS, RHS)) {
2312     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2313     Deduced = true;
2314   }
2315 
2316   if (!OBO->hasNoSignedWrap() &&
2317       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2318                       /* Signed */ true, LHS, RHS)) {
2319     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2320     Deduced = true;
2321   }
2322 
2323   return {Flags, Deduced};
2324 }
2325 
2326 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2327 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2328 // can't-overflow flags for the operation if possible.
2329 static SCEV::NoWrapFlags
2330 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2331                       const ArrayRef<const SCEV *> Ops,
2332                       SCEV::NoWrapFlags Flags) {
2333   using namespace std::placeholders;
2334 
2335   using OBO = OverflowingBinaryOperator;
2336 
2337   bool CanAnalyze =
2338       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2339   (void)CanAnalyze;
2340   assert(CanAnalyze && "don't call from other places!");
2341 
2342   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2343   SCEV::NoWrapFlags SignOrUnsignWrap =
2344       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2345 
2346   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2347   auto IsKnownNonNegative = [&](const SCEV *S) {
2348     return SE->isKnownNonNegative(S);
2349   };
2350 
2351   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2352     Flags =
2353         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2354 
2355   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2356 
2357   if (SignOrUnsignWrap != SignOrUnsignMask &&
2358       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2359       isa<SCEVConstant>(Ops[0])) {
2360 
2361     auto Opcode = [&] {
2362       switch (Type) {
2363       case scAddExpr:
2364         return Instruction::Add;
2365       case scMulExpr:
2366         return Instruction::Mul;
2367       default:
2368         llvm_unreachable("Unexpected SCEV op.");
2369       }
2370     }();
2371 
2372     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2373 
2374     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2375     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2376       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2377           Opcode, C, OBO::NoSignedWrap);
2378       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2379         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2380     }
2381 
2382     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2383     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2384       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2385           Opcode, C, OBO::NoUnsignedWrap);
2386       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2387         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2388     }
2389   }
2390 
2391   // <0,+,nonnegative><nw> is also nuw
2392   // TODO: Add corresponding nsw case
2393   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2394       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2395       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2396     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2397 
2398   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2399   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2400       Ops.size() == 2) {
2401     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2402       if (UDiv->getOperand(1) == Ops[1])
2403         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2404     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2405       if (UDiv->getOperand(1) == Ops[0])
2406         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2407   }
2408 
2409   return Flags;
2410 }
2411 
2412 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2413   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2414 }
2415 
2416 /// Get a canonical add expression, or something simpler if possible.
2417 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2418                                         SCEV::NoWrapFlags OrigFlags,
2419                                         unsigned Depth) {
2420   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2421          "only nuw or nsw allowed");
2422   assert(!Ops.empty() && "Cannot get empty add!");
2423   if (Ops.size() == 1) return Ops[0];
2424 #ifndef NDEBUG
2425   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2426   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2427     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2428            "SCEVAddExpr operand types don't match!");
2429   unsigned NumPtrs = count_if(
2430       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2431   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2432 #endif
2433 
2434   // Sort by complexity, this groups all similar expression types together.
2435   GroupByComplexity(Ops, &LI, DT);
2436 
2437   // If there are any constants, fold them together.
2438   unsigned Idx = 0;
2439   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2440     ++Idx;
2441     assert(Idx < Ops.size());
2442     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2443       // We found two constants, fold them together!
2444       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2445       if (Ops.size() == 2) return Ops[0];
2446       Ops.erase(Ops.begin()+1);  // Erase the folded element
2447       LHSC = cast<SCEVConstant>(Ops[0]);
2448     }
2449 
2450     // If we are left with a constant zero being added, strip it off.
2451     if (LHSC->getValue()->isZero()) {
2452       Ops.erase(Ops.begin());
2453       --Idx;
2454     }
2455 
2456     if (Ops.size() == 1) return Ops[0];
2457   }
2458 
2459   // Delay expensive flag strengthening until necessary.
2460   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2461     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2462   };
2463 
2464   // Limit recursion calls depth.
2465   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2466     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2467 
2468   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2469     // Don't strengthen flags if we have no new information.
2470     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2471     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2472       Add->setNoWrapFlags(ComputeFlags(Ops));
2473     return S;
2474   }
2475 
2476   // Okay, check to see if the same value occurs in the operand list more than
2477   // once.  If so, merge them together into an multiply expression.  Since we
2478   // sorted the list, these values are required to be adjacent.
2479   Type *Ty = Ops[0]->getType();
2480   bool FoundMatch = false;
2481   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2482     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2483       // Scan ahead to count how many equal operands there are.
2484       unsigned Count = 2;
2485       while (i+Count != e && Ops[i+Count] == Ops[i])
2486         ++Count;
2487       // Merge the values into a multiply.
2488       const SCEV *Scale = getConstant(Ty, Count);
2489       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2490       if (Ops.size() == Count)
2491         return Mul;
2492       Ops[i] = Mul;
2493       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2494       --i; e -= Count - 1;
2495       FoundMatch = true;
2496     }
2497   if (FoundMatch)
2498     return getAddExpr(Ops, OrigFlags, Depth + 1);
2499 
2500   // Check for truncates. If all the operands are truncated from the same
2501   // type, see if factoring out the truncate would permit the result to be
2502   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2503   // if the contents of the resulting outer trunc fold to something simple.
2504   auto FindTruncSrcType = [&]() -> Type * {
2505     // We're ultimately looking to fold an addrec of truncs and muls of only
2506     // constants and truncs, so if we find any other types of SCEV
2507     // as operands of the addrec then we bail and return nullptr here.
2508     // Otherwise, we return the type of the operand of a trunc that we find.
2509     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2510       return T->getOperand()->getType();
2511     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2512       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2513       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2514         return T->getOperand()->getType();
2515     }
2516     return nullptr;
2517   };
2518   if (auto *SrcType = FindTruncSrcType()) {
2519     SmallVector<const SCEV *, 8> LargeOps;
2520     bool Ok = true;
2521     // Check all the operands to see if they can be represented in the
2522     // source type of the truncate.
2523     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2524       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2525         if (T->getOperand()->getType() != SrcType) {
2526           Ok = false;
2527           break;
2528         }
2529         LargeOps.push_back(T->getOperand());
2530       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2531         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2532       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2533         SmallVector<const SCEV *, 8> LargeMulOps;
2534         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2535           if (const SCEVTruncateExpr *T =
2536                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2537             if (T->getOperand()->getType() != SrcType) {
2538               Ok = false;
2539               break;
2540             }
2541             LargeMulOps.push_back(T->getOperand());
2542           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2543             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2544           } else {
2545             Ok = false;
2546             break;
2547           }
2548         }
2549         if (Ok)
2550           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2551       } else {
2552         Ok = false;
2553         break;
2554       }
2555     }
2556     if (Ok) {
2557       // Evaluate the expression in the larger type.
2558       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2559       // If it folds to something simple, use it. Otherwise, don't.
2560       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2561         return getTruncateExpr(Fold, Ty);
2562     }
2563   }
2564 
2565   if (Ops.size() == 2) {
2566     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2567     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2568     // C1).
2569     const SCEV *A = Ops[0];
2570     const SCEV *B = Ops[1];
2571     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2572     auto *C = dyn_cast<SCEVConstant>(A);
2573     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2574       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2575       auto C2 = C->getAPInt();
2576       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2577 
2578       APInt ConstAdd = C1 + C2;
2579       auto AddFlags = AddExpr->getNoWrapFlags();
2580       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2581       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2582           ConstAdd.ule(C1)) {
2583         PreservedFlags =
2584             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2585       }
2586 
2587       // Adding a constant with the same sign and small magnitude is NSW, if the
2588       // original AddExpr was NSW.
2589       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2590           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2591           ConstAdd.abs().ule(C1.abs())) {
2592         PreservedFlags =
2593             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2594       }
2595 
2596       if (PreservedFlags != SCEV::FlagAnyWrap) {
2597         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2598         NewOps[0] = getConstant(ConstAdd);
2599         return getAddExpr(NewOps, PreservedFlags);
2600       }
2601     }
2602   }
2603 
2604   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2605   if (Ops.size() == 2) {
2606     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2607     if (Mul && Mul->getNumOperands() == 2 &&
2608         Mul->getOperand(0)->isAllOnesValue()) {
2609       const SCEV *X;
2610       const SCEV *Y;
2611       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2612         return getMulExpr(Y, getUDivExpr(X, Y));
2613       }
2614     }
2615   }
2616 
2617   // Skip past any other cast SCEVs.
2618   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2619     ++Idx;
2620 
2621   // If there are add operands they would be next.
2622   if (Idx < Ops.size()) {
2623     bool DeletedAdd = false;
2624     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2625     // common NUW flag for expression after inlining. Other flags cannot be
2626     // preserved, because they may depend on the original order of operations.
2627     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2628     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2629       if (Ops.size() > AddOpsInlineThreshold ||
2630           Add->getNumOperands() > AddOpsInlineThreshold)
2631         break;
2632       // If we have an add, expand the add operands onto the end of the operands
2633       // list.
2634       Ops.erase(Ops.begin()+Idx);
2635       Ops.append(Add->op_begin(), Add->op_end());
2636       DeletedAdd = true;
2637       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2638     }
2639 
2640     // If we deleted at least one add, we added operands to the end of the list,
2641     // and they are not necessarily sorted.  Recurse to resort and resimplify
2642     // any operands we just acquired.
2643     if (DeletedAdd)
2644       return getAddExpr(Ops, CommonFlags, Depth + 1);
2645   }
2646 
2647   // Skip over the add expression until we get to a multiply.
2648   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2649     ++Idx;
2650 
2651   // Check to see if there are any folding opportunities present with
2652   // operands multiplied by constant values.
2653   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2654     uint64_t BitWidth = getTypeSizeInBits(Ty);
2655     DenseMap<const SCEV *, APInt> M;
2656     SmallVector<const SCEV *, 8> NewOps;
2657     APInt AccumulatedConstant(BitWidth, 0);
2658     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2659                                      Ops.data(), Ops.size(),
2660                                      APInt(BitWidth, 1), *this)) {
2661       struct APIntCompare {
2662         bool operator()(const APInt &LHS, const APInt &RHS) const {
2663           return LHS.ult(RHS);
2664         }
2665       };
2666 
2667       // Some interesting folding opportunity is present, so its worthwhile to
2668       // re-generate the operands list. Group the operands by constant scale,
2669       // to avoid multiplying by the same constant scale multiple times.
2670       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2671       for (const SCEV *NewOp : NewOps)
2672         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2673       // Re-generate the operands list.
2674       Ops.clear();
2675       if (AccumulatedConstant != 0)
2676         Ops.push_back(getConstant(AccumulatedConstant));
2677       for (auto &MulOp : MulOpLists) {
2678         if (MulOp.first == 1) {
2679           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2680         } else if (MulOp.first != 0) {
2681           Ops.push_back(getMulExpr(
2682               getConstant(MulOp.first),
2683               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2684               SCEV::FlagAnyWrap, Depth + 1));
2685         }
2686       }
2687       if (Ops.empty())
2688         return getZero(Ty);
2689       if (Ops.size() == 1)
2690         return Ops[0];
2691       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2692     }
2693   }
2694 
2695   // If we are adding something to a multiply expression, make sure the
2696   // something is not already an operand of the multiply.  If so, merge it into
2697   // the multiply.
2698   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2699     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2700     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2701       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2702       if (isa<SCEVConstant>(MulOpSCEV))
2703         continue;
2704       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2705         if (MulOpSCEV == Ops[AddOp]) {
2706           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2707           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2708           if (Mul->getNumOperands() != 2) {
2709             // If the multiply has more than two operands, we must get the
2710             // Y*Z term.
2711             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2712                                                 Mul->op_begin()+MulOp);
2713             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2714             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2715           }
2716           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2717           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2718           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2719                                             SCEV::FlagAnyWrap, Depth + 1);
2720           if (Ops.size() == 2) return OuterMul;
2721           if (AddOp < Idx) {
2722             Ops.erase(Ops.begin()+AddOp);
2723             Ops.erase(Ops.begin()+Idx-1);
2724           } else {
2725             Ops.erase(Ops.begin()+Idx);
2726             Ops.erase(Ops.begin()+AddOp-1);
2727           }
2728           Ops.push_back(OuterMul);
2729           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2730         }
2731 
2732       // Check this multiply against other multiplies being added together.
2733       for (unsigned OtherMulIdx = Idx+1;
2734            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2735            ++OtherMulIdx) {
2736         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2737         // If MulOp occurs in OtherMul, we can fold the two multiplies
2738         // together.
2739         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2740              OMulOp != e; ++OMulOp)
2741           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2742             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2743             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2744             if (Mul->getNumOperands() != 2) {
2745               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2746                                                   Mul->op_begin()+MulOp);
2747               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2748               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2749             }
2750             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2751             if (OtherMul->getNumOperands() != 2) {
2752               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2753                                                   OtherMul->op_begin()+OMulOp);
2754               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2755               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2756             }
2757             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2758             const SCEV *InnerMulSum =
2759                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2760             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2761                                               SCEV::FlagAnyWrap, Depth + 1);
2762             if (Ops.size() == 2) return OuterMul;
2763             Ops.erase(Ops.begin()+Idx);
2764             Ops.erase(Ops.begin()+OtherMulIdx-1);
2765             Ops.push_back(OuterMul);
2766             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2767           }
2768       }
2769     }
2770   }
2771 
2772   // If there are any add recurrences in the operands list, see if any other
2773   // added values are loop invariant.  If so, we can fold them into the
2774   // recurrence.
2775   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2776     ++Idx;
2777 
2778   // Scan over all recurrences, trying to fold loop invariants into them.
2779   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2780     // Scan all of the other operands to this add and add them to the vector if
2781     // they are loop invariant w.r.t. the recurrence.
2782     SmallVector<const SCEV *, 8> LIOps;
2783     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2784     const Loop *AddRecLoop = AddRec->getLoop();
2785     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2786       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2787         LIOps.push_back(Ops[i]);
2788         Ops.erase(Ops.begin()+i);
2789         --i; --e;
2790       }
2791 
2792     // If we found some loop invariants, fold them into the recurrence.
2793     if (!LIOps.empty()) {
2794       // Compute nowrap flags for the addition of the loop-invariant ops and
2795       // the addrec. Temporarily push it as an operand for that purpose. These
2796       // flags are valid in the scope of the addrec only.
2797       LIOps.push_back(AddRec);
2798       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2799       LIOps.pop_back();
2800 
2801       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2802       LIOps.push_back(AddRec->getStart());
2803 
2804       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2805 
2806       // It is not in general safe to propagate flags valid on an add within
2807       // the addrec scope to one outside it.  We must prove that the inner
2808       // scope is guaranteed to execute if the outer one does to be able to
2809       // safely propagate.  We know the program is undefined if poison is
2810       // produced on the inner scoped addrec.  We also know that *for this use*
2811       // the outer scoped add can't overflow (because of the flags we just
2812       // computed for the inner scoped add) without the program being undefined.
2813       // Proving that entry to the outer scope neccesitates entry to the inner
2814       // scope, thus proves the program undefined if the flags would be violated
2815       // in the outer scope.
2816       SCEV::NoWrapFlags AddFlags = Flags;
2817       if (AddFlags != SCEV::FlagAnyWrap) {
2818         auto *DefI = getDefiningScopeBound(LIOps);
2819         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2820         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2821           AddFlags = SCEV::FlagAnyWrap;
2822       }
2823       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2824 
2825       // Build the new addrec. Propagate the NUW and NSW flags if both the
2826       // outer add and the inner addrec are guaranteed to have no overflow.
2827       // Always propagate NW.
2828       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2829       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2830 
2831       // If all of the other operands were loop invariant, we are done.
2832       if (Ops.size() == 1) return NewRec;
2833 
2834       // Otherwise, add the folded AddRec by the non-invariant parts.
2835       for (unsigned i = 0;; ++i)
2836         if (Ops[i] == AddRec) {
2837           Ops[i] = NewRec;
2838           break;
2839         }
2840       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2841     }
2842 
2843     // Okay, if there weren't any loop invariants to be folded, check to see if
2844     // there are multiple AddRec's with the same loop induction variable being
2845     // added together.  If so, we can fold them.
2846     for (unsigned OtherIdx = Idx+1;
2847          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2848          ++OtherIdx) {
2849       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2850       // so that the 1st found AddRecExpr is dominated by all others.
2851       assert(DT.dominates(
2852            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2853            AddRec->getLoop()->getHeader()) &&
2854         "AddRecExprs are not sorted in reverse dominance order?");
2855       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2856         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2857         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2858         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2859              ++OtherIdx) {
2860           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2861           if (OtherAddRec->getLoop() == AddRecLoop) {
2862             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2863                  i != e; ++i) {
2864               if (i >= AddRecOps.size()) {
2865                 AddRecOps.append(OtherAddRec->op_begin()+i,
2866                                  OtherAddRec->op_end());
2867                 break;
2868               }
2869               SmallVector<const SCEV *, 2> TwoOps = {
2870                   AddRecOps[i], OtherAddRec->getOperand(i)};
2871               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2872             }
2873             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2874           }
2875         }
2876         // Step size has changed, so we cannot guarantee no self-wraparound.
2877         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2878         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2879       }
2880     }
2881 
2882     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2883     // next one.
2884   }
2885 
2886   // Okay, it looks like we really DO need an add expr.  Check to see if we
2887   // already have one, otherwise create a new one.
2888   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2889 }
2890 
2891 const SCEV *
2892 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2893                                     SCEV::NoWrapFlags Flags) {
2894   FoldingSetNodeID ID;
2895   ID.AddInteger(scAddExpr);
2896   for (const SCEV *Op : Ops)
2897     ID.AddPointer(Op);
2898   void *IP = nullptr;
2899   SCEVAddExpr *S =
2900       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2901   if (!S) {
2902     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2903     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2904     S = new (SCEVAllocator)
2905         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2906     UniqueSCEVs.InsertNode(S, IP);
2907     registerUser(S, Ops);
2908   }
2909   S->setNoWrapFlags(Flags);
2910   return S;
2911 }
2912 
2913 const SCEV *
2914 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2915                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2916   FoldingSetNodeID ID;
2917   ID.AddInteger(scAddRecExpr);
2918   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2919     ID.AddPointer(Ops[i]);
2920   ID.AddPointer(L);
2921   void *IP = nullptr;
2922   SCEVAddRecExpr *S =
2923       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2924   if (!S) {
2925     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2926     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2927     S = new (SCEVAllocator)
2928         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2929     UniqueSCEVs.InsertNode(S, IP);
2930     LoopUsers[L].push_back(S);
2931     registerUser(S, Ops);
2932   }
2933   setNoWrapFlags(S, Flags);
2934   return S;
2935 }
2936 
2937 const SCEV *
2938 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2939                                     SCEV::NoWrapFlags Flags) {
2940   FoldingSetNodeID ID;
2941   ID.AddInteger(scMulExpr);
2942   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2943     ID.AddPointer(Ops[i]);
2944   void *IP = nullptr;
2945   SCEVMulExpr *S =
2946     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2947   if (!S) {
2948     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2949     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2950     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2951                                         O, Ops.size());
2952     UniqueSCEVs.InsertNode(S, IP);
2953     registerUser(S, Ops);
2954   }
2955   S->setNoWrapFlags(Flags);
2956   return S;
2957 }
2958 
2959 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2960   uint64_t k = i*j;
2961   if (j > 1 && k / j != i) Overflow = true;
2962   return k;
2963 }
2964 
2965 /// Compute the result of "n choose k", the binomial coefficient.  If an
2966 /// intermediate computation overflows, Overflow will be set and the return will
2967 /// be garbage. Overflow is not cleared on absence of overflow.
2968 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2969   // We use the multiplicative formula:
2970   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2971   // At each iteration, we take the n-th term of the numeral and divide by the
2972   // (k-n)th term of the denominator.  This division will always produce an
2973   // integral result, and helps reduce the chance of overflow in the
2974   // intermediate computations. However, we can still overflow even when the
2975   // final result would fit.
2976 
2977   if (n == 0 || n == k) return 1;
2978   if (k > n) return 0;
2979 
2980   if (k > n/2)
2981     k = n-k;
2982 
2983   uint64_t r = 1;
2984   for (uint64_t i = 1; i <= k; ++i) {
2985     r = umul_ov(r, n-(i-1), Overflow);
2986     r /= i;
2987   }
2988   return r;
2989 }
2990 
2991 /// Determine if any of the operands in this SCEV are a constant or if
2992 /// any of the add or multiply expressions in this SCEV contain a constant.
2993 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2994   struct FindConstantInAddMulChain {
2995     bool FoundConstant = false;
2996 
2997     bool follow(const SCEV *S) {
2998       FoundConstant |= isa<SCEVConstant>(S);
2999       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3000     }
3001 
3002     bool isDone() const {
3003       return FoundConstant;
3004     }
3005   };
3006 
3007   FindConstantInAddMulChain F;
3008   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3009   ST.visitAll(StartExpr);
3010   return F.FoundConstant;
3011 }
3012 
3013 /// Get a canonical multiply expression, or something simpler if possible.
3014 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3015                                         SCEV::NoWrapFlags OrigFlags,
3016                                         unsigned Depth) {
3017   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3018          "only nuw or nsw allowed");
3019   assert(!Ops.empty() && "Cannot get empty mul!");
3020   if (Ops.size() == 1) return Ops[0];
3021 #ifndef NDEBUG
3022   Type *ETy = Ops[0]->getType();
3023   assert(!ETy->isPointerTy());
3024   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3025     assert(Ops[i]->getType() == ETy &&
3026            "SCEVMulExpr operand types don't match!");
3027 #endif
3028 
3029   // Sort by complexity, this groups all similar expression types together.
3030   GroupByComplexity(Ops, &LI, DT);
3031 
3032   // If there are any constants, fold them together.
3033   unsigned Idx = 0;
3034   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3035     ++Idx;
3036     assert(Idx < Ops.size());
3037     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3038       // We found two constants, fold them together!
3039       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3040       if (Ops.size() == 2) return Ops[0];
3041       Ops.erase(Ops.begin()+1);  // Erase the folded element
3042       LHSC = cast<SCEVConstant>(Ops[0]);
3043     }
3044 
3045     // If we have a multiply of zero, it will always be zero.
3046     if (LHSC->getValue()->isZero())
3047       return LHSC;
3048 
3049     // If we are left with a constant one being multiplied, strip it off.
3050     if (LHSC->getValue()->isOne()) {
3051       Ops.erase(Ops.begin());
3052       --Idx;
3053     }
3054 
3055     if (Ops.size() == 1)
3056       return Ops[0];
3057   }
3058 
3059   // Delay expensive flag strengthening until necessary.
3060   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3061     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3062   };
3063 
3064   // Limit recursion calls depth.
3065   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3066     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3067 
3068   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3069     // Don't strengthen flags if we have no new information.
3070     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3071     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3072       Mul->setNoWrapFlags(ComputeFlags(Ops));
3073     return S;
3074   }
3075 
3076   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3077     if (Ops.size() == 2) {
3078       // C1*(C2+V) -> C1*C2 + C1*V
3079       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3080         // If any of Add's ops are Adds or Muls with a constant, apply this
3081         // transformation as well.
3082         //
3083         // TODO: There are some cases where this transformation is not
3084         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3085         // this transformation should be narrowed down.
3086         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
3087           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
3088                                        SCEV::FlagAnyWrap, Depth + 1),
3089                             getMulExpr(LHSC, Add->getOperand(1),
3090                                        SCEV::FlagAnyWrap, Depth + 1),
3091                             SCEV::FlagAnyWrap, Depth + 1);
3092 
3093       if (Ops[0]->isAllOnesValue()) {
3094         // If we have a mul by -1 of an add, try distributing the -1 among the
3095         // add operands.
3096         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3097           SmallVector<const SCEV *, 4> NewOps;
3098           bool AnyFolded = false;
3099           for (const SCEV *AddOp : Add->operands()) {
3100             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3101                                          Depth + 1);
3102             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3103             NewOps.push_back(Mul);
3104           }
3105           if (AnyFolded)
3106             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3107         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3108           // Negation preserves a recurrence's no self-wrap property.
3109           SmallVector<const SCEV *, 4> Operands;
3110           for (const SCEV *AddRecOp : AddRec->operands())
3111             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3112                                           Depth + 1));
3113 
3114           return getAddRecExpr(Operands, AddRec->getLoop(),
3115                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3116         }
3117       }
3118     }
3119   }
3120 
3121   // Skip over the add expression until we get to a multiply.
3122   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3123     ++Idx;
3124 
3125   // If there are mul operands inline them all into this expression.
3126   if (Idx < Ops.size()) {
3127     bool DeletedMul = false;
3128     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3129       if (Ops.size() > MulOpsInlineThreshold)
3130         break;
3131       // If we have an mul, expand the mul operands onto the end of the
3132       // operands list.
3133       Ops.erase(Ops.begin()+Idx);
3134       Ops.append(Mul->op_begin(), Mul->op_end());
3135       DeletedMul = true;
3136     }
3137 
3138     // If we deleted at least one mul, we added operands to the end of the
3139     // list, and they are not necessarily sorted.  Recurse to resort and
3140     // resimplify any operands we just acquired.
3141     if (DeletedMul)
3142       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3143   }
3144 
3145   // If there are any add recurrences in the operands list, see if any other
3146   // added values are loop invariant.  If so, we can fold them into the
3147   // recurrence.
3148   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3149     ++Idx;
3150 
3151   // Scan over all recurrences, trying to fold loop invariants into them.
3152   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3153     // Scan all of the other operands to this mul and add them to the vector
3154     // if they are loop invariant w.r.t. the recurrence.
3155     SmallVector<const SCEV *, 8> LIOps;
3156     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3157     const Loop *AddRecLoop = AddRec->getLoop();
3158     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3159       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3160         LIOps.push_back(Ops[i]);
3161         Ops.erase(Ops.begin()+i);
3162         --i; --e;
3163       }
3164 
3165     // If we found some loop invariants, fold them into the recurrence.
3166     if (!LIOps.empty()) {
3167       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3168       SmallVector<const SCEV *, 4> NewOps;
3169       NewOps.reserve(AddRec->getNumOperands());
3170       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3171       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3172         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3173                                     SCEV::FlagAnyWrap, Depth + 1));
3174 
3175       // Build the new addrec. Propagate the NUW and NSW flags if both the
3176       // outer mul and the inner addrec are guaranteed to have no overflow.
3177       //
3178       // No self-wrap cannot be guaranteed after changing the step size, but
3179       // will be inferred if either NUW or NSW is true.
3180       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3181       const SCEV *NewRec = getAddRecExpr(
3182           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3183 
3184       // If all of the other operands were loop invariant, we are done.
3185       if (Ops.size() == 1) return NewRec;
3186 
3187       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3188       for (unsigned i = 0;; ++i)
3189         if (Ops[i] == AddRec) {
3190           Ops[i] = NewRec;
3191           break;
3192         }
3193       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3194     }
3195 
3196     // Okay, if there weren't any loop invariants to be folded, check to see
3197     // if there are multiple AddRec's with the same loop induction variable
3198     // being multiplied together.  If so, we can fold them.
3199 
3200     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3201     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3202     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3203     //   ]]],+,...up to x=2n}.
3204     // Note that the arguments to choose() are always integers with values
3205     // known at compile time, never SCEV objects.
3206     //
3207     // The implementation avoids pointless extra computations when the two
3208     // addrec's are of different length (mathematically, it's equivalent to
3209     // an infinite stream of zeros on the right).
3210     bool OpsModified = false;
3211     for (unsigned OtherIdx = Idx+1;
3212          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3213          ++OtherIdx) {
3214       const SCEVAddRecExpr *OtherAddRec =
3215         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3216       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3217         continue;
3218 
3219       // Limit max number of arguments to avoid creation of unreasonably big
3220       // SCEVAddRecs with very complex operands.
3221       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3222           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3223         continue;
3224 
3225       bool Overflow = false;
3226       Type *Ty = AddRec->getType();
3227       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3228       SmallVector<const SCEV*, 7> AddRecOps;
3229       for (int x = 0, xe = AddRec->getNumOperands() +
3230              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3231         SmallVector <const SCEV *, 7> SumOps;
3232         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3233           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3234           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3235                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3236                z < ze && !Overflow; ++z) {
3237             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3238             uint64_t Coeff;
3239             if (LargerThan64Bits)
3240               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3241             else
3242               Coeff = Coeff1*Coeff2;
3243             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3244             const SCEV *Term1 = AddRec->getOperand(y-z);
3245             const SCEV *Term2 = OtherAddRec->getOperand(z);
3246             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3247                                         SCEV::FlagAnyWrap, Depth + 1));
3248           }
3249         }
3250         if (SumOps.empty())
3251           SumOps.push_back(getZero(Ty));
3252         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3253       }
3254       if (!Overflow) {
3255         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3256                                               SCEV::FlagAnyWrap);
3257         if (Ops.size() == 2) return NewAddRec;
3258         Ops[Idx] = NewAddRec;
3259         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3260         OpsModified = true;
3261         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3262         if (!AddRec)
3263           break;
3264       }
3265     }
3266     if (OpsModified)
3267       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3268 
3269     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3270     // next one.
3271   }
3272 
3273   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3274   // already have one, otherwise create a new one.
3275   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3276 }
3277 
3278 /// Represents an unsigned remainder expression based on unsigned division.
3279 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3280                                          const SCEV *RHS) {
3281   assert(getEffectiveSCEVType(LHS->getType()) ==
3282          getEffectiveSCEVType(RHS->getType()) &&
3283          "SCEVURemExpr operand types don't match!");
3284 
3285   // Short-circuit easy cases
3286   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3287     // If constant is one, the result is trivial
3288     if (RHSC->getValue()->isOne())
3289       return getZero(LHS->getType()); // X urem 1 --> 0
3290 
3291     // If constant is a power of two, fold into a zext(trunc(LHS)).
3292     if (RHSC->getAPInt().isPowerOf2()) {
3293       Type *FullTy = LHS->getType();
3294       Type *TruncTy =
3295           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3296       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3297     }
3298   }
3299 
3300   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3301   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3302   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3303   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3304 }
3305 
3306 /// Get a canonical unsigned division expression, or something simpler if
3307 /// possible.
3308 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3309                                          const SCEV *RHS) {
3310   assert(!LHS->getType()->isPointerTy() &&
3311          "SCEVUDivExpr operand can't be pointer!");
3312   assert(LHS->getType() == RHS->getType() &&
3313          "SCEVUDivExpr operand types don't match!");
3314 
3315   FoldingSetNodeID ID;
3316   ID.AddInteger(scUDivExpr);
3317   ID.AddPointer(LHS);
3318   ID.AddPointer(RHS);
3319   void *IP = nullptr;
3320   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3321     return S;
3322 
3323   // 0 udiv Y == 0
3324   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3325     if (LHSC->getValue()->isZero())
3326       return LHS;
3327 
3328   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3329     if (RHSC->getValue()->isOne())
3330       return LHS;                               // X udiv 1 --> x
3331     // If the denominator is zero, the result of the udiv is undefined. Don't
3332     // try to analyze it, because the resolution chosen here may differ from
3333     // the resolution chosen in other parts of the compiler.
3334     if (!RHSC->getValue()->isZero()) {
3335       // Determine if the division can be folded into the operands of
3336       // its operands.
3337       // TODO: Generalize this to non-constants by using known-bits information.
3338       Type *Ty = LHS->getType();
3339       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3340       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3341       // For non-power-of-two values, effectively round the value up to the
3342       // nearest power of two.
3343       if (!RHSC->getAPInt().isPowerOf2())
3344         ++MaxShiftAmt;
3345       IntegerType *ExtTy =
3346         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3347       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3348         if (const SCEVConstant *Step =
3349             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3350           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3351           const APInt &StepInt = Step->getAPInt();
3352           const APInt &DivInt = RHSC->getAPInt();
3353           if (!StepInt.urem(DivInt) &&
3354               getZeroExtendExpr(AR, ExtTy) ==
3355               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3356                             getZeroExtendExpr(Step, ExtTy),
3357                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3358             SmallVector<const SCEV *, 4> Operands;
3359             for (const SCEV *Op : AR->operands())
3360               Operands.push_back(getUDivExpr(Op, RHS));
3361             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3362           }
3363           /// Get a canonical UDivExpr for a recurrence.
3364           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3365           // We can currently only fold X%N if X is constant.
3366           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3367           if (StartC && !DivInt.urem(StepInt) &&
3368               getZeroExtendExpr(AR, ExtTy) ==
3369               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3370                             getZeroExtendExpr(Step, ExtTy),
3371                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3372             const APInt &StartInt = StartC->getAPInt();
3373             const APInt &StartRem = StartInt.urem(StepInt);
3374             if (StartRem != 0) {
3375               const SCEV *NewLHS =
3376                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3377                                 AR->getLoop(), SCEV::FlagNW);
3378               if (LHS != NewLHS) {
3379                 LHS = NewLHS;
3380 
3381                 // Reset the ID to include the new LHS, and check if it is
3382                 // already cached.
3383                 ID.clear();
3384                 ID.AddInteger(scUDivExpr);
3385                 ID.AddPointer(LHS);
3386                 ID.AddPointer(RHS);
3387                 IP = nullptr;
3388                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3389                   return S;
3390               }
3391             }
3392           }
3393         }
3394       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3395       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3396         SmallVector<const SCEV *, 4> Operands;
3397         for (const SCEV *Op : M->operands())
3398           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3399         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3400           // Find an operand that's safely divisible.
3401           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3402             const SCEV *Op = M->getOperand(i);
3403             const SCEV *Div = getUDivExpr(Op, RHSC);
3404             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3405               Operands = SmallVector<const SCEV *, 4>(M->operands());
3406               Operands[i] = Div;
3407               return getMulExpr(Operands);
3408             }
3409           }
3410       }
3411 
3412       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3413       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3414         if (auto *DivisorConstant =
3415                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3416           bool Overflow = false;
3417           APInt NewRHS =
3418               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3419           if (Overflow) {
3420             return getConstant(RHSC->getType(), 0, false);
3421           }
3422           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3423         }
3424       }
3425 
3426       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3427       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3428         SmallVector<const SCEV *, 4> Operands;
3429         for (const SCEV *Op : A->operands())
3430           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3431         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3432           Operands.clear();
3433           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3434             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3435             if (isa<SCEVUDivExpr>(Op) ||
3436                 getMulExpr(Op, RHS) != A->getOperand(i))
3437               break;
3438             Operands.push_back(Op);
3439           }
3440           if (Operands.size() == A->getNumOperands())
3441             return getAddExpr(Operands);
3442         }
3443       }
3444 
3445       // Fold if both operands are constant.
3446       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3447         Constant *LHSCV = LHSC->getValue();
3448         Constant *RHSCV = RHSC->getValue();
3449         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3450                                                                    RHSCV)));
3451       }
3452     }
3453   }
3454 
3455   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3456   // changes). Make sure we get a new one.
3457   IP = nullptr;
3458   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3459   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3460                                              LHS, RHS);
3461   UniqueSCEVs.InsertNode(S, IP);
3462   registerUser(S, {LHS, RHS});
3463   return S;
3464 }
3465 
3466 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3467   APInt A = C1->getAPInt().abs();
3468   APInt B = C2->getAPInt().abs();
3469   uint32_t ABW = A.getBitWidth();
3470   uint32_t BBW = B.getBitWidth();
3471 
3472   if (ABW > BBW)
3473     B = B.zext(ABW);
3474   else if (ABW < BBW)
3475     A = A.zext(BBW);
3476 
3477   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3478 }
3479 
3480 /// Get a canonical unsigned division expression, or something simpler if
3481 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3482 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3483 /// it's not exact because the udiv may be clearing bits.
3484 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3485                                               const SCEV *RHS) {
3486   // TODO: we could try to find factors in all sorts of things, but for now we
3487   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3488   // end of this file for inspiration.
3489 
3490   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3491   if (!Mul || !Mul->hasNoUnsignedWrap())
3492     return getUDivExpr(LHS, RHS);
3493 
3494   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3495     // If the mulexpr multiplies by a constant, then that constant must be the
3496     // first element of the mulexpr.
3497     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3498       if (LHSCst == RHSCst) {
3499         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3500         return getMulExpr(Operands);
3501       }
3502 
3503       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3504       // that there's a factor provided by one of the other terms. We need to
3505       // check.
3506       APInt Factor = gcd(LHSCst, RHSCst);
3507       if (!Factor.isIntN(1)) {
3508         LHSCst =
3509             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3510         RHSCst =
3511             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3512         SmallVector<const SCEV *, 2> Operands;
3513         Operands.push_back(LHSCst);
3514         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3515         LHS = getMulExpr(Operands);
3516         RHS = RHSCst;
3517         Mul = dyn_cast<SCEVMulExpr>(LHS);
3518         if (!Mul)
3519           return getUDivExactExpr(LHS, RHS);
3520       }
3521     }
3522   }
3523 
3524   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3525     if (Mul->getOperand(i) == RHS) {
3526       SmallVector<const SCEV *, 2> Operands;
3527       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3528       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3529       return getMulExpr(Operands);
3530     }
3531   }
3532 
3533   return getUDivExpr(LHS, RHS);
3534 }
3535 
3536 /// Get an add recurrence expression for the specified loop.  Simplify the
3537 /// expression as much as possible.
3538 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3539                                            const Loop *L,
3540                                            SCEV::NoWrapFlags Flags) {
3541   SmallVector<const SCEV *, 4> Operands;
3542   Operands.push_back(Start);
3543   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3544     if (StepChrec->getLoop() == L) {
3545       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3546       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3547     }
3548 
3549   Operands.push_back(Step);
3550   return getAddRecExpr(Operands, L, Flags);
3551 }
3552 
3553 /// Get an add recurrence expression for the specified loop.  Simplify the
3554 /// expression as much as possible.
3555 const SCEV *
3556 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3557                                const Loop *L, SCEV::NoWrapFlags Flags) {
3558   if (Operands.size() == 1) return Operands[0];
3559 #ifndef NDEBUG
3560   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3561   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3562     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3563            "SCEVAddRecExpr operand types don't match!");
3564     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3565   }
3566   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3567     assert(isLoopInvariant(Operands[i], L) &&
3568            "SCEVAddRecExpr operand is not loop-invariant!");
3569 #endif
3570 
3571   if (Operands.back()->isZero()) {
3572     Operands.pop_back();
3573     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3574   }
3575 
3576   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3577   // use that information to infer NUW and NSW flags. However, computing a
3578   // BE count requires calling getAddRecExpr, so we may not yet have a
3579   // meaningful BE count at this point (and if we don't, we'd be stuck
3580   // with a SCEVCouldNotCompute as the cached BE count).
3581 
3582   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3583 
3584   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3585   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3586     const Loop *NestedLoop = NestedAR->getLoop();
3587     if (L->contains(NestedLoop)
3588             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3589             : (!NestedLoop->contains(L) &&
3590                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3591       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3592       Operands[0] = NestedAR->getStart();
3593       // AddRecs require their operands be loop-invariant with respect to their
3594       // loops. Don't perform this transformation if it would break this
3595       // requirement.
3596       bool AllInvariant = all_of(
3597           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3598 
3599       if (AllInvariant) {
3600         // Create a recurrence for the outer loop with the same step size.
3601         //
3602         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3603         // inner recurrence has the same property.
3604         SCEV::NoWrapFlags OuterFlags =
3605           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3606 
3607         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3608         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3609           return isLoopInvariant(Op, NestedLoop);
3610         });
3611 
3612         if (AllInvariant) {
3613           // Ok, both add recurrences are valid after the transformation.
3614           //
3615           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3616           // the outer recurrence has the same property.
3617           SCEV::NoWrapFlags InnerFlags =
3618             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3619           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3620         }
3621       }
3622       // Reset Operands to its original state.
3623       Operands[0] = NestedAR;
3624     }
3625   }
3626 
3627   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3628   // already have one, otherwise create a new one.
3629   return getOrCreateAddRecExpr(Operands, L, Flags);
3630 }
3631 
3632 const SCEV *
3633 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3634                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3635   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3636   // getSCEV(Base)->getType() has the same address space as Base->getType()
3637   // because SCEV::getType() preserves the address space.
3638   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3639   const bool AssumeInBoundsFlags = [&]() {
3640     if (!GEP->isInBounds())
3641       return false;
3642 
3643     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3644     // but to do that, we have to ensure that said flag is valid in the entire
3645     // defined scope of the SCEV.
3646     auto *GEPI = dyn_cast<Instruction>(GEP);
3647     // TODO: non-instructions have global scope.  We might be able to prove
3648     // some global scope cases
3649     return GEPI && isSCEVExprNeverPoison(GEPI);
3650   }();
3651 
3652   SCEV::NoWrapFlags OffsetWrap =
3653     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3654 
3655   Type *CurTy = GEP->getType();
3656   bool FirstIter = true;
3657   SmallVector<const SCEV *, 4> Offsets;
3658   for (const SCEV *IndexExpr : IndexExprs) {
3659     // Compute the (potentially symbolic) offset in bytes for this index.
3660     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3661       // For a struct, add the member offset.
3662       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3663       unsigned FieldNo = Index->getZExtValue();
3664       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3665       Offsets.push_back(FieldOffset);
3666 
3667       // Update CurTy to the type of the field at Index.
3668       CurTy = STy->getTypeAtIndex(Index);
3669     } else {
3670       // Update CurTy to its element type.
3671       if (FirstIter) {
3672         assert(isa<PointerType>(CurTy) &&
3673                "The first index of a GEP indexes a pointer");
3674         CurTy = GEP->getSourceElementType();
3675         FirstIter = false;
3676       } else {
3677         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3678       }
3679       // For an array, add the element offset, explicitly scaled.
3680       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3681       // Getelementptr indices are signed.
3682       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3683 
3684       // Multiply the index by the element size to compute the element offset.
3685       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3686       Offsets.push_back(LocalOffset);
3687     }
3688   }
3689 
3690   // Handle degenerate case of GEP without offsets.
3691   if (Offsets.empty())
3692     return BaseExpr;
3693 
3694   // Add the offsets together, assuming nsw if inbounds.
3695   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3696   // Add the base address and the offset. We cannot use the nsw flag, as the
3697   // base address is unsigned. However, if we know that the offset is
3698   // non-negative, we can use nuw.
3699   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3700                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3701   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3702   assert(BaseExpr->getType() == GEPExpr->getType() &&
3703          "GEP should not change type mid-flight.");
3704   return GEPExpr;
3705 }
3706 
3707 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3708                                                ArrayRef<const SCEV *> Ops) {
3709   FoldingSetNodeID ID;
3710   ID.AddInteger(SCEVType);
3711   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3712     ID.AddPointer(Ops[i]);
3713   void *IP = nullptr;
3714   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3715 }
3716 
3717 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3718   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3719   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3720 }
3721 
3722 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3723                                            SmallVectorImpl<const SCEV *> &Ops) {
3724   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3725   if (Ops.size() == 1) return Ops[0];
3726 #ifndef NDEBUG
3727   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3728   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3729     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3730            "Operand types don't match!");
3731     assert(Ops[0]->getType()->isPointerTy() ==
3732                Ops[i]->getType()->isPointerTy() &&
3733            "min/max should be consistently pointerish");
3734   }
3735 #endif
3736 
3737   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3738   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3739 
3740   // Sort by complexity, this groups all similar expression types together.
3741   GroupByComplexity(Ops, &LI, DT);
3742 
3743   // Check if we have created the same expression before.
3744   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3745     return S;
3746   }
3747 
3748   // If there are any constants, fold them together.
3749   unsigned Idx = 0;
3750   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3751     ++Idx;
3752     assert(Idx < Ops.size());
3753     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3754       if (Kind == scSMaxExpr)
3755         return APIntOps::smax(LHS, RHS);
3756       else if (Kind == scSMinExpr)
3757         return APIntOps::smin(LHS, RHS);
3758       else if (Kind == scUMaxExpr)
3759         return APIntOps::umax(LHS, RHS);
3760       else if (Kind == scUMinExpr)
3761         return APIntOps::umin(LHS, RHS);
3762       llvm_unreachable("Unknown SCEV min/max opcode");
3763     };
3764 
3765     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3766       // We found two constants, fold them together!
3767       ConstantInt *Fold = ConstantInt::get(
3768           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3769       Ops[0] = getConstant(Fold);
3770       Ops.erase(Ops.begin()+1);  // Erase the folded element
3771       if (Ops.size() == 1) return Ops[0];
3772       LHSC = cast<SCEVConstant>(Ops[0]);
3773     }
3774 
3775     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3776     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3777 
3778     if (IsMax ? IsMinV : IsMaxV) {
3779       // If we are left with a constant minimum(/maximum)-int, strip it off.
3780       Ops.erase(Ops.begin());
3781       --Idx;
3782     } else if (IsMax ? IsMaxV : IsMinV) {
3783       // If we have a max(/min) with a constant maximum(/minimum)-int,
3784       // it will always be the extremum.
3785       return LHSC;
3786     }
3787 
3788     if (Ops.size() == 1) return Ops[0];
3789   }
3790 
3791   // Find the first operation of the same kind
3792   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3793     ++Idx;
3794 
3795   // Check to see if one of the operands is of the same kind. If so, expand its
3796   // operands onto our operand list, and recurse to simplify.
3797   if (Idx < Ops.size()) {
3798     bool DeletedAny = false;
3799     while (Ops[Idx]->getSCEVType() == Kind) {
3800       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3801       Ops.erase(Ops.begin()+Idx);
3802       Ops.append(SMME->op_begin(), SMME->op_end());
3803       DeletedAny = true;
3804     }
3805 
3806     if (DeletedAny)
3807       return getMinMaxExpr(Kind, Ops);
3808   }
3809 
3810   // Okay, check to see if the same value occurs in the operand list twice.  If
3811   // so, delete one.  Since we sorted the list, these values are required to
3812   // be adjacent.
3813   llvm::CmpInst::Predicate GEPred =
3814       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3815   llvm::CmpInst::Predicate LEPred =
3816       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3817   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3818   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3819   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3820     if (Ops[i] == Ops[i + 1] ||
3821         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3822       //  X op Y op Y  -->  X op Y
3823       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3824       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3825       --i;
3826       --e;
3827     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3828                                                Ops[i + 1])) {
3829       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3830       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3831       --i;
3832       --e;
3833     }
3834   }
3835 
3836   if (Ops.size() == 1) return Ops[0];
3837 
3838   assert(!Ops.empty() && "Reduced smax down to nothing!");
3839 
3840   // Okay, it looks like we really DO need an expr.  Check to see if we
3841   // already have one, otherwise create a new one.
3842   FoldingSetNodeID ID;
3843   ID.AddInteger(Kind);
3844   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3845     ID.AddPointer(Ops[i]);
3846   void *IP = nullptr;
3847   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3848   if (ExistingSCEV)
3849     return ExistingSCEV;
3850   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3851   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3852   SCEV *S = new (SCEVAllocator)
3853       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3854 
3855   UniqueSCEVs.InsertNode(S, IP);
3856   registerUser(S, Ops);
3857   return S;
3858 }
3859 
3860 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3861   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3862   return getSMaxExpr(Ops);
3863 }
3864 
3865 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3866   return getMinMaxExpr(scSMaxExpr, Ops);
3867 }
3868 
3869 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3870   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3871   return getUMaxExpr(Ops);
3872 }
3873 
3874 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3875   return getMinMaxExpr(scUMaxExpr, Ops);
3876 }
3877 
3878 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3879                                          const SCEV *RHS) {
3880   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3881   return getSMinExpr(Ops);
3882 }
3883 
3884 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3885   return getMinMaxExpr(scSMinExpr, Ops);
3886 }
3887 
3888 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3889                                          const SCEV *RHS) {
3890   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3891   return getUMinExpr(Ops);
3892 }
3893 
3894 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3895   return getMinMaxExpr(scUMinExpr, Ops);
3896 }
3897 
3898 const SCEV *
3899 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3900                                              ScalableVectorType *ScalableTy) {
3901   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3902   Constant *One = ConstantInt::get(IntTy, 1);
3903   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3904   // Note that the expression we created is the final expression, we don't
3905   // want to simplify it any further Also, if we call a normal getSCEV(),
3906   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3907   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3908 }
3909 
3910 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3911   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3912     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3913   // We can bypass creating a target-independent constant expression and then
3914   // folding it back into a ConstantInt. This is just a compile-time
3915   // optimization.
3916   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3917 }
3918 
3919 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3920   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3921     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3922   // We can bypass creating a target-independent constant expression and then
3923   // folding it back into a ConstantInt. This is just a compile-time
3924   // optimization.
3925   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3926 }
3927 
3928 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3929                                              StructType *STy,
3930                                              unsigned FieldNo) {
3931   // We can bypass creating a target-independent constant expression and then
3932   // folding it back into a ConstantInt. This is just a compile-time
3933   // optimization.
3934   return getConstant(
3935       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3936 }
3937 
3938 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3939   // Don't attempt to do anything other than create a SCEVUnknown object
3940   // here.  createSCEV only calls getUnknown after checking for all other
3941   // interesting possibilities, and any other code that calls getUnknown
3942   // is doing so in order to hide a value from SCEV canonicalization.
3943 
3944   FoldingSetNodeID ID;
3945   ID.AddInteger(scUnknown);
3946   ID.AddPointer(V);
3947   void *IP = nullptr;
3948   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3949     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3950            "Stale SCEVUnknown in uniquing map!");
3951     return S;
3952   }
3953   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3954                                             FirstUnknown);
3955   FirstUnknown = cast<SCEVUnknown>(S);
3956   UniqueSCEVs.InsertNode(S, IP);
3957   return S;
3958 }
3959 
3960 //===----------------------------------------------------------------------===//
3961 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3962 //
3963 
3964 /// Test if values of the given type are analyzable within the SCEV
3965 /// framework. This primarily includes integer types, and it can optionally
3966 /// include pointer types if the ScalarEvolution class has access to
3967 /// target-specific information.
3968 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3969   // Integers and pointers are always SCEVable.
3970   return Ty->isIntOrPtrTy();
3971 }
3972 
3973 /// Return the size in bits of the specified type, for which isSCEVable must
3974 /// return true.
3975 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3976   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3977   if (Ty->isPointerTy())
3978     return getDataLayout().getIndexTypeSizeInBits(Ty);
3979   return getDataLayout().getTypeSizeInBits(Ty);
3980 }
3981 
3982 /// Return a type with the same bitwidth as the given type and which represents
3983 /// how SCEV will treat the given type, for which isSCEVable must return
3984 /// true. For pointer types, this is the pointer index sized integer type.
3985 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3986   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3987 
3988   if (Ty->isIntegerTy())
3989     return Ty;
3990 
3991   // The only other support type is pointer.
3992   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3993   return getDataLayout().getIndexType(Ty);
3994 }
3995 
3996 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3997   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3998 }
3999 
4000 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4001                                                          const SCEV *B) {
4002   /// For a valid use point to exist, the defining scope of one operand
4003   /// must dominate the other.
4004   bool PreciseA, PreciseB;
4005   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4006   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4007   if (!PreciseA || !PreciseB)
4008     // Can't tell.
4009     return false;
4010   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4011     DT.dominates(ScopeB, ScopeA);
4012 }
4013 
4014 
4015 const SCEV *ScalarEvolution::getCouldNotCompute() {
4016   return CouldNotCompute.get();
4017 }
4018 
4019 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4020   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4021     auto *SU = dyn_cast<SCEVUnknown>(S);
4022     return SU && SU->getValue() == nullptr;
4023   });
4024 
4025   return !ContainsNulls;
4026 }
4027 
4028 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4029   HasRecMapType::iterator I = HasRecMap.find(S);
4030   if (I != HasRecMap.end())
4031     return I->second;
4032 
4033   bool FoundAddRec =
4034       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4035   HasRecMap.insert({S, FoundAddRec});
4036   return FoundAddRec;
4037 }
4038 
4039 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
4040 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
4041 /// offset I, then return {S', I}, else return {\p S, nullptr}.
4042 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
4043   const auto *Add = dyn_cast<SCEVAddExpr>(S);
4044   if (!Add)
4045     return {S, nullptr};
4046 
4047   if (Add->getNumOperands() != 2)
4048     return {S, nullptr};
4049 
4050   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
4051   if (!ConstOp)
4052     return {S, nullptr};
4053 
4054   return {Add->getOperand(1), ConstOp->getValue()};
4055 }
4056 
4057 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4058 /// by the value and offset from any ValueOffsetPair in the set.
4059 ScalarEvolution::ValueOffsetPairSetVector *
4060 ScalarEvolution::getSCEVValues(const SCEV *S) {
4061   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4062   if (SI == ExprValueMap.end())
4063     return nullptr;
4064 #ifndef NDEBUG
4065   if (VerifySCEVMap) {
4066     // Check there is no dangling Value in the set returned.
4067     for (const auto &VE : SI->second)
4068       assert(ValueExprMap.count(VE.first));
4069   }
4070 #endif
4071   return &SI->second;
4072 }
4073 
4074 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4075 /// cannot be used separately. eraseValueFromMap should be used to remove
4076 /// V from ValueExprMap and ExprValueMap at the same time.
4077 void ScalarEvolution::eraseValueFromMap(Value *V) {
4078   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4079   if (I != ValueExprMap.end()) {
4080     const SCEV *S = I->second;
4081     // Remove {V, 0} from the set of ExprValueMap[S]
4082     if (auto *SV = getSCEVValues(S))
4083       SV->remove({V, nullptr});
4084 
4085     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
4086     const SCEV *Stripped;
4087     ConstantInt *Offset;
4088     std::tie(Stripped, Offset) = splitAddExpr(S);
4089     if (Offset != nullptr) {
4090       if (auto *SV = getSCEVValues(Stripped))
4091         SV->remove({V, Offset});
4092     }
4093     ValueExprMap.erase(V);
4094   }
4095 }
4096 
4097 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4098 /// create a new one.
4099 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4100   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4101 
4102   const SCEV *S = getExistingSCEV(V);
4103   if (S == nullptr) {
4104     S = createSCEV(V);
4105     // During PHI resolution, it is possible to create two SCEVs for the same
4106     // V, so it is needed to double check whether V->S is inserted into
4107     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4108     std::pair<ValueExprMapType::iterator, bool> Pair =
4109         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4110     if (Pair.second) {
4111       ExprValueMap[S].insert({V, nullptr});
4112 
4113       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
4114       // ExprValueMap.
4115       const SCEV *Stripped = S;
4116       ConstantInt *Offset = nullptr;
4117       std::tie(Stripped, Offset) = splitAddExpr(S);
4118       // If stripped is SCEVUnknown, don't bother to save
4119       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
4120       // increase the complexity of the expansion code.
4121       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
4122       // because it may generate add/sub instead of GEP in SCEV expansion.
4123       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
4124           !isa<GetElementPtrInst>(V))
4125         ExprValueMap[Stripped].insert({V, Offset});
4126     }
4127   }
4128   return S;
4129 }
4130 
4131 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4132   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4133 
4134   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4135   if (I != ValueExprMap.end()) {
4136     const SCEV *S = I->second;
4137     if (checkValidity(S))
4138       return S;
4139     eraseValueFromMap(V);
4140     forgetMemoizedResults(S);
4141   }
4142   return nullptr;
4143 }
4144 
4145 /// Return a SCEV corresponding to -V = -1*V
4146 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4147                                              SCEV::NoWrapFlags Flags) {
4148   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4149     return getConstant(
4150                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4151 
4152   Type *Ty = V->getType();
4153   Ty = getEffectiveSCEVType(Ty);
4154   return getMulExpr(V, getMinusOne(Ty), Flags);
4155 }
4156 
4157 /// If Expr computes ~A, return A else return nullptr
4158 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4159   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4160   if (!Add || Add->getNumOperands() != 2 ||
4161       !Add->getOperand(0)->isAllOnesValue())
4162     return nullptr;
4163 
4164   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4165   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4166       !AddRHS->getOperand(0)->isAllOnesValue())
4167     return nullptr;
4168 
4169   return AddRHS->getOperand(1);
4170 }
4171 
4172 /// Return a SCEV corresponding to ~V = -1-V
4173 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4174   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4175 
4176   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4177     return getConstant(
4178                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4179 
4180   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4181   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4182     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4183       SmallVector<const SCEV *, 2> MatchedOperands;
4184       for (const SCEV *Operand : MME->operands()) {
4185         const SCEV *Matched = MatchNotExpr(Operand);
4186         if (!Matched)
4187           return (const SCEV *)nullptr;
4188         MatchedOperands.push_back(Matched);
4189       }
4190       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4191                            MatchedOperands);
4192     };
4193     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4194       return Replaced;
4195   }
4196 
4197   Type *Ty = V->getType();
4198   Ty = getEffectiveSCEVType(Ty);
4199   return getMinusSCEV(getMinusOne(Ty), V);
4200 }
4201 
4202 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4203   assert(P->getType()->isPointerTy());
4204 
4205   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4206     // The base of an AddRec is the first operand.
4207     SmallVector<const SCEV *> Ops{AddRec->operands()};
4208     Ops[0] = removePointerBase(Ops[0]);
4209     // Don't try to transfer nowrap flags for now. We could in some cases
4210     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4211     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4212   }
4213   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4214     // The base of an Add is the pointer operand.
4215     SmallVector<const SCEV *> Ops{Add->operands()};
4216     const SCEV **PtrOp = nullptr;
4217     for (const SCEV *&AddOp : Ops) {
4218       if (AddOp->getType()->isPointerTy()) {
4219         assert(!PtrOp && "Cannot have multiple pointer ops");
4220         PtrOp = &AddOp;
4221       }
4222     }
4223     *PtrOp = removePointerBase(*PtrOp);
4224     // Don't try to transfer nowrap flags for now. We could in some cases
4225     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4226     return getAddExpr(Ops);
4227   }
4228   // Any other expression must be a pointer base.
4229   return getZero(P->getType());
4230 }
4231 
4232 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4233                                           SCEV::NoWrapFlags Flags,
4234                                           unsigned Depth) {
4235   // Fast path: X - X --> 0.
4236   if (LHS == RHS)
4237     return getZero(LHS->getType());
4238 
4239   // If we subtract two pointers with different pointer bases, bail.
4240   // Eventually, we're going to add an assertion to getMulExpr that we
4241   // can't multiply by a pointer.
4242   if (RHS->getType()->isPointerTy()) {
4243     if (!LHS->getType()->isPointerTy() ||
4244         getPointerBase(LHS) != getPointerBase(RHS))
4245       return getCouldNotCompute();
4246     LHS = removePointerBase(LHS);
4247     RHS = removePointerBase(RHS);
4248   }
4249 
4250   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4251   // makes it so that we cannot make much use of NUW.
4252   auto AddFlags = SCEV::FlagAnyWrap;
4253   const bool RHSIsNotMinSigned =
4254       !getSignedRangeMin(RHS).isMinSignedValue();
4255   if (hasFlags(Flags, SCEV::FlagNSW)) {
4256     // Let M be the minimum representable signed value. Then (-1)*RHS
4257     // signed-wraps if and only if RHS is M. That can happen even for
4258     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4259     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4260     // (-1)*RHS, we need to prove that RHS != M.
4261     //
4262     // If LHS is non-negative and we know that LHS - RHS does not
4263     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4264     // either by proving that RHS > M or that LHS >= 0.
4265     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4266       AddFlags = SCEV::FlagNSW;
4267     }
4268   }
4269 
4270   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4271   // RHS is NSW and LHS >= 0.
4272   //
4273   // The difficulty here is that the NSW flag may have been proven
4274   // relative to a loop that is to be found in a recurrence in LHS and
4275   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4276   // larger scope than intended.
4277   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4278 
4279   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4280 }
4281 
4282 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4283                                                      unsigned Depth) {
4284   Type *SrcTy = V->getType();
4285   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4286          "Cannot truncate or zero extend with non-integer arguments!");
4287   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4288     return V;  // No conversion
4289   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4290     return getTruncateExpr(V, Ty, Depth);
4291   return getZeroExtendExpr(V, Ty, Depth);
4292 }
4293 
4294 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4295                                                      unsigned Depth) {
4296   Type *SrcTy = V->getType();
4297   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4298          "Cannot truncate or zero extend with non-integer arguments!");
4299   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4300     return V;  // No conversion
4301   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4302     return getTruncateExpr(V, Ty, Depth);
4303   return getSignExtendExpr(V, Ty, Depth);
4304 }
4305 
4306 const SCEV *
4307 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4308   Type *SrcTy = V->getType();
4309   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4310          "Cannot noop or zero extend with non-integer arguments!");
4311   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4312          "getNoopOrZeroExtend cannot truncate!");
4313   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4314     return V;  // No conversion
4315   return getZeroExtendExpr(V, Ty);
4316 }
4317 
4318 const SCEV *
4319 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4320   Type *SrcTy = V->getType();
4321   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4322          "Cannot noop or sign extend with non-integer arguments!");
4323   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4324          "getNoopOrSignExtend cannot truncate!");
4325   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4326     return V;  // No conversion
4327   return getSignExtendExpr(V, Ty);
4328 }
4329 
4330 const SCEV *
4331 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4332   Type *SrcTy = V->getType();
4333   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4334          "Cannot noop or any extend with non-integer arguments!");
4335   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4336          "getNoopOrAnyExtend cannot truncate!");
4337   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4338     return V;  // No conversion
4339   return getAnyExtendExpr(V, Ty);
4340 }
4341 
4342 const SCEV *
4343 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4344   Type *SrcTy = V->getType();
4345   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4346          "Cannot truncate or noop with non-integer arguments!");
4347   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4348          "getTruncateOrNoop cannot extend!");
4349   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4350     return V;  // No conversion
4351   return getTruncateExpr(V, Ty);
4352 }
4353 
4354 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4355                                                         const SCEV *RHS) {
4356   const SCEV *PromotedLHS = LHS;
4357   const SCEV *PromotedRHS = RHS;
4358 
4359   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4360     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4361   else
4362     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4363 
4364   return getUMaxExpr(PromotedLHS, PromotedRHS);
4365 }
4366 
4367 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4368                                                         const SCEV *RHS) {
4369   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4370   return getUMinFromMismatchedTypes(Ops);
4371 }
4372 
4373 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4374     SmallVectorImpl<const SCEV *> &Ops) {
4375   assert(!Ops.empty() && "At least one operand must be!");
4376   // Trivial case.
4377   if (Ops.size() == 1)
4378     return Ops[0];
4379 
4380   // Find the max type first.
4381   Type *MaxType = nullptr;
4382   for (auto *S : Ops)
4383     if (MaxType)
4384       MaxType = getWiderType(MaxType, S->getType());
4385     else
4386       MaxType = S->getType();
4387   assert(MaxType && "Failed to find maximum type!");
4388 
4389   // Extend all ops to max type.
4390   SmallVector<const SCEV *, 2> PromotedOps;
4391   for (auto *S : Ops)
4392     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4393 
4394   // Generate umin.
4395   return getUMinExpr(PromotedOps);
4396 }
4397 
4398 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4399   // A pointer operand may evaluate to a nonpointer expression, such as null.
4400   if (!V->getType()->isPointerTy())
4401     return V;
4402 
4403   while (true) {
4404     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4405       V = AddRec->getStart();
4406     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4407       const SCEV *PtrOp = nullptr;
4408       for (const SCEV *AddOp : Add->operands()) {
4409         if (AddOp->getType()->isPointerTy()) {
4410           assert(!PtrOp && "Cannot have multiple pointer ops");
4411           PtrOp = AddOp;
4412         }
4413       }
4414       assert(PtrOp && "Must have pointer op");
4415       V = PtrOp;
4416     } else // Not something we can look further into.
4417       return V;
4418   }
4419 }
4420 
4421 /// Push users of the given Instruction onto the given Worklist.
4422 static void PushDefUseChildren(Instruction *I,
4423                                SmallVectorImpl<Instruction *> &Worklist,
4424                                SmallPtrSetImpl<Instruction *> &Visited) {
4425   // Push the def-use children onto the Worklist stack.
4426   for (User *U : I->users()) {
4427     auto *UserInsn = cast<Instruction>(U);
4428     if (Visited.insert(UserInsn).second)
4429       Worklist.push_back(UserInsn);
4430   }
4431 }
4432 
4433 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4434   SmallVector<Instruction *, 16> Worklist;
4435   SmallPtrSet<Instruction *, 8> Visited;
4436   SmallVector<const SCEV *, 8> ToForget;
4437   Visited.insert(PN);
4438   Worklist.push_back(PN);
4439   while (!Worklist.empty()) {
4440     Instruction *I = Worklist.pop_back_val();
4441 
4442     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4443     if (It != ValueExprMap.end()) {
4444       const SCEV *Old = It->second;
4445 
4446       // Short-circuit the def-use traversal if the symbolic name
4447       // ceases to appear in expressions.
4448       if (Old != SymName && !hasOperand(Old, SymName))
4449         continue;
4450 
4451       // SCEVUnknown for a PHI either means that it has an unrecognized
4452       // structure, it's a PHI that's in the progress of being computed
4453       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4454       // additional loop trip count information isn't going to change anything.
4455       // In the second case, createNodeForPHI will perform the necessary
4456       // updates on its own when it gets to that point. In the third, we do
4457       // want to forget the SCEVUnknown.
4458       if (!isa<PHINode>(I) ||
4459           !isa<SCEVUnknown>(Old) ||
4460           (I != PN && Old == SymName)) {
4461         eraseValueFromMap(It->first);
4462         ToForget.push_back(Old);
4463       }
4464     }
4465 
4466     PushDefUseChildren(I, Worklist, Visited);
4467   }
4468   forgetMemoizedResults(ToForget);
4469 }
4470 
4471 namespace {
4472 
4473 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4474 /// expression in case its Loop is L. If it is not L then
4475 /// if IgnoreOtherLoops is true then use AddRec itself
4476 /// otherwise rewrite cannot be done.
4477 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4478 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4479 public:
4480   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4481                              bool IgnoreOtherLoops = true) {
4482     SCEVInitRewriter Rewriter(L, SE);
4483     const SCEV *Result = Rewriter.visit(S);
4484     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4485       return SE.getCouldNotCompute();
4486     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4487                ? SE.getCouldNotCompute()
4488                : Result;
4489   }
4490 
4491   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4492     if (!SE.isLoopInvariant(Expr, L))
4493       SeenLoopVariantSCEVUnknown = true;
4494     return Expr;
4495   }
4496 
4497   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4498     // Only re-write AddRecExprs for this loop.
4499     if (Expr->getLoop() == L)
4500       return Expr->getStart();
4501     SeenOtherLoops = true;
4502     return Expr;
4503   }
4504 
4505   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4506 
4507   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4508 
4509 private:
4510   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4511       : SCEVRewriteVisitor(SE), L(L) {}
4512 
4513   const Loop *L;
4514   bool SeenLoopVariantSCEVUnknown = false;
4515   bool SeenOtherLoops = false;
4516 };
4517 
4518 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4519 /// increment expression in case its Loop is L. If it is not L then
4520 /// use AddRec itself.
4521 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4522 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4523 public:
4524   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4525     SCEVPostIncRewriter Rewriter(L, SE);
4526     const SCEV *Result = Rewriter.visit(S);
4527     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4528         ? SE.getCouldNotCompute()
4529         : Result;
4530   }
4531 
4532   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4533     if (!SE.isLoopInvariant(Expr, L))
4534       SeenLoopVariantSCEVUnknown = true;
4535     return Expr;
4536   }
4537 
4538   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4539     // Only re-write AddRecExprs for this loop.
4540     if (Expr->getLoop() == L)
4541       return Expr->getPostIncExpr(SE);
4542     SeenOtherLoops = true;
4543     return Expr;
4544   }
4545 
4546   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4547 
4548   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4549 
4550 private:
4551   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4552       : SCEVRewriteVisitor(SE), L(L) {}
4553 
4554   const Loop *L;
4555   bool SeenLoopVariantSCEVUnknown = false;
4556   bool SeenOtherLoops = false;
4557 };
4558 
4559 /// This class evaluates the compare condition by matching it against the
4560 /// condition of loop latch. If there is a match we assume a true value
4561 /// for the condition while building SCEV nodes.
4562 class SCEVBackedgeConditionFolder
4563     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4564 public:
4565   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4566                              ScalarEvolution &SE) {
4567     bool IsPosBECond = false;
4568     Value *BECond = nullptr;
4569     if (BasicBlock *Latch = L->getLoopLatch()) {
4570       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4571       if (BI && BI->isConditional()) {
4572         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4573                "Both outgoing branches should not target same header!");
4574         BECond = BI->getCondition();
4575         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4576       } else {
4577         return S;
4578       }
4579     }
4580     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4581     return Rewriter.visit(S);
4582   }
4583 
4584   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4585     const SCEV *Result = Expr;
4586     bool InvariantF = SE.isLoopInvariant(Expr, L);
4587 
4588     if (!InvariantF) {
4589       Instruction *I = cast<Instruction>(Expr->getValue());
4590       switch (I->getOpcode()) {
4591       case Instruction::Select: {
4592         SelectInst *SI = cast<SelectInst>(I);
4593         Optional<const SCEV *> Res =
4594             compareWithBackedgeCondition(SI->getCondition());
4595         if (Res.hasValue()) {
4596           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4597           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4598         }
4599         break;
4600       }
4601       default: {
4602         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4603         if (Res.hasValue())
4604           Result = Res.getValue();
4605         break;
4606       }
4607       }
4608     }
4609     return Result;
4610   }
4611 
4612 private:
4613   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4614                                        bool IsPosBECond, ScalarEvolution &SE)
4615       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4616         IsPositiveBECond(IsPosBECond) {}
4617 
4618   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4619 
4620   const Loop *L;
4621   /// Loop back condition.
4622   Value *BackedgeCond = nullptr;
4623   /// Set to true if loop back is on positive branch condition.
4624   bool IsPositiveBECond;
4625 };
4626 
4627 Optional<const SCEV *>
4628 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4629 
4630   // If value matches the backedge condition for loop latch,
4631   // then return a constant evolution node based on loopback
4632   // branch taken.
4633   if (BackedgeCond == IC)
4634     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4635                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4636   return None;
4637 }
4638 
4639 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4640 public:
4641   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4642                              ScalarEvolution &SE) {
4643     SCEVShiftRewriter Rewriter(L, SE);
4644     const SCEV *Result = Rewriter.visit(S);
4645     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4646   }
4647 
4648   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4649     // Only allow AddRecExprs for this loop.
4650     if (!SE.isLoopInvariant(Expr, L))
4651       Valid = false;
4652     return Expr;
4653   }
4654 
4655   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4656     if (Expr->getLoop() == L && Expr->isAffine())
4657       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4658     Valid = false;
4659     return Expr;
4660   }
4661 
4662   bool isValid() { return Valid; }
4663 
4664 private:
4665   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4666       : SCEVRewriteVisitor(SE), L(L) {}
4667 
4668   const Loop *L;
4669   bool Valid = true;
4670 };
4671 
4672 } // end anonymous namespace
4673 
4674 SCEV::NoWrapFlags
4675 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4676   if (!AR->isAffine())
4677     return SCEV::FlagAnyWrap;
4678 
4679   using OBO = OverflowingBinaryOperator;
4680 
4681   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4682 
4683   if (!AR->hasNoSignedWrap()) {
4684     ConstantRange AddRecRange = getSignedRange(AR);
4685     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4686 
4687     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4688         Instruction::Add, IncRange, OBO::NoSignedWrap);
4689     if (NSWRegion.contains(AddRecRange))
4690       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4691   }
4692 
4693   if (!AR->hasNoUnsignedWrap()) {
4694     ConstantRange AddRecRange = getUnsignedRange(AR);
4695     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4696 
4697     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4698         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4699     if (NUWRegion.contains(AddRecRange))
4700       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4701   }
4702 
4703   return Result;
4704 }
4705 
4706 SCEV::NoWrapFlags
4707 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4708   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4709 
4710   if (AR->hasNoSignedWrap())
4711     return Result;
4712 
4713   if (!AR->isAffine())
4714     return Result;
4715 
4716   const SCEV *Step = AR->getStepRecurrence(*this);
4717   const Loop *L = AR->getLoop();
4718 
4719   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4720   // Note that this serves two purposes: It filters out loops that are
4721   // simply not analyzable, and it covers the case where this code is
4722   // being called from within backedge-taken count analysis, such that
4723   // attempting to ask for the backedge-taken count would likely result
4724   // in infinite recursion. In the later case, the analysis code will
4725   // cope with a conservative value, and it will take care to purge
4726   // that value once it has finished.
4727   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4728 
4729   // Normally, in the cases we can prove no-overflow via a
4730   // backedge guarding condition, we can also compute a backedge
4731   // taken count for the loop.  The exceptions are assumptions and
4732   // guards present in the loop -- SCEV is not great at exploiting
4733   // these to compute max backedge taken counts, but can still use
4734   // these to prove lack of overflow.  Use this fact to avoid
4735   // doing extra work that may not pay off.
4736 
4737   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4738       AC.assumptions().empty())
4739     return Result;
4740 
4741   // If the backedge is guarded by a comparison with the pre-inc  value the
4742   // addrec is safe. Also, if the entry is guarded by a comparison with the
4743   // start value and the backedge is guarded by a comparison with the post-inc
4744   // value, the addrec is safe.
4745   ICmpInst::Predicate Pred;
4746   const SCEV *OverflowLimit =
4747     getSignedOverflowLimitForStep(Step, &Pred, this);
4748   if (OverflowLimit &&
4749       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4750        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4751     Result = setFlags(Result, SCEV::FlagNSW);
4752   }
4753   return Result;
4754 }
4755 SCEV::NoWrapFlags
4756 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4757   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4758 
4759   if (AR->hasNoUnsignedWrap())
4760     return Result;
4761 
4762   if (!AR->isAffine())
4763     return Result;
4764 
4765   const SCEV *Step = AR->getStepRecurrence(*this);
4766   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4767   const Loop *L = AR->getLoop();
4768 
4769   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4770   // Note that this serves two purposes: It filters out loops that are
4771   // simply not analyzable, and it covers the case where this code is
4772   // being called from within backedge-taken count analysis, such that
4773   // attempting to ask for the backedge-taken count would likely result
4774   // in infinite recursion. In the later case, the analysis code will
4775   // cope with a conservative value, and it will take care to purge
4776   // that value once it has finished.
4777   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4778 
4779   // Normally, in the cases we can prove no-overflow via a
4780   // backedge guarding condition, we can also compute a backedge
4781   // taken count for the loop.  The exceptions are assumptions and
4782   // guards present in the loop -- SCEV is not great at exploiting
4783   // these to compute max backedge taken counts, but can still use
4784   // these to prove lack of overflow.  Use this fact to avoid
4785   // doing extra work that may not pay off.
4786 
4787   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4788       AC.assumptions().empty())
4789     return Result;
4790 
4791   // If the backedge is guarded by a comparison with the pre-inc  value the
4792   // addrec is safe. Also, if the entry is guarded by a comparison with the
4793   // start value and the backedge is guarded by a comparison with the post-inc
4794   // value, the addrec is safe.
4795   if (isKnownPositive(Step)) {
4796     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4797                                 getUnsignedRangeMax(Step));
4798     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4799         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4800       Result = setFlags(Result, SCEV::FlagNUW);
4801     }
4802   }
4803 
4804   return Result;
4805 }
4806 
4807 namespace {
4808 
4809 /// Represents an abstract binary operation.  This may exist as a
4810 /// normal instruction or constant expression, or may have been
4811 /// derived from an expression tree.
4812 struct BinaryOp {
4813   unsigned Opcode;
4814   Value *LHS;
4815   Value *RHS;
4816   bool IsNSW = false;
4817   bool IsNUW = false;
4818 
4819   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4820   /// constant expression.
4821   Operator *Op = nullptr;
4822 
4823   explicit BinaryOp(Operator *Op)
4824       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4825         Op(Op) {
4826     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4827       IsNSW = OBO->hasNoSignedWrap();
4828       IsNUW = OBO->hasNoUnsignedWrap();
4829     }
4830   }
4831 
4832   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4833                     bool IsNUW = false)
4834       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4835 };
4836 
4837 } // end anonymous namespace
4838 
4839 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4840 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4841   auto *Op = dyn_cast<Operator>(V);
4842   if (!Op)
4843     return None;
4844 
4845   // Implementation detail: all the cleverness here should happen without
4846   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4847   // SCEV expressions when possible, and we should not break that.
4848 
4849   switch (Op->getOpcode()) {
4850   case Instruction::Add:
4851   case Instruction::Sub:
4852   case Instruction::Mul:
4853   case Instruction::UDiv:
4854   case Instruction::URem:
4855   case Instruction::And:
4856   case Instruction::Or:
4857   case Instruction::AShr:
4858   case Instruction::Shl:
4859     return BinaryOp(Op);
4860 
4861   case Instruction::Xor:
4862     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4863       // If the RHS of the xor is a signmask, then this is just an add.
4864       // Instcombine turns add of signmask into xor as a strength reduction step.
4865       if (RHSC->getValue().isSignMask())
4866         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4867     return BinaryOp(Op);
4868 
4869   case Instruction::LShr:
4870     // Turn logical shift right of a constant into a unsigned divide.
4871     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4872       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4873 
4874       // If the shift count is not less than the bitwidth, the result of
4875       // the shift is undefined. Don't try to analyze it, because the
4876       // resolution chosen here may differ from the resolution chosen in
4877       // other parts of the compiler.
4878       if (SA->getValue().ult(BitWidth)) {
4879         Constant *X =
4880             ConstantInt::get(SA->getContext(),
4881                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4882         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4883       }
4884     }
4885     return BinaryOp(Op);
4886 
4887   case Instruction::ExtractValue: {
4888     auto *EVI = cast<ExtractValueInst>(Op);
4889     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4890       break;
4891 
4892     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4893     if (!WO)
4894       break;
4895 
4896     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4897     bool Signed = WO->isSigned();
4898     // TODO: Should add nuw/nsw flags for mul as well.
4899     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4900       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4901 
4902     // Now that we know that all uses of the arithmetic-result component of
4903     // CI are guarded by the overflow check, we can go ahead and pretend
4904     // that the arithmetic is non-overflowing.
4905     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4906                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4907   }
4908 
4909   default:
4910     break;
4911   }
4912 
4913   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4914   // semantics as a Sub, return a binary sub expression.
4915   if (auto *II = dyn_cast<IntrinsicInst>(V))
4916     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4917       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4918 
4919   return None;
4920 }
4921 
4922 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4923 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4924 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4925 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4926 /// follows one of the following patterns:
4927 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4928 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4929 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4930 /// we return the type of the truncation operation, and indicate whether the
4931 /// truncated type should be treated as signed/unsigned by setting
4932 /// \p Signed to true/false, respectively.
4933 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4934                                bool &Signed, ScalarEvolution &SE) {
4935   // The case where Op == SymbolicPHI (that is, with no type conversions on
4936   // the way) is handled by the regular add recurrence creating logic and
4937   // would have already been triggered in createAddRecForPHI. Reaching it here
4938   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4939   // because one of the other operands of the SCEVAddExpr updating this PHI is
4940   // not invariant).
4941   //
4942   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4943   // this case predicates that allow us to prove that Op == SymbolicPHI will
4944   // be added.
4945   if (Op == SymbolicPHI)
4946     return nullptr;
4947 
4948   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4949   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4950   if (SourceBits != NewBits)
4951     return nullptr;
4952 
4953   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4954   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4955   if (!SExt && !ZExt)
4956     return nullptr;
4957   const SCEVTruncateExpr *Trunc =
4958       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4959            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4960   if (!Trunc)
4961     return nullptr;
4962   const SCEV *X = Trunc->getOperand();
4963   if (X != SymbolicPHI)
4964     return nullptr;
4965   Signed = SExt != nullptr;
4966   return Trunc->getType();
4967 }
4968 
4969 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4970   if (!PN->getType()->isIntegerTy())
4971     return nullptr;
4972   const Loop *L = LI.getLoopFor(PN->getParent());
4973   if (!L || L->getHeader() != PN->getParent())
4974     return nullptr;
4975   return L;
4976 }
4977 
4978 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4979 // computation that updates the phi follows the following pattern:
4980 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4981 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4982 // If so, try to see if it can be rewritten as an AddRecExpr under some
4983 // Predicates. If successful, return them as a pair. Also cache the results
4984 // of the analysis.
4985 //
4986 // Example usage scenario:
4987 //    Say the Rewriter is called for the following SCEV:
4988 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4989 //    where:
4990 //         %X = phi i64 (%Start, %BEValue)
4991 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4992 //    and call this function with %SymbolicPHI = %X.
4993 //
4994 //    The analysis will find that the value coming around the backedge has
4995 //    the following SCEV:
4996 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4997 //    Upon concluding that this matches the desired pattern, the function
4998 //    will return the pair {NewAddRec, SmallPredsVec} where:
4999 //         NewAddRec = {%Start,+,%Step}
5000 //         SmallPredsVec = {P1, P2, P3} as follows:
5001 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5002 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5003 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5004 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5005 //    under the predicates {P1,P2,P3}.
5006 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5007 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5008 //
5009 // TODO's:
5010 //
5011 // 1) Extend the Induction descriptor to also support inductions that involve
5012 //    casts: When needed (namely, when we are called in the context of the
5013 //    vectorizer induction analysis), a Set of cast instructions will be
5014 //    populated by this method, and provided back to isInductionPHI. This is
5015 //    needed to allow the vectorizer to properly record them to be ignored by
5016 //    the cost model and to avoid vectorizing them (otherwise these casts,
5017 //    which are redundant under the runtime overflow checks, will be
5018 //    vectorized, which can be costly).
5019 //
5020 // 2) Support additional induction/PHISCEV patterns: We also want to support
5021 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5022 //    after the induction update operation (the induction increment):
5023 //
5024 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5025 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5026 //
5027 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5028 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5029 //
5030 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5031 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5032 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5033   SmallVector<const SCEVPredicate *, 3> Predicates;
5034 
5035   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5036   // return an AddRec expression under some predicate.
5037 
5038   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5039   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5040   assert(L && "Expecting an integer loop header phi");
5041 
5042   // The loop may have multiple entrances or multiple exits; we can analyze
5043   // this phi as an addrec if it has a unique entry value and a unique
5044   // backedge value.
5045   Value *BEValueV = nullptr, *StartValueV = nullptr;
5046   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5047     Value *V = PN->getIncomingValue(i);
5048     if (L->contains(PN->getIncomingBlock(i))) {
5049       if (!BEValueV) {
5050         BEValueV = V;
5051       } else if (BEValueV != V) {
5052         BEValueV = nullptr;
5053         break;
5054       }
5055     } else if (!StartValueV) {
5056       StartValueV = V;
5057     } else if (StartValueV != V) {
5058       StartValueV = nullptr;
5059       break;
5060     }
5061   }
5062   if (!BEValueV || !StartValueV)
5063     return None;
5064 
5065   const SCEV *BEValue = getSCEV(BEValueV);
5066 
5067   // If the value coming around the backedge is an add with the symbolic
5068   // value we just inserted, possibly with casts that we can ignore under
5069   // an appropriate runtime guard, then we found a simple induction variable!
5070   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5071   if (!Add)
5072     return None;
5073 
5074   // If there is a single occurrence of the symbolic value, possibly
5075   // casted, replace it with a recurrence.
5076   unsigned FoundIndex = Add->getNumOperands();
5077   Type *TruncTy = nullptr;
5078   bool Signed;
5079   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5080     if ((TruncTy =
5081              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5082       if (FoundIndex == e) {
5083         FoundIndex = i;
5084         break;
5085       }
5086 
5087   if (FoundIndex == Add->getNumOperands())
5088     return None;
5089 
5090   // Create an add with everything but the specified operand.
5091   SmallVector<const SCEV *, 8> Ops;
5092   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5093     if (i != FoundIndex)
5094       Ops.push_back(Add->getOperand(i));
5095   const SCEV *Accum = getAddExpr(Ops);
5096 
5097   // The runtime checks will not be valid if the step amount is
5098   // varying inside the loop.
5099   if (!isLoopInvariant(Accum, L))
5100     return None;
5101 
5102   // *** Part2: Create the predicates
5103 
5104   // Analysis was successful: we have a phi-with-cast pattern for which we
5105   // can return an AddRec expression under the following predicates:
5106   //
5107   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5108   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5109   // P2: An Equal predicate that guarantees that
5110   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5111   // P3: An Equal predicate that guarantees that
5112   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5113   //
5114   // As we next prove, the above predicates guarantee that:
5115   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5116   //
5117   //
5118   // More formally, we want to prove that:
5119   //     Expr(i+1) = Start + (i+1) * Accum
5120   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5121   //
5122   // Given that:
5123   // 1) Expr(0) = Start
5124   // 2) Expr(1) = Start + Accum
5125   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5126   // 3) Induction hypothesis (step i):
5127   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5128   //
5129   // Proof:
5130   //  Expr(i+1) =
5131   //   = Start + (i+1)*Accum
5132   //   = (Start + i*Accum) + Accum
5133   //   = Expr(i) + Accum
5134   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5135   //                                                             :: from step i
5136   //
5137   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5138   //
5139   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5140   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5141   //     + Accum                                                     :: from P3
5142   //
5143   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5144   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5145   //
5146   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5147   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5148   //
5149   // By induction, the same applies to all iterations 1<=i<n:
5150   //
5151 
5152   // Create a truncated addrec for which we will add a no overflow check (P1).
5153   const SCEV *StartVal = getSCEV(StartValueV);
5154   const SCEV *PHISCEV =
5155       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5156                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5157 
5158   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5159   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5160   // will be constant.
5161   //
5162   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5163   // add P1.
5164   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5165     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5166         Signed ? SCEVWrapPredicate::IncrementNSSW
5167                : SCEVWrapPredicate::IncrementNUSW;
5168     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5169     Predicates.push_back(AddRecPred);
5170   }
5171 
5172   // Create the Equal Predicates P2,P3:
5173 
5174   // It is possible that the predicates P2 and/or P3 are computable at
5175   // compile time due to StartVal and/or Accum being constants.
5176   // If either one is, then we can check that now and escape if either P2
5177   // or P3 is false.
5178 
5179   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5180   // for each of StartVal and Accum
5181   auto getExtendedExpr = [&](const SCEV *Expr,
5182                              bool CreateSignExtend) -> const SCEV * {
5183     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5184     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5185     const SCEV *ExtendedExpr =
5186         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5187                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5188     return ExtendedExpr;
5189   };
5190 
5191   // Given:
5192   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5193   //               = getExtendedExpr(Expr)
5194   // Determine whether the predicate P: Expr == ExtendedExpr
5195   // is known to be false at compile time
5196   auto PredIsKnownFalse = [&](const SCEV *Expr,
5197                               const SCEV *ExtendedExpr) -> bool {
5198     return Expr != ExtendedExpr &&
5199            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5200   };
5201 
5202   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5203   if (PredIsKnownFalse(StartVal, StartExtended)) {
5204     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5205     return None;
5206   }
5207 
5208   // The Step is always Signed (because the overflow checks are either
5209   // NSSW or NUSW)
5210   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5211   if (PredIsKnownFalse(Accum, AccumExtended)) {
5212     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5213     return None;
5214   }
5215 
5216   auto AppendPredicate = [&](const SCEV *Expr,
5217                              const SCEV *ExtendedExpr) -> void {
5218     if (Expr != ExtendedExpr &&
5219         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5220       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5221       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5222       Predicates.push_back(Pred);
5223     }
5224   };
5225 
5226   AppendPredicate(StartVal, StartExtended);
5227   AppendPredicate(Accum, AccumExtended);
5228 
5229   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5230   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5231   // into NewAR if it will also add the runtime overflow checks specified in
5232   // Predicates.
5233   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5234 
5235   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5236       std::make_pair(NewAR, Predicates);
5237   // Remember the result of the analysis for this SCEV at this locayyytion.
5238   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5239   return PredRewrite;
5240 }
5241 
5242 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5243 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5244   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5245   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5246   if (!L)
5247     return None;
5248 
5249   // Check to see if we already analyzed this PHI.
5250   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5251   if (I != PredicatedSCEVRewrites.end()) {
5252     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5253         I->second;
5254     // Analysis was done before and failed to create an AddRec:
5255     if (Rewrite.first == SymbolicPHI)
5256       return None;
5257     // Analysis was done before and succeeded to create an AddRec under
5258     // a predicate:
5259     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5260     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5261     return Rewrite;
5262   }
5263 
5264   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5265     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5266 
5267   // Record in the cache that the analysis failed
5268   if (!Rewrite) {
5269     SmallVector<const SCEVPredicate *, 3> Predicates;
5270     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5271     return None;
5272   }
5273 
5274   return Rewrite;
5275 }
5276 
5277 // FIXME: This utility is currently required because the Rewriter currently
5278 // does not rewrite this expression:
5279 // {0, +, (sext ix (trunc iy to ix) to iy)}
5280 // into {0, +, %step},
5281 // even when the following Equal predicate exists:
5282 // "%step == (sext ix (trunc iy to ix) to iy)".
5283 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5284     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5285   if (AR1 == AR2)
5286     return true;
5287 
5288   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5289     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5290         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5291       return false;
5292     return true;
5293   };
5294 
5295   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5296       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5297     return false;
5298   return true;
5299 }
5300 
5301 /// A helper function for createAddRecFromPHI to handle simple cases.
5302 ///
5303 /// This function tries to find an AddRec expression for the simplest (yet most
5304 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5305 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5306 /// technique for finding the AddRec expression.
5307 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5308                                                       Value *BEValueV,
5309                                                       Value *StartValueV) {
5310   const Loop *L = LI.getLoopFor(PN->getParent());
5311   assert(L && L->getHeader() == PN->getParent());
5312   assert(BEValueV && StartValueV);
5313 
5314   auto BO = MatchBinaryOp(BEValueV, DT);
5315   if (!BO)
5316     return nullptr;
5317 
5318   if (BO->Opcode != Instruction::Add)
5319     return nullptr;
5320 
5321   const SCEV *Accum = nullptr;
5322   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5323     Accum = getSCEV(BO->RHS);
5324   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5325     Accum = getSCEV(BO->LHS);
5326 
5327   if (!Accum)
5328     return nullptr;
5329 
5330   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5331   if (BO->IsNUW)
5332     Flags = setFlags(Flags, SCEV::FlagNUW);
5333   if (BO->IsNSW)
5334     Flags = setFlags(Flags, SCEV::FlagNSW);
5335 
5336   const SCEV *StartVal = getSCEV(StartValueV);
5337   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5338 
5339   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5340 
5341   // We can add Flags to the post-inc expression only if we
5342   // know that it is *undefined behavior* for BEValueV to
5343   // overflow.
5344   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5345     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5346       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5347 
5348   return PHISCEV;
5349 }
5350 
5351 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5352   const Loop *L = LI.getLoopFor(PN->getParent());
5353   if (!L || L->getHeader() != PN->getParent())
5354     return nullptr;
5355 
5356   // The loop may have multiple entrances or multiple exits; we can analyze
5357   // this phi as an addrec if it has a unique entry value and a unique
5358   // backedge value.
5359   Value *BEValueV = nullptr, *StartValueV = nullptr;
5360   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5361     Value *V = PN->getIncomingValue(i);
5362     if (L->contains(PN->getIncomingBlock(i))) {
5363       if (!BEValueV) {
5364         BEValueV = V;
5365       } else if (BEValueV != V) {
5366         BEValueV = nullptr;
5367         break;
5368       }
5369     } else if (!StartValueV) {
5370       StartValueV = V;
5371     } else if (StartValueV != V) {
5372       StartValueV = nullptr;
5373       break;
5374     }
5375   }
5376   if (!BEValueV || !StartValueV)
5377     return nullptr;
5378 
5379   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5380          "PHI node already processed?");
5381 
5382   // First, try to find AddRec expression without creating a fictituos symbolic
5383   // value for PN.
5384   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5385     return S;
5386 
5387   // Handle PHI node value symbolically.
5388   const SCEV *SymbolicName = getUnknown(PN);
5389   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5390 
5391   // Using this symbolic name for the PHI, analyze the value coming around
5392   // the back-edge.
5393   const SCEV *BEValue = getSCEV(BEValueV);
5394 
5395   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5396   // has a special value for the first iteration of the loop.
5397 
5398   // If the value coming around the backedge is an add with the symbolic
5399   // value we just inserted, then we found a simple induction variable!
5400   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5401     // If there is a single occurrence of the symbolic value, replace it
5402     // with a recurrence.
5403     unsigned FoundIndex = Add->getNumOperands();
5404     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5405       if (Add->getOperand(i) == SymbolicName)
5406         if (FoundIndex == e) {
5407           FoundIndex = i;
5408           break;
5409         }
5410 
5411     if (FoundIndex != Add->getNumOperands()) {
5412       // Create an add with everything but the specified operand.
5413       SmallVector<const SCEV *, 8> Ops;
5414       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5415         if (i != FoundIndex)
5416           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5417                                                              L, *this));
5418       const SCEV *Accum = getAddExpr(Ops);
5419 
5420       // This is not a valid addrec if the step amount is varying each
5421       // loop iteration, but is not itself an addrec in this loop.
5422       if (isLoopInvariant(Accum, L) ||
5423           (isa<SCEVAddRecExpr>(Accum) &&
5424            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5425         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5426 
5427         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5428           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5429             if (BO->IsNUW)
5430               Flags = setFlags(Flags, SCEV::FlagNUW);
5431             if (BO->IsNSW)
5432               Flags = setFlags(Flags, SCEV::FlagNSW);
5433           }
5434         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5435           // If the increment is an inbounds GEP, then we know the address
5436           // space cannot be wrapped around. We cannot make any guarantee
5437           // about signed or unsigned overflow because pointers are
5438           // unsigned but we may have a negative index from the base
5439           // pointer. We can guarantee that no unsigned wrap occurs if the
5440           // indices form a positive value.
5441           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5442             Flags = setFlags(Flags, SCEV::FlagNW);
5443 
5444             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5445             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5446               Flags = setFlags(Flags, SCEV::FlagNUW);
5447           }
5448 
5449           // We cannot transfer nuw and nsw flags from subtraction
5450           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5451           // for instance.
5452         }
5453 
5454         const SCEV *StartVal = getSCEV(StartValueV);
5455         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5456 
5457         // Okay, for the entire analysis of this edge we assumed the PHI
5458         // to be symbolic.  We now need to go back and purge all of the
5459         // entries for the scalars that use the symbolic expression.
5460         forgetSymbolicName(PN, SymbolicName);
5461         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5462 
5463         // We can add Flags to the post-inc expression only if we
5464         // know that it is *undefined behavior* for BEValueV to
5465         // overflow.
5466         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5467           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5468             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5469 
5470         return PHISCEV;
5471       }
5472     }
5473   } else {
5474     // Otherwise, this could be a loop like this:
5475     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5476     // In this case, j = {1,+,1}  and BEValue is j.
5477     // Because the other in-value of i (0) fits the evolution of BEValue
5478     // i really is an addrec evolution.
5479     //
5480     // We can generalize this saying that i is the shifted value of BEValue
5481     // by one iteration:
5482     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5483     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5484     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5485     if (Shifted != getCouldNotCompute() &&
5486         Start != getCouldNotCompute()) {
5487       const SCEV *StartVal = getSCEV(StartValueV);
5488       if (Start == StartVal) {
5489         // Okay, for the entire analysis of this edge we assumed the PHI
5490         // to be symbolic.  We now need to go back and purge all of the
5491         // entries for the scalars that use the symbolic expression.
5492         forgetSymbolicName(PN, SymbolicName);
5493         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5494         return Shifted;
5495       }
5496     }
5497   }
5498 
5499   // Remove the temporary PHI node SCEV that has been inserted while intending
5500   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5501   // as it will prevent later (possibly simpler) SCEV expressions to be added
5502   // to the ValueExprMap.
5503   eraseValueFromMap(PN);
5504 
5505   return nullptr;
5506 }
5507 
5508 // Checks if the SCEV S is available at BB.  S is considered available at BB
5509 // if S can be materialized at BB without introducing a fault.
5510 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5511                                BasicBlock *BB) {
5512   struct CheckAvailable {
5513     bool TraversalDone = false;
5514     bool Available = true;
5515 
5516     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5517     BasicBlock *BB = nullptr;
5518     DominatorTree &DT;
5519 
5520     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5521       : L(L), BB(BB), DT(DT) {}
5522 
5523     bool setUnavailable() {
5524       TraversalDone = true;
5525       Available = false;
5526       return false;
5527     }
5528 
5529     bool follow(const SCEV *S) {
5530       switch (S->getSCEVType()) {
5531       case scConstant:
5532       case scPtrToInt:
5533       case scTruncate:
5534       case scZeroExtend:
5535       case scSignExtend:
5536       case scAddExpr:
5537       case scMulExpr:
5538       case scUMaxExpr:
5539       case scSMaxExpr:
5540       case scUMinExpr:
5541       case scSMinExpr:
5542         // These expressions are available if their operand(s) is/are.
5543         return true;
5544 
5545       case scAddRecExpr: {
5546         // We allow add recurrences that are on the loop BB is in, or some
5547         // outer loop.  This guarantees availability because the value of the
5548         // add recurrence at BB is simply the "current" value of the induction
5549         // variable.  We can relax this in the future; for instance an add
5550         // recurrence on a sibling dominating loop is also available at BB.
5551         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5552         if (L && (ARLoop == L || ARLoop->contains(L)))
5553           return true;
5554 
5555         return setUnavailable();
5556       }
5557 
5558       case scUnknown: {
5559         // For SCEVUnknown, we check for simple dominance.
5560         const auto *SU = cast<SCEVUnknown>(S);
5561         Value *V = SU->getValue();
5562 
5563         if (isa<Argument>(V))
5564           return false;
5565 
5566         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5567           return false;
5568 
5569         return setUnavailable();
5570       }
5571 
5572       case scUDivExpr:
5573       case scCouldNotCompute:
5574         // We do not try to smart about these at all.
5575         return setUnavailable();
5576       }
5577       llvm_unreachable("Unknown SCEV kind!");
5578     }
5579 
5580     bool isDone() { return TraversalDone; }
5581   };
5582 
5583   CheckAvailable CA(L, BB, DT);
5584   SCEVTraversal<CheckAvailable> ST(CA);
5585 
5586   ST.visitAll(S);
5587   return CA.Available;
5588 }
5589 
5590 // Try to match a control flow sequence that branches out at BI and merges back
5591 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5592 // match.
5593 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5594                           Value *&C, Value *&LHS, Value *&RHS) {
5595   C = BI->getCondition();
5596 
5597   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5598   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5599 
5600   if (!LeftEdge.isSingleEdge())
5601     return false;
5602 
5603   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5604 
5605   Use &LeftUse = Merge->getOperandUse(0);
5606   Use &RightUse = Merge->getOperandUse(1);
5607 
5608   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5609     LHS = LeftUse;
5610     RHS = RightUse;
5611     return true;
5612   }
5613 
5614   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5615     LHS = RightUse;
5616     RHS = LeftUse;
5617     return true;
5618   }
5619 
5620   return false;
5621 }
5622 
5623 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5624   auto IsReachable =
5625       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5626   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5627     const Loop *L = LI.getLoopFor(PN->getParent());
5628 
5629     // We don't want to break LCSSA, even in a SCEV expression tree.
5630     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5631       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5632         return nullptr;
5633 
5634     // Try to match
5635     //
5636     //  br %cond, label %left, label %right
5637     // left:
5638     //  br label %merge
5639     // right:
5640     //  br label %merge
5641     // merge:
5642     //  V = phi [ %x, %left ], [ %y, %right ]
5643     //
5644     // as "select %cond, %x, %y"
5645 
5646     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5647     assert(IDom && "At least the entry block should dominate PN");
5648 
5649     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5650     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5651 
5652     if (BI && BI->isConditional() &&
5653         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5654         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5655         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5656       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5657   }
5658 
5659   return nullptr;
5660 }
5661 
5662 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5663   if (const SCEV *S = createAddRecFromPHI(PN))
5664     return S;
5665 
5666   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5667     return S;
5668 
5669   // If the PHI has a single incoming value, follow that value, unless the
5670   // PHI's incoming blocks are in a different loop, in which case doing so
5671   // risks breaking LCSSA form. Instcombine would normally zap these, but
5672   // it doesn't have DominatorTree information, so it may miss cases.
5673   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5674     if (LI.replacementPreservesLCSSAForm(PN, V))
5675       return getSCEV(V);
5676 
5677   // If it's not a loop phi, we can't handle it yet.
5678   return getUnknown(PN);
5679 }
5680 
5681 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5682                                                       Value *Cond,
5683                                                       Value *TrueVal,
5684                                                       Value *FalseVal) {
5685   // Handle "constant" branch or select. This can occur for instance when a
5686   // loop pass transforms an inner loop and moves on to process the outer loop.
5687   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5688     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5689 
5690   // Try to match some simple smax or umax patterns.
5691   auto *ICI = dyn_cast<ICmpInst>(Cond);
5692   if (!ICI)
5693     return getUnknown(I);
5694 
5695   Value *LHS = ICI->getOperand(0);
5696   Value *RHS = ICI->getOperand(1);
5697 
5698   switch (ICI->getPredicate()) {
5699   case ICmpInst::ICMP_SLT:
5700   case ICmpInst::ICMP_SLE:
5701   case ICmpInst::ICMP_ULT:
5702   case ICmpInst::ICMP_ULE:
5703     std::swap(LHS, RHS);
5704     LLVM_FALLTHROUGH;
5705   case ICmpInst::ICMP_SGT:
5706   case ICmpInst::ICMP_SGE:
5707   case ICmpInst::ICMP_UGT:
5708   case ICmpInst::ICMP_UGE:
5709     // a > b ? a+x : b+x  ->  max(a, b)+x
5710     // a > b ? b+x : a+x  ->  min(a, b)+x
5711     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5712       bool Signed = ICI->isSigned();
5713       const SCEV *LA = getSCEV(TrueVal);
5714       const SCEV *RA = getSCEV(FalseVal);
5715       const SCEV *LS = getSCEV(LHS);
5716       const SCEV *RS = getSCEV(RHS);
5717       if (LA->getType()->isPointerTy()) {
5718         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5719         // Need to make sure we can't produce weird expressions involving
5720         // negated pointers.
5721         if (LA == LS && RA == RS)
5722           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5723         if (LA == RS && RA == LS)
5724           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5725       }
5726       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5727         if (Op->getType()->isPointerTy()) {
5728           Op = getLosslessPtrToIntExpr(Op);
5729           if (isa<SCEVCouldNotCompute>(Op))
5730             return Op;
5731         }
5732         if (Signed)
5733           Op = getNoopOrSignExtend(Op, I->getType());
5734         else
5735           Op = getNoopOrZeroExtend(Op, I->getType());
5736         return Op;
5737       };
5738       LS = CoerceOperand(LS);
5739       RS = CoerceOperand(RS);
5740       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
5741         break;
5742       const SCEV *LDiff = getMinusSCEV(LA, LS);
5743       const SCEV *RDiff = getMinusSCEV(RA, RS);
5744       if (LDiff == RDiff)
5745         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
5746                           LDiff);
5747       LDiff = getMinusSCEV(LA, RS);
5748       RDiff = getMinusSCEV(RA, LS);
5749       if (LDiff == RDiff)
5750         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
5751                           LDiff);
5752     }
5753     break;
5754   case ICmpInst::ICMP_NE:
5755     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5756     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5757         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5758       const SCEV *One = getOne(I->getType());
5759       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5760       const SCEV *LA = getSCEV(TrueVal);
5761       const SCEV *RA = getSCEV(FalseVal);
5762       const SCEV *LDiff = getMinusSCEV(LA, LS);
5763       const SCEV *RDiff = getMinusSCEV(RA, One);
5764       if (LDiff == RDiff)
5765         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5766     }
5767     break;
5768   case ICmpInst::ICMP_EQ:
5769     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5770     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5771         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5772       const SCEV *One = getOne(I->getType());
5773       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5774       const SCEV *LA = getSCEV(TrueVal);
5775       const SCEV *RA = getSCEV(FalseVal);
5776       const SCEV *LDiff = getMinusSCEV(LA, One);
5777       const SCEV *RDiff = getMinusSCEV(RA, LS);
5778       if (LDiff == RDiff)
5779         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5780     }
5781     break;
5782   default:
5783     break;
5784   }
5785 
5786   return getUnknown(I);
5787 }
5788 
5789 /// Expand GEP instructions into add and multiply operations. This allows them
5790 /// to be analyzed by regular SCEV code.
5791 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5792   // Don't attempt to analyze GEPs over unsized objects.
5793   if (!GEP->getSourceElementType()->isSized())
5794     return getUnknown(GEP);
5795 
5796   SmallVector<const SCEV *, 4> IndexExprs;
5797   for (Value *Index : GEP->indices())
5798     IndexExprs.push_back(getSCEV(Index));
5799   return getGEPExpr(GEP, IndexExprs);
5800 }
5801 
5802 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5803   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5804     return C->getAPInt().countTrailingZeros();
5805 
5806   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5807     return GetMinTrailingZeros(I->getOperand());
5808 
5809   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5810     return std::min(GetMinTrailingZeros(T->getOperand()),
5811                     (uint32_t)getTypeSizeInBits(T->getType()));
5812 
5813   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5814     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5815     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5816                ? getTypeSizeInBits(E->getType())
5817                : OpRes;
5818   }
5819 
5820   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5821     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5822     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5823                ? getTypeSizeInBits(E->getType())
5824                : OpRes;
5825   }
5826 
5827   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5828     // The result is the min of all operands results.
5829     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5830     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5831       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5832     return MinOpRes;
5833   }
5834 
5835   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5836     // The result is the sum of all operands results.
5837     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5838     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5839     for (unsigned i = 1, e = M->getNumOperands();
5840          SumOpRes != BitWidth && i != e; ++i)
5841       SumOpRes =
5842           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5843     return SumOpRes;
5844   }
5845 
5846   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5847     // The result is the min of all operands results.
5848     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5849     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5850       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5851     return MinOpRes;
5852   }
5853 
5854   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5855     // The result is the min of all operands results.
5856     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5857     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5858       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5859     return MinOpRes;
5860   }
5861 
5862   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5863     // The result is the min of all operands results.
5864     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5865     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5866       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5867     return MinOpRes;
5868   }
5869 
5870   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5871     // For a SCEVUnknown, ask ValueTracking.
5872     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5873     return Known.countMinTrailingZeros();
5874   }
5875 
5876   // SCEVUDivExpr
5877   return 0;
5878 }
5879 
5880 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5881   auto I = MinTrailingZerosCache.find(S);
5882   if (I != MinTrailingZerosCache.end())
5883     return I->second;
5884 
5885   uint32_t Result = GetMinTrailingZerosImpl(S);
5886   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5887   assert(InsertPair.second && "Should insert a new key");
5888   return InsertPair.first->second;
5889 }
5890 
5891 /// Helper method to assign a range to V from metadata present in the IR.
5892 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5893   if (Instruction *I = dyn_cast<Instruction>(V))
5894     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5895       return getConstantRangeFromMetadata(*MD);
5896 
5897   return None;
5898 }
5899 
5900 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5901                                      SCEV::NoWrapFlags Flags) {
5902   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5903     AddRec->setNoWrapFlags(Flags);
5904     UnsignedRanges.erase(AddRec);
5905     SignedRanges.erase(AddRec);
5906   }
5907 }
5908 
5909 ConstantRange ScalarEvolution::
5910 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5911   const DataLayout &DL = getDataLayout();
5912 
5913   unsigned BitWidth = getTypeSizeInBits(U->getType());
5914   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
5915 
5916   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5917   // use information about the trip count to improve our available range.  Note
5918   // that the trip count independent cases are already handled by known bits.
5919   // WARNING: The definition of recurrence used here is subtly different than
5920   // the one used by AddRec (and thus most of this file).  Step is allowed to
5921   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5922   // and other addrecs in the same loop (for non-affine addrecs).  The code
5923   // below intentionally handles the case where step is not loop invariant.
5924   auto *P = dyn_cast<PHINode>(U->getValue());
5925   if (!P)
5926     return FullSet;
5927 
5928   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5929   // even the values that are not available in these blocks may come from them,
5930   // and this leads to false-positive recurrence test.
5931   for (auto *Pred : predecessors(P->getParent()))
5932     if (!DT.isReachableFromEntry(Pred))
5933       return FullSet;
5934 
5935   BinaryOperator *BO;
5936   Value *Start, *Step;
5937   if (!matchSimpleRecurrence(P, BO, Start, Step))
5938     return FullSet;
5939 
5940   // If we found a recurrence in reachable code, we must be in a loop. Note
5941   // that BO might be in some subloop of L, and that's completely okay.
5942   auto *L = LI.getLoopFor(P->getParent());
5943   assert(L && L->getHeader() == P->getParent());
5944   if (!L->contains(BO->getParent()))
5945     // NOTE: This bailout should be an assert instead.  However, asserting
5946     // the condition here exposes a case where LoopFusion is querying SCEV
5947     // with malformed loop information during the midst of the transform.
5948     // There doesn't appear to be an obvious fix, so for the moment bailout
5949     // until the caller issue can be fixed.  PR49566 tracks the bug.
5950     return FullSet;
5951 
5952   // TODO: Extend to other opcodes such as mul, and div
5953   switch (BO->getOpcode()) {
5954   default:
5955     return FullSet;
5956   case Instruction::AShr:
5957   case Instruction::LShr:
5958   case Instruction::Shl:
5959     break;
5960   };
5961 
5962   if (BO->getOperand(0) != P)
5963     // TODO: Handle the power function forms some day.
5964     return FullSet;
5965 
5966   unsigned TC = getSmallConstantMaxTripCount(L);
5967   if (!TC || TC >= BitWidth)
5968     return FullSet;
5969 
5970   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5971   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5972   assert(KnownStart.getBitWidth() == BitWidth &&
5973          KnownStep.getBitWidth() == BitWidth);
5974 
5975   // Compute total shift amount, being careful of overflow and bitwidths.
5976   auto MaxShiftAmt = KnownStep.getMaxValue();
5977   APInt TCAP(BitWidth, TC-1);
5978   bool Overflow = false;
5979   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5980   if (Overflow)
5981     return FullSet;
5982 
5983   switch (BO->getOpcode()) {
5984   default:
5985     llvm_unreachable("filtered out above");
5986   case Instruction::AShr: {
5987     // For each ashr, three cases:
5988     //   shift = 0 => unchanged value
5989     //   saturation => 0 or -1
5990     //   other => a value closer to zero (of the same sign)
5991     // Thus, the end value is closer to zero than the start.
5992     auto KnownEnd = KnownBits::ashr(KnownStart,
5993                                     KnownBits::makeConstant(TotalShift));
5994     if (KnownStart.isNonNegative())
5995       // Analogous to lshr (simply not yet canonicalized)
5996       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5997                                         KnownStart.getMaxValue() + 1);
5998     if (KnownStart.isNegative())
5999       // End >=u Start && End <=s Start
6000       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6001                                         KnownEnd.getMaxValue() + 1);
6002     break;
6003   }
6004   case Instruction::LShr: {
6005     // For each lshr, three cases:
6006     //   shift = 0 => unchanged value
6007     //   saturation => 0
6008     //   other => a smaller positive number
6009     // Thus, the low end of the unsigned range is the last value produced.
6010     auto KnownEnd = KnownBits::lshr(KnownStart,
6011                                     KnownBits::makeConstant(TotalShift));
6012     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6013                                       KnownStart.getMaxValue() + 1);
6014   }
6015   case Instruction::Shl: {
6016     // Iff no bits are shifted out, value increases on every shift.
6017     auto KnownEnd = KnownBits::shl(KnownStart,
6018                                    KnownBits::makeConstant(TotalShift));
6019     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6020       return ConstantRange(KnownStart.getMinValue(),
6021                            KnownEnd.getMaxValue() + 1);
6022     break;
6023   }
6024   };
6025   return FullSet;
6026 }
6027 
6028 /// Determine the range for a particular SCEV.  If SignHint is
6029 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6030 /// with a "cleaner" unsigned (resp. signed) representation.
6031 const ConstantRange &
6032 ScalarEvolution::getRangeRef(const SCEV *S,
6033                              ScalarEvolution::RangeSignHint SignHint) {
6034   DenseMap<const SCEV *, ConstantRange> &Cache =
6035       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6036                                                        : SignedRanges;
6037   ConstantRange::PreferredRangeType RangeType =
6038       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
6039           ? ConstantRange::Unsigned : ConstantRange::Signed;
6040 
6041   // See if we've computed this range already.
6042   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6043   if (I != Cache.end())
6044     return I->second;
6045 
6046   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6047     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6048 
6049   unsigned BitWidth = getTypeSizeInBits(S->getType());
6050   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6051   using OBO = OverflowingBinaryOperator;
6052 
6053   // If the value has known zeros, the maximum value will have those known zeros
6054   // as well.
6055   uint32_t TZ = GetMinTrailingZeros(S);
6056   if (TZ != 0) {
6057     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6058       ConservativeResult =
6059           ConstantRange(APInt::getMinValue(BitWidth),
6060                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6061     else
6062       ConservativeResult = ConstantRange(
6063           APInt::getSignedMinValue(BitWidth),
6064           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6065   }
6066 
6067   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6068     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6069     unsigned WrapType = OBO::AnyWrap;
6070     if (Add->hasNoSignedWrap())
6071       WrapType |= OBO::NoSignedWrap;
6072     if (Add->hasNoUnsignedWrap())
6073       WrapType |= OBO::NoUnsignedWrap;
6074     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6075       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6076                           WrapType, RangeType);
6077     return setRange(Add, SignHint,
6078                     ConservativeResult.intersectWith(X, RangeType));
6079   }
6080 
6081   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6082     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6083     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6084       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6085     return setRange(Mul, SignHint,
6086                     ConservativeResult.intersectWith(X, RangeType));
6087   }
6088 
6089   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
6090     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
6091     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
6092       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
6093     return setRange(SMax, SignHint,
6094                     ConservativeResult.intersectWith(X, RangeType));
6095   }
6096 
6097   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
6098     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
6099     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
6100       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
6101     return setRange(UMax, SignHint,
6102                     ConservativeResult.intersectWith(X, RangeType));
6103   }
6104 
6105   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
6106     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
6107     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
6108       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
6109     return setRange(SMin, SignHint,
6110                     ConservativeResult.intersectWith(X, RangeType));
6111   }
6112 
6113   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
6114     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
6115     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
6116       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
6117     return setRange(UMin, SignHint,
6118                     ConservativeResult.intersectWith(X, RangeType));
6119   }
6120 
6121   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6122     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6123     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6124     return setRange(UDiv, SignHint,
6125                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6126   }
6127 
6128   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6129     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6130     return setRange(ZExt, SignHint,
6131                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6132                                                      RangeType));
6133   }
6134 
6135   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6136     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6137     return setRange(SExt, SignHint,
6138                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6139                                                      RangeType));
6140   }
6141 
6142   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6143     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6144     return setRange(PtrToInt, SignHint, X);
6145   }
6146 
6147   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6148     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6149     return setRange(Trunc, SignHint,
6150                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6151                                                      RangeType));
6152   }
6153 
6154   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6155     // If there's no unsigned wrap, the value will never be less than its
6156     // initial value.
6157     if (AddRec->hasNoUnsignedWrap()) {
6158       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6159       if (!UnsignedMinValue.isZero())
6160         ConservativeResult = ConservativeResult.intersectWith(
6161             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6162     }
6163 
6164     // If there's no signed wrap, and all the operands except initial value have
6165     // the same sign or zero, the value won't ever be:
6166     // 1: smaller than initial value if operands are non negative,
6167     // 2: bigger than initial value if operands are non positive.
6168     // For both cases, value can not cross signed min/max boundary.
6169     if (AddRec->hasNoSignedWrap()) {
6170       bool AllNonNeg = true;
6171       bool AllNonPos = true;
6172       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6173         if (!isKnownNonNegative(AddRec->getOperand(i)))
6174           AllNonNeg = false;
6175         if (!isKnownNonPositive(AddRec->getOperand(i)))
6176           AllNonPos = false;
6177       }
6178       if (AllNonNeg)
6179         ConservativeResult = ConservativeResult.intersectWith(
6180             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6181                                        APInt::getSignedMinValue(BitWidth)),
6182             RangeType);
6183       else if (AllNonPos)
6184         ConservativeResult = ConservativeResult.intersectWith(
6185             ConstantRange::getNonEmpty(
6186                 APInt::getSignedMinValue(BitWidth),
6187                 getSignedRangeMax(AddRec->getStart()) + 1),
6188             RangeType);
6189     }
6190 
6191     // TODO: non-affine addrec
6192     if (AddRec->isAffine()) {
6193       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6194       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6195           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6196         auto RangeFromAffine = getRangeForAffineAR(
6197             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6198             BitWidth);
6199         ConservativeResult =
6200             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6201 
6202         auto RangeFromFactoring = getRangeViaFactoring(
6203             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6204             BitWidth);
6205         ConservativeResult =
6206             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6207       }
6208 
6209       // Now try symbolic BE count and more powerful methods.
6210       if (UseExpensiveRangeSharpening) {
6211         const SCEV *SymbolicMaxBECount =
6212             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6213         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6214             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6215             AddRec->hasNoSelfWrap()) {
6216           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6217               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6218           ConservativeResult =
6219               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6220         }
6221       }
6222     }
6223 
6224     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6225   }
6226 
6227   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6228 
6229     // Check if the IR explicitly contains !range metadata.
6230     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6231     if (MDRange.hasValue())
6232       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6233                                                             RangeType);
6234 
6235     // Use facts about recurrences in the underlying IR.  Note that add
6236     // recurrences are AddRecExprs and thus don't hit this path.  This
6237     // primarily handles shift recurrences.
6238     auto CR = getRangeForUnknownRecurrence(U);
6239     ConservativeResult = ConservativeResult.intersectWith(CR);
6240 
6241     // See if ValueTracking can give us a useful range.
6242     const DataLayout &DL = getDataLayout();
6243     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6244     if (Known.getBitWidth() != BitWidth)
6245       Known = Known.zextOrTrunc(BitWidth);
6246 
6247     // ValueTracking may be able to compute a tighter result for the number of
6248     // sign bits than for the value of those sign bits.
6249     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6250     if (U->getType()->isPointerTy()) {
6251       // If the pointer size is larger than the index size type, this can cause
6252       // NS to be larger than BitWidth. So compensate for this.
6253       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6254       int ptrIdxDiff = ptrSize - BitWidth;
6255       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6256         NS -= ptrIdxDiff;
6257     }
6258 
6259     if (NS > 1) {
6260       // If we know any of the sign bits, we know all of the sign bits.
6261       if (!Known.Zero.getHiBits(NS).isZero())
6262         Known.Zero.setHighBits(NS);
6263       if (!Known.One.getHiBits(NS).isZero())
6264         Known.One.setHighBits(NS);
6265     }
6266 
6267     if (Known.getMinValue() != Known.getMaxValue() + 1)
6268       ConservativeResult = ConservativeResult.intersectWith(
6269           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6270           RangeType);
6271     if (NS > 1)
6272       ConservativeResult = ConservativeResult.intersectWith(
6273           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6274                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6275           RangeType);
6276 
6277     // A range of Phi is a subset of union of all ranges of its input.
6278     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6279       // Make sure that we do not run over cycled Phis.
6280       if (PendingPhiRanges.insert(Phi).second) {
6281         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6282         for (auto &Op : Phi->operands()) {
6283           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6284           RangeFromOps = RangeFromOps.unionWith(OpRange);
6285           // No point to continue if we already have a full set.
6286           if (RangeFromOps.isFullSet())
6287             break;
6288         }
6289         ConservativeResult =
6290             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6291         bool Erased = PendingPhiRanges.erase(Phi);
6292         assert(Erased && "Failed to erase Phi properly?");
6293         (void) Erased;
6294       }
6295     }
6296 
6297     return setRange(U, SignHint, std::move(ConservativeResult));
6298   }
6299 
6300   return setRange(S, SignHint, std::move(ConservativeResult));
6301 }
6302 
6303 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6304 // values that the expression can take. Initially, the expression has a value
6305 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6306 // argument defines if we treat Step as signed or unsigned.
6307 static ConstantRange getRangeForAffineARHelper(APInt Step,
6308                                                const ConstantRange &StartRange,
6309                                                const APInt &MaxBECount,
6310                                                unsigned BitWidth, bool Signed) {
6311   // If either Step or MaxBECount is 0, then the expression won't change, and we
6312   // just need to return the initial range.
6313   if (Step == 0 || MaxBECount == 0)
6314     return StartRange;
6315 
6316   // If we don't know anything about the initial value (i.e. StartRange is
6317   // FullRange), then we don't know anything about the final range either.
6318   // Return FullRange.
6319   if (StartRange.isFullSet())
6320     return ConstantRange::getFull(BitWidth);
6321 
6322   // If Step is signed and negative, then we use its absolute value, but we also
6323   // note that we're moving in the opposite direction.
6324   bool Descending = Signed && Step.isNegative();
6325 
6326   if (Signed)
6327     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6328     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6329     // This equations hold true due to the well-defined wrap-around behavior of
6330     // APInt.
6331     Step = Step.abs();
6332 
6333   // Check if Offset is more than full span of BitWidth. If it is, the
6334   // expression is guaranteed to overflow.
6335   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6336     return ConstantRange::getFull(BitWidth);
6337 
6338   // Offset is by how much the expression can change. Checks above guarantee no
6339   // overflow here.
6340   APInt Offset = Step * MaxBECount;
6341 
6342   // Minimum value of the final range will match the minimal value of StartRange
6343   // if the expression is increasing and will be decreased by Offset otherwise.
6344   // Maximum value of the final range will match the maximal value of StartRange
6345   // if the expression is decreasing and will be increased by Offset otherwise.
6346   APInt StartLower = StartRange.getLower();
6347   APInt StartUpper = StartRange.getUpper() - 1;
6348   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6349                                    : (StartUpper + std::move(Offset));
6350 
6351   // It's possible that the new minimum/maximum value will fall into the initial
6352   // range (due to wrap around). This means that the expression can take any
6353   // value in this bitwidth, and we have to return full range.
6354   if (StartRange.contains(MovedBoundary))
6355     return ConstantRange::getFull(BitWidth);
6356 
6357   APInt NewLower =
6358       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6359   APInt NewUpper =
6360       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6361   NewUpper += 1;
6362 
6363   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6364   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6365 }
6366 
6367 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6368                                                    const SCEV *Step,
6369                                                    const SCEV *MaxBECount,
6370                                                    unsigned BitWidth) {
6371   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6372          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6373          "Precondition!");
6374 
6375   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6376   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6377 
6378   // First, consider step signed.
6379   ConstantRange StartSRange = getSignedRange(Start);
6380   ConstantRange StepSRange = getSignedRange(Step);
6381 
6382   // If Step can be both positive and negative, we need to find ranges for the
6383   // maximum absolute step values in both directions and union them.
6384   ConstantRange SR =
6385       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6386                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6387   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6388                                               StartSRange, MaxBECountValue,
6389                                               BitWidth, /* Signed = */ true));
6390 
6391   // Next, consider step unsigned.
6392   ConstantRange UR = getRangeForAffineARHelper(
6393       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6394       MaxBECountValue, BitWidth, /* Signed = */ false);
6395 
6396   // Finally, intersect signed and unsigned ranges.
6397   return SR.intersectWith(UR, ConstantRange::Smallest);
6398 }
6399 
6400 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6401     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6402     ScalarEvolution::RangeSignHint SignHint) {
6403   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6404   assert(AddRec->hasNoSelfWrap() &&
6405          "This only works for non-self-wrapping AddRecs!");
6406   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6407   const SCEV *Step = AddRec->getStepRecurrence(*this);
6408   // Only deal with constant step to save compile time.
6409   if (!isa<SCEVConstant>(Step))
6410     return ConstantRange::getFull(BitWidth);
6411   // Let's make sure that we can prove that we do not self-wrap during
6412   // MaxBECount iterations. We need this because MaxBECount is a maximum
6413   // iteration count estimate, and we might infer nw from some exit for which we
6414   // do not know max exit count (or any other side reasoning).
6415   // TODO: Turn into assert at some point.
6416   if (getTypeSizeInBits(MaxBECount->getType()) >
6417       getTypeSizeInBits(AddRec->getType()))
6418     return ConstantRange::getFull(BitWidth);
6419   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6420   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6421   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6422   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6423   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6424                                          MaxItersWithoutWrap))
6425     return ConstantRange::getFull(BitWidth);
6426 
6427   ICmpInst::Predicate LEPred =
6428       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6429   ICmpInst::Predicate GEPred =
6430       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6431   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6432 
6433   // We know that there is no self-wrap. Let's take Start and End values and
6434   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6435   // the iteration. They either lie inside the range [Min(Start, End),
6436   // Max(Start, End)] or outside it:
6437   //
6438   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6439   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6440   //
6441   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6442   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6443   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6444   // Start <= End and step is positive, or Start >= End and step is negative.
6445   const SCEV *Start = AddRec->getStart();
6446   ConstantRange StartRange = getRangeRef(Start, SignHint);
6447   ConstantRange EndRange = getRangeRef(End, SignHint);
6448   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6449   // If they already cover full iteration space, we will know nothing useful
6450   // even if we prove what we want to prove.
6451   if (RangeBetween.isFullSet())
6452     return RangeBetween;
6453   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6454   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6455                                : RangeBetween.isWrappedSet();
6456   if (IsWrappedSet)
6457     return ConstantRange::getFull(BitWidth);
6458 
6459   if (isKnownPositive(Step) &&
6460       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6461     return RangeBetween;
6462   else if (isKnownNegative(Step) &&
6463            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6464     return RangeBetween;
6465   return ConstantRange::getFull(BitWidth);
6466 }
6467 
6468 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6469                                                     const SCEV *Step,
6470                                                     const SCEV *MaxBECount,
6471                                                     unsigned BitWidth) {
6472   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6473   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6474 
6475   struct SelectPattern {
6476     Value *Condition = nullptr;
6477     APInt TrueValue;
6478     APInt FalseValue;
6479 
6480     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6481                            const SCEV *S) {
6482       Optional<unsigned> CastOp;
6483       APInt Offset(BitWidth, 0);
6484 
6485       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6486              "Should be!");
6487 
6488       // Peel off a constant offset:
6489       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6490         // In the future we could consider being smarter here and handle
6491         // {Start+Step,+,Step} too.
6492         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6493           return;
6494 
6495         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6496         S = SA->getOperand(1);
6497       }
6498 
6499       // Peel off a cast operation
6500       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6501         CastOp = SCast->getSCEVType();
6502         S = SCast->getOperand();
6503       }
6504 
6505       using namespace llvm::PatternMatch;
6506 
6507       auto *SU = dyn_cast<SCEVUnknown>(S);
6508       const APInt *TrueVal, *FalseVal;
6509       if (!SU ||
6510           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6511                                           m_APInt(FalseVal)))) {
6512         Condition = nullptr;
6513         return;
6514       }
6515 
6516       TrueValue = *TrueVal;
6517       FalseValue = *FalseVal;
6518 
6519       // Re-apply the cast we peeled off earlier
6520       if (CastOp.hasValue())
6521         switch (*CastOp) {
6522         default:
6523           llvm_unreachable("Unknown SCEV cast type!");
6524 
6525         case scTruncate:
6526           TrueValue = TrueValue.trunc(BitWidth);
6527           FalseValue = FalseValue.trunc(BitWidth);
6528           break;
6529         case scZeroExtend:
6530           TrueValue = TrueValue.zext(BitWidth);
6531           FalseValue = FalseValue.zext(BitWidth);
6532           break;
6533         case scSignExtend:
6534           TrueValue = TrueValue.sext(BitWidth);
6535           FalseValue = FalseValue.sext(BitWidth);
6536           break;
6537         }
6538 
6539       // Re-apply the constant offset we peeled off earlier
6540       TrueValue += Offset;
6541       FalseValue += Offset;
6542     }
6543 
6544     bool isRecognized() { return Condition != nullptr; }
6545   };
6546 
6547   SelectPattern StartPattern(*this, BitWidth, Start);
6548   if (!StartPattern.isRecognized())
6549     return ConstantRange::getFull(BitWidth);
6550 
6551   SelectPattern StepPattern(*this, BitWidth, Step);
6552   if (!StepPattern.isRecognized())
6553     return ConstantRange::getFull(BitWidth);
6554 
6555   if (StartPattern.Condition != StepPattern.Condition) {
6556     // We don't handle this case today; but we could, by considering four
6557     // possibilities below instead of two. I'm not sure if there are cases where
6558     // that will help over what getRange already does, though.
6559     return ConstantRange::getFull(BitWidth);
6560   }
6561 
6562   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6563   // construct arbitrary general SCEV expressions here.  This function is called
6564   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6565   // say) can end up caching a suboptimal value.
6566 
6567   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6568   // C2352 and C2512 (otherwise it isn't needed).
6569 
6570   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6571   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6572   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6573   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6574 
6575   ConstantRange TrueRange =
6576       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6577   ConstantRange FalseRange =
6578       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6579 
6580   return TrueRange.unionWith(FalseRange);
6581 }
6582 
6583 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6584   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6585   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6586 
6587   // Return early if there are no flags to propagate to the SCEV.
6588   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6589   if (BinOp->hasNoUnsignedWrap())
6590     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6591   if (BinOp->hasNoSignedWrap())
6592     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6593   if (Flags == SCEV::FlagAnyWrap)
6594     return SCEV::FlagAnyWrap;
6595 
6596   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6597 }
6598 
6599 const Instruction *
6600 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
6601   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
6602     return &*AddRec->getLoop()->getHeader()->begin();
6603   if (auto *U = dyn_cast<SCEVUnknown>(S))
6604     if (auto *I = dyn_cast<Instruction>(U->getValue()))
6605       return I;
6606   return nullptr;
6607 }
6608 
6609 /// Fills \p Ops with unique operands of \p S, if it has operands. If not,
6610 /// \p Ops remains unmodified.
6611 static void collectUniqueOps(const SCEV *S,
6612                              SmallVectorImpl<const SCEV *> &Ops) {
6613   SmallPtrSet<const SCEV *, 4> Unique;
6614   auto InsertUnique = [&](const SCEV *S) {
6615     if (Unique.insert(S).second)
6616       Ops.push_back(S);
6617   };
6618   if (auto *S2 = dyn_cast<SCEVCastExpr>(S))
6619     for (auto *Op : S2->operands())
6620       InsertUnique(Op);
6621   else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S))
6622     for (auto *Op : S2->operands())
6623       InsertUnique(Op);
6624   else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S))
6625     for (auto *Op : S2->operands())
6626       InsertUnique(Op);
6627 }
6628 
6629 const Instruction *
6630 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
6631                                        bool &Precise) {
6632   Precise = true;
6633   // Do a bounded search of the def relation of the requested SCEVs.
6634   SmallSet<const SCEV *, 16> Visited;
6635   SmallVector<const SCEV *> Worklist;
6636   auto pushOp = [&](const SCEV *S) {
6637     if (!Visited.insert(S).second)
6638       return;
6639     // Threshold of 30 here is arbitrary.
6640     if (Visited.size() > 30) {
6641       Precise = false;
6642       return;
6643     }
6644     Worklist.push_back(S);
6645   };
6646 
6647   for (auto *S : Ops)
6648     pushOp(S);
6649 
6650   const Instruction *Bound = nullptr;
6651   while (!Worklist.empty()) {
6652     auto *S = Worklist.pop_back_val();
6653     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
6654       if (!Bound || DT.dominates(Bound, DefI))
6655         Bound = DefI;
6656     } else {
6657       SmallVector<const SCEV *, 4> Ops;
6658       collectUniqueOps(S, Ops);
6659       for (auto *Op : Ops)
6660         pushOp(Op);
6661     }
6662   }
6663   return Bound ? Bound : &*F.getEntryBlock().begin();
6664 }
6665 
6666 const Instruction *
6667 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
6668   bool Discard;
6669   return getDefiningScopeBound(Ops, Discard);
6670 }
6671 
6672 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
6673                                                         const Instruction *B) {
6674   if (A->getParent() == B->getParent() &&
6675       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
6676                                                  B->getIterator()))
6677     return true;
6678 
6679   auto *BLoop = LI.getLoopFor(B->getParent());
6680   if (BLoop && BLoop->getHeader() == B->getParent() &&
6681       BLoop->getLoopPreheader() == A->getParent() &&
6682       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
6683                                                  A->getParent()->end()) &&
6684       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
6685                                                  B->getIterator()))
6686     return true;
6687   return false;
6688 }
6689 
6690 
6691 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6692   // Only proceed if we can prove that I does not yield poison.
6693   if (!programUndefinedIfPoison(I))
6694     return false;
6695 
6696   // At this point we know that if I is executed, then it does not wrap
6697   // according to at least one of NSW or NUW. If I is not executed, then we do
6698   // not know if the calculation that I represents would wrap. Multiple
6699   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6700   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6701   // derived from other instructions that map to the same SCEV. We cannot make
6702   // that guarantee for cases where I is not executed. So we need to find a
6703   // upper bound on the defining scope for the SCEV, and prove that I is
6704   // executed every time we enter that scope.  When the bounding scope is a
6705   // loop (the common case), this is equivalent to proving I executes on every
6706   // iteration of that loop.
6707   SmallVector<const SCEV *> SCEVOps;
6708   for (const Use &Op : I->operands()) {
6709     // I could be an extractvalue from a call to an overflow intrinsic.
6710     // TODO: We can do better here in some cases.
6711     if (isSCEVable(Op->getType()))
6712       SCEVOps.push_back(getSCEV(Op));
6713   }
6714   auto *DefI = getDefiningScopeBound(SCEVOps);
6715   return isGuaranteedToTransferExecutionTo(DefI, I);
6716 }
6717 
6718 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6719   // If we know that \c I can never be poison period, then that's enough.
6720   if (isSCEVExprNeverPoison(I))
6721     return true;
6722 
6723   // For an add recurrence specifically, we assume that infinite loops without
6724   // side effects are undefined behavior, and then reason as follows:
6725   //
6726   // If the add recurrence is poison in any iteration, it is poison on all
6727   // future iterations (since incrementing poison yields poison). If the result
6728   // of the add recurrence is fed into the loop latch condition and the loop
6729   // does not contain any throws or exiting blocks other than the latch, we now
6730   // have the ability to "choose" whether the backedge is taken or not (by
6731   // choosing a sufficiently evil value for the poison feeding into the branch)
6732   // for every iteration including and after the one in which \p I first became
6733   // poison.  There are two possibilities (let's call the iteration in which \p
6734   // I first became poison as K):
6735   //
6736   //  1. In the set of iterations including and after K, the loop body executes
6737   //     no side effects.  In this case executing the backege an infinte number
6738   //     of times will yield undefined behavior.
6739   //
6740   //  2. In the set of iterations including and after K, the loop body executes
6741   //     at least one side effect.  In this case, that specific instance of side
6742   //     effect is control dependent on poison, which also yields undefined
6743   //     behavior.
6744 
6745   auto *ExitingBB = L->getExitingBlock();
6746   auto *LatchBB = L->getLoopLatch();
6747   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6748     return false;
6749 
6750   SmallPtrSet<const Instruction *, 16> Pushed;
6751   SmallVector<const Instruction *, 8> PoisonStack;
6752 
6753   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6754   // things that are known to be poison under that assumption go on the
6755   // PoisonStack.
6756   Pushed.insert(I);
6757   PoisonStack.push_back(I);
6758 
6759   bool LatchControlDependentOnPoison = false;
6760   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6761     const Instruction *Poison = PoisonStack.pop_back_val();
6762 
6763     for (auto *PoisonUser : Poison->users()) {
6764       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6765         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6766           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6767       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6768         assert(BI->isConditional() && "Only possibility!");
6769         if (BI->getParent() == LatchBB) {
6770           LatchControlDependentOnPoison = true;
6771           break;
6772         }
6773       }
6774     }
6775   }
6776 
6777   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6778 }
6779 
6780 ScalarEvolution::LoopProperties
6781 ScalarEvolution::getLoopProperties(const Loop *L) {
6782   using LoopProperties = ScalarEvolution::LoopProperties;
6783 
6784   auto Itr = LoopPropertiesCache.find(L);
6785   if (Itr == LoopPropertiesCache.end()) {
6786     auto HasSideEffects = [](Instruction *I) {
6787       if (auto *SI = dyn_cast<StoreInst>(I))
6788         return !SI->isSimple();
6789 
6790       return I->mayThrow() || I->mayWriteToMemory();
6791     };
6792 
6793     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6794                          /*HasNoSideEffects*/ true};
6795 
6796     for (auto *BB : L->getBlocks())
6797       for (auto &I : *BB) {
6798         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6799           LP.HasNoAbnormalExits = false;
6800         if (HasSideEffects(&I))
6801           LP.HasNoSideEffects = false;
6802         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6803           break; // We're already as pessimistic as we can get.
6804       }
6805 
6806     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6807     assert(InsertPair.second && "We just checked!");
6808     Itr = InsertPair.first;
6809   }
6810 
6811   return Itr->second;
6812 }
6813 
6814 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
6815   // A mustprogress loop without side effects must be finite.
6816   // TODO: The check used here is very conservative.  It's only *specific*
6817   // side effects which are well defined in infinite loops.
6818   return isMustProgress(L) && loopHasNoSideEffects(L);
6819 }
6820 
6821 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6822   if (!isSCEVable(V->getType()))
6823     return getUnknown(V);
6824 
6825   if (Instruction *I = dyn_cast<Instruction>(V)) {
6826     // Don't attempt to analyze instructions in blocks that aren't
6827     // reachable. Such instructions don't matter, and they aren't required
6828     // to obey basic rules for definitions dominating uses which this
6829     // analysis depends on.
6830     if (!DT.isReachableFromEntry(I->getParent()))
6831       return getUnknown(UndefValue::get(V->getType()));
6832   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6833     return getConstant(CI);
6834   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6835     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6836   else if (!isa<ConstantExpr>(V))
6837     return getUnknown(V);
6838 
6839   Operator *U = cast<Operator>(V);
6840   if (auto BO = MatchBinaryOp(U, DT)) {
6841     switch (BO->Opcode) {
6842     case Instruction::Add: {
6843       // The simple thing to do would be to just call getSCEV on both operands
6844       // and call getAddExpr with the result. However if we're looking at a
6845       // bunch of things all added together, this can be quite inefficient,
6846       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6847       // Instead, gather up all the operands and make a single getAddExpr call.
6848       // LLVM IR canonical form means we need only traverse the left operands.
6849       SmallVector<const SCEV *, 4> AddOps;
6850       do {
6851         if (BO->Op) {
6852           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6853             AddOps.push_back(OpSCEV);
6854             break;
6855           }
6856 
6857           // If a NUW or NSW flag can be applied to the SCEV for this
6858           // addition, then compute the SCEV for this addition by itself
6859           // with a separate call to getAddExpr. We need to do that
6860           // instead of pushing the operands of the addition onto AddOps,
6861           // since the flags are only known to apply to this particular
6862           // addition - they may not apply to other additions that can be
6863           // formed with operands from AddOps.
6864           const SCEV *RHS = getSCEV(BO->RHS);
6865           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6866           if (Flags != SCEV::FlagAnyWrap) {
6867             const SCEV *LHS = getSCEV(BO->LHS);
6868             if (BO->Opcode == Instruction::Sub)
6869               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6870             else
6871               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6872             break;
6873           }
6874         }
6875 
6876         if (BO->Opcode == Instruction::Sub)
6877           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6878         else
6879           AddOps.push_back(getSCEV(BO->RHS));
6880 
6881         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6882         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6883                        NewBO->Opcode != Instruction::Sub)) {
6884           AddOps.push_back(getSCEV(BO->LHS));
6885           break;
6886         }
6887         BO = NewBO;
6888       } while (true);
6889 
6890       return getAddExpr(AddOps);
6891     }
6892 
6893     case Instruction::Mul: {
6894       SmallVector<const SCEV *, 4> MulOps;
6895       do {
6896         if (BO->Op) {
6897           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6898             MulOps.push_back(OpSCEV);
6899             break;
6900           }
6901 
6902           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6903           if (Flags != SCEV::FlagAnyWrap) {
6904             MulOps.push_back(
6905                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6906             break;
6907           }
6908         }
6909 
6910         MulOps.push_back(getSCEV(BO->RHS));
6911         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6912         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6913           MulOps.push_back(getSCEV(BO->LHS));
6914           break;
6915         }
6916         BO = NewBO;
6917       } while (true);
6918 
6919       return getMulExpr(MulOps);
6920     }
6921     case Instruction::UDiv:
6922       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6923     case Instruction::URem:
6924       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6925     case Instruction::Sub: {
6926       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6927       if (BO->Op)
6928         Flags = getNoWrapFlagsFromUB(BO->Op);
6929       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6930     }
6931     case Instruction::And:
6932       // For an expression like x&255 that merely masks off the high bits,
6933       // use zext(trunc(x)) as the SCEV expression.
6934       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6935         if (CI->isZero())
6936           return getSCEV(BO->RHS);
6937         if (CI->isMinusOne())
6938           return getSCEV(BO->LHS);
6939         const APInt &A = CI->getValue();
6940 
6941         // Instcombine's ShrinkDemandedConstant may strip bits out of
6942         // constants, obscuring what would otherwise be a low-bits mask.
6943         // Use computeKnownBits to compute what ShrinkDemandedConstant
6944         // knew about to reconstruct a low-bits mask value.
6945         unsigned LZ = A.countLeadingZeros();
6946         unsigned TZ = A.countTrailingZeros();
6947         unsigned BitWidth = A.getBitWidth();
6948         KnownBits Known(BitWidth);
6949         computeKnownBits(BO->LHS, Known, getDataLayout(),
6950                          0, &AC, nullptr, &DT);
6951 
6952         APInt EffectiveMask =
6953             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6954         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6955           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6956           const SCEV *LHS = getSCEV(BO->LHS);
6957           const SCEV *ShiftedLHS = nullptr;
6958           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6959             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6960               // For an expression like (x * 8) & 8, simplify the multiply.
6961               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6962               unsigned GCD = std::min(MulZeros, TZ);
6963               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6964               SmallVector<const SCEV*, 4> MulOps;
6965               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6966               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6967               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6968               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6969             }
6970           }
6971           if (!ShiftedLHS)
6972             ShiftedLHS = getUDivExpr(LHS, MulCount);
6973           return getMulExpr(
6974               getZeroExtendExpr(
6975                   getTruncateExpr(ShiftedLHS,
6976                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6977                   BO->LHS->getType()),
6978               MulCount);
6979         }
6980       }
6981       break;
6982 
6983     case Instruction::Or:
6984       // If the RHS of the Or is a constant, we may have something like:
6985       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6986       // optimizations will transparently handle this case.
6987       //
6988       // In order for this transformation to be safe, the LHS must be of the
6989       // form X*(2^n) and the Or constant must be less than 2^n.
6990       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6991         const SCEV *LHS = getSCEV(BO->LHS);
6992         const APInt &CIVal = CI->getValue();
6993         if (GetMinTrailingZeros(LHS) >=
6994             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6995           // Build a plain add SCEV.
6996           return getAddExpr(LHS, getSCEV(CI),
6997                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6998         }
6999       }
7000       break;
7001 
7002     case Instruction::Xor:
7003       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7004         // If the RHS of xor is -1, then this is a not operation.
7005         if (CI->isMinusOne())
7006           return getNotSCEV(getSCEV(BO->LHS));
7007 
7008         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7009         // This is a variant of the check for xor with -1, and it handles
7010         // the case where instcombine has trimmed non-demanded bits out
7011         // of an xor with -1.
7012         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7013           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7014             if (LBO->getOpcode() == Instruction::And &&
7015                 LCI->getValue() == CI->getValue())
7016               if (const SCEVZeroExtendExpr *Z =
7017                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7018                 Type *UTy = BO->LHS->getType();
7019                 const SCEV *Z0 = Z->getOperand();
7020                 Type *Z0Ty = Z0->getType();
7021                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7022 
7023                 // If C is a low-bits mask, the zero extend is serving to
7024                 // mask off the high bits. Complement the operand and
7025                 // re-apply the zext.
7026                 if (CI->getValue().isMask(Z0TySize))
7027                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7028 
7029                 // If C is a single bit, it may be in the sign-bit position
7030                 // before the zero-extend. In this case, represent the xor
7031                 // using an add, which is equivalent, and re-apply the zext.
7032                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7033                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7034                     Trunc.isSignMask())
7035                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7036                                            UTy);
7037               }
7038       }
7039       break;
7040 
7041     case Instruction::Shl:
7042       // Turn shift left of a constant amount into a multiply.
7043       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7044         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7045 
7046         // If the shift count is not less than the bitwidth, the result of
7047         // the shift is undefined. Don't try to analyze it, because the
7048         // resolution chosen here may differ from the resolution chosen in
7049         // other parts of the compiler.
7050         if (SA->getValue().uge(BitWidth))
7051           break;
7052 
7053         // We can safely preserve the nuw flag in all cases. It's also safe to
7054         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7055         // requires special handling. It can be preserved as long as we're not
7056         // left shifting by bitwidth - 1.
7057         auto Flags = SCEV::FlagAnyWrap;
7058         if (BO->Op) {
7059           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7060           if ((MulFlags & SCEV::FlagNSW) &&
7061               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7062             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7063           if (MulFlags & SCEV::FlagNUW)
7064             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7065         }
7066 
7067         Constant *X = ConstantInt::get(
7068             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7069         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
7070       }
7071       break;
7072 
7073     case Instruction::AShr: {
7074       // AShr X, C, where C is a constant.
7075       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7076       if (!CI)
7077         break;
7078 
7079       Type *OuterTy = BO->LHS->getType();
7080       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7081       // If the shift count is not less than the bitwidth, the result of
7082       // the shift is undefined. Don't try to analyze it, because the
7083       // resolution chosen here may differ from the resolution chosen in
7084       // other parts of the compiler.
7085       if (CI->getValue().uge(BitWidth))
7086         break;
7087 
7088       if (CI->isZero())
7089         return getSCEV(BO->LHS); // shift by zero --> noop
7090 
7091       uint64_t AShrAmt = CI->getZExtValue();
7092       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7093 
7094       Operator *L = dyn_cast<Operator>(BO->LHS);
7095       if (L && L->getOpcode() == Instruction::Shl) {
7096         // X = Shl A, n
7097         // Y = AShr X, m
7098         // Both n and m are constant.
7099 
7100         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7101         if (L->getOperand(1) == BO->RHS)
7102           // For a two-shift sext-inreg, i.e. n = m,
7103           // use sext(trunc(x)) as the SCEV expression.
7104           return getSignExtendExpr(
7105               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7106 
7107         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7108         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7109           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7110           if (ShlAmt > AShrAmt) {
7111             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7112             // expression. We already checked that ShlAmt < BitWidth, so
7113             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7114             // ShlAmt - AShrAmt < Amt.
7115             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7116                                             ShlAmt - AShrAmt);
7117             return getSignExtendExpr(
7118                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7119                 getConstant(Mul)), OuterTy);
7120           }
7121         }
7122       }
7123       break;
7124     }
7125     }
7126   }
7127 
7128   switch (U->getOpcode()) {
7129   case Instruction::Trunc:
7130     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7131 
7132   case Instruction::ZExt:
7133     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7134 
7135   case Instruction::SExt:
7136     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7137       // The NSW flag of a subtract does not always survive the conversion to
7138       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7139       // more likely to preserve NSW and allow later AddRec optimisations.
7140       //
7141       // NOTE: This is effectively duplicating this logic from getSignExtend:
7142       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7143       // but by that point the NSW information has potentially been lost.
7144       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7145         Type *Ty = U->getType();
7146         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7147         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7148         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7149       }
7150     }
7151     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7152 
7153   case Instruction::BitCast:
7154     // BitCasts are no-op casts so we just eliminate the cast.
7155     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7156       return getSCEV(U->getOperand(0));
7157     break;
7158 
7159   case Instruction::PtrToInt: {
7160     // Pointer to integer cast is straight-forward, so do model it.
7161     const SCEV *Op = getSCEV(U->getOperand(0));
7162     Type *DstIntTy = U->getType();
7163     // But only if effective SCEV (integer) type is wide enough to represent
7164     // all possible pointer values.
7165     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7166     if (isa<SCEVCouldNotCompute>(IntOp))
7167       return getUnknown(V);
7168     return IntOp;
7169   }
7170   case Instruction::IntToPtr:
7171     // Just don't deal with inttoptr casts.
7172     return getUnknown(V);
7173 
7174   case Instruction::SDiv:
7175     // If both operands are non-negative, this is just an udiv.
7176     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7177         isKnownNonNegative(getSCEV(U->getOperand(1))))
7178       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7179     break;
7180 
7181   case Instruction::SRem:
7182     // If both operands are non-negative, this is just an urem.
7183     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7184         isKnownNonNegative(getSCEV(U->getOperand(1))))
7185       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7186     break;
7187 
7188   case Instruction::GetElementPtr:
7189     return createNodeForGEP(cast<GEPOperator>(U));
7190 
7191   case Instruction::PHI:
7192     return createNodeForPHI(cast<PHINode>(U));
7193 
7194   case Instruction::Select:
7195     // U can also be a select constant expr, which let fall through.  Since
7196     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
7197     // constant expressions cannot have instructions as operands, we'd have
7198     // returned getUnknown for a select constant expressions anyway.
7199     if (isa<Instruction>(U))
7200       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
7201                                       U->getOperand(1), U->getOperand(2));
7202     break;
7203 
7204   case Instruction::Call:
7205   case Instruction::Invoke:
7206     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7207       return getSCEV(RV);
7208 
7209     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7210       switch (II->getIntrinsicID()) {
7211       case Intrinsic::abs:
7212         return getAbsExpr(
7213             getSCEV(II->getArgOperand(0)),
7214             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7215       case Intrinsic::umax:
7216         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7217                            getSCEV(II->getArgOperand(1)));
7218       case Intrinsic::umin:
7219         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7220                            getSCEV(II->getArgOperand(1)));
7221       case Intrinsic::smax:
7222         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7223                            getSCEV(II->getArgOperand(1)));
7224       case Intrinsic::smin:
7225         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7226                            getSCEV(II->getArgOperand(1)));
7227       case Intrinsic::usub_sat: {
7228         const SCEV *X = getSCEV(II->getArgOperand(0));
7229         const SCEV *Y = getSCEV(II->getArgOperand(1));
7230         const SCEV *ClampedY = getUMinExpr(X, Y);
7231         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7232       }
7233       case Intrinsic::uadd_sat: {
7234         const SCEV *X = getSCEV(II->getArgOperand(0));
7235         const SCEV *Y = getSCEV(II->getArgOperand(1));
7236         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7237         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7238       }
7239       case Intrinsic::start_loop_iterations:
7240         // A start_loop_iterations is just equivalent to the first operand for
7241         // SCEV purposes.
7242         return getSCEV(II->getArgOperand(0));
7243       default:
7244         break;
7245       }
7246     }
7247     break;
7248   }
7249 
7250   return getUnknown(V);
7251 }
7252 
7253 //===----------------------------------------------------------------------===//
7254 //                   Iteration Count Computation Code
7255 //
7256 
7257 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
7258                                                        bool Extend) {
7259   if (isa<SCEVCouldNotCompute>(ExitCount))
7260     return getCouldNotCompute();
7261 
7262   auto *ExitCountType = ExitCount->getType();
7263   assert(ExitCountType->isIntegerTy());
7264 
7265   if (!Extend)
7266     return getAddExpr(ExitCount, getOne(ExitCountType));
7267 
7268   auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
7269                                     1 + ExitCountType->getScalarSizeInBits());
7270   return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
7271                     getOne(WiderType));
7272 }
7273 
7274 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7275   if (!ExitCount)
7276     return 0;
7277 
7278   ConstantInt *ExitConst = ExitCount->getValue();
7279 
7280   // Guard against huge trip counts.
7281   if (ExitConst->getValue().getActiveBits() > 32)
7282     return 0;
7283 
7284   // In case of integer overflow, this returns 0, which is correct.
7285   return ((unsigned)ExitConst->getZExtValue()) + 1;
7286 }
7287 
7288 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7289   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7290   return getConstantTripCount(ExitCount);
7291 }
7292 
7293 unsigned
7294 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7295                                            const BasicBlock *ExitingBlock) {
7296   assert(ExitingBlock && "Must pass a non-null exiting block!");
7297   assert(L->isLoopExiting(ExitingBlock) &&
7298          "Exiting block must actually branch out of the loop!");
7299   const SCEVConstant *ExitCount =
7300       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7301   return getConstantTripCount(ExitCount);
7302 }
7303 
7304 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7305   const auto *MaxExitCount =
7306       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7307   return getConstantTripCount(MaxExitCount);
7308 }
7309 
7310 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
7311   // We can't infer from Array in Irregular Loop.
7312   // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
7313   if (!L->isLoopSimplifyForm() || !L->isInnermost())
7314     return getCouldNotCompute();
7315 
7316   // FIXME: To make the scene more typical, we only analysis loops that have
7317   // one exiting block and that block must be the latch. To make it easier to
7318   // capture loops that have memory access and memory access will be executed
7319   // in each iteration.
7320   const BasicBlock *LoopLatch = L->getLoopLatch();
7321   assert(LoopLatch && "See defination of simplify form loop.");
7322   if (L->getExitingBlock() != LoopLatch)
7323     return getCouldNotCompute();
7324 
7325   const DataLayout &DL = getDataLayout();
7326   SmallVector<const SCEV *> InferCountColl;
7327   for (auto *BB : L->getBlocks()) {
7328     // Go here, we can know that Loop is a single exiting and simplified form
7329     // loop. Make sure that infer from Memory Operation in those BBs must be
7330     // executed in loop. First step, we can make sure that max execution time
7331     // of MemAccessBB in loop represents latch max excution time.
7332     // If MemAccessBB does not dom Latch, skip.
7333     //            Entry
7334     //              │
7335     //        ┌─────▼─────┐
7336     //        │Loop Header◄─────┐
7337     //        └──┬──────┬─┘     │
7338     //           │      │       │
7339     //  ┌────────▼──┐ ┌─▼─────┐ │
7340     //  │MemAccessBB│ │OtherBB│ │
7341     //  └────────┬──┘ └─┬─────┘ │
7342     //           │      │       │
7343     //         ┌─▼──────▼─┐     │
7344     //         │Loop Latch├─────┘
7345     //         └────┬─────┘
7346     //              ▼
7347     //             Exit
7348     if (!DT.dominates(BB, LoopLatch))
7349       continue;
7350 
7351     for (Instruction &Inst : *BB) {
7352       // Find Memory Operation Instruction.
7353       auto *GEP = getLoadStorePointerOperand(&Inst);
7354       if (!GEP)
7355         continue;
7356 
7357       auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
7358       // Do not infer from scalar type, eg."ElemSize = sizeof()".
7359       if (!ElemSize)
7360         continue;
7361 
7362       // Use a existing polynomial recurrence on the trip count.
7363       auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
7364       if (!AddRec)
7365         continue;
7366       auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
7367       auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
7368       if (!ArrBase || !Step)
7369         continue;
7370       assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
7371 
7372       // Only handle { %array + step },
7373       // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
7374       if (AddRec->getStart() != ArrBase)
7375         continue;
7376 
7377       // Memory operation pattern which have gaps.
7378       // Or repeat memory opreation.
7379       // And index of GEP wraps arround.
7380       if (Step->getAPInt().getActiveBits() > 32 ||
7381           Step->getAPInt().getZExtValue() !=
7382               ElemSize->getAPInt().getZExtValue() ||
7383           Step->isZero() || Step->getAPInt().isNegative())
7384         continue;
7385 
7386       // Only infer from stack array which has certain size.
7387       // Make sure alloca instruction is not excuted in loop.
7388       AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
7389       if (!AllocateInst || L->contains(AllocateInst->getParent()))
7390         continue;
7391 
7392       // Make sure only handle normal array.
7393       auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
7394       auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
7395       if (!Ty || !ArrSize || !ArrSize->isOne())
7396         continue;
7397       // Also make sure step was increased the same with sizeof allocated
7398       // element type.
7399       const PointerType *GEPT = dyn_cast<PointerType>(GEP->getType());
7400       if (Ty->getElementType() != GEPT->getElementType())
7401         continue;
7402 
7403       // FIXME: Since gep indices are silently zext to the indexing type,
7404       // we will have a narrow gep index which wraps around rather than
7405       // increasing strictly, we shoule ensure that step is increasing
7406       // strictly by the loop iteration.
7407       // Now we can infer a max execution time by MemLength/StepLength.
7408       const SCEV *MemSize =
7409           getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
7410       auto *MaxExeCount =
7411           dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
7412       if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
7413         continue;
7414 
7415       // If the loop reaches the maximum number of executions, we can not
7416       // access bytes starting outside the statically allocated size without
7417       // being immediate UB. But it is allowed to enter loop header one more
7418       // time.
7419       auto *InferCount = dyn_cast<SCEVConstant>(
7420           getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
7421       // Discard the maximum number of execution times under 32bits.
7422       if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
7423         continue;
7424 
7425       InferCountColl.push_back(InferCount);
7426     }
7427   }
7428 
7429   if (InferCountColl.size() == 0)
7430     return getCouldNotCompute();
7431 
7432   return getUMinFromMismatchedTypes(InferCountColl);
7433 }
7434 
7435 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7436   SmallVector<BasicBlock *, 8> ExitingBlocks;
7437   L->getExitingBlocks(ExitingBlocks);
7438 
7439   Optional<unsigned> Res = None;
7440   for (auto *ExitingBB : ExitingBlocks) {
7441     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7442     if (!Res)
7443       Res = Multiple;
7444     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7445   }
7446   return Res.getValueOr(1);
7447 }
7448 
7449 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7450                                                        const SCEV *ExitCount) {
7451   if (ExitCount == getCouldNotCompute())
7452     return 1;
7453 
7454   // Get the trip count
7455   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7456 
7457   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7458   if (!TC)
7459     // Attempt to factor more general cases. Returns the greatest power of
7460     // two divisor. If overflow happens, the trip count expression is still
7461     // divisible by the greatest power of 2 divisor returned.
7462     return 1U << std::min((uint32_t)31,
7463                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7464 
7465   ConstantInt *Result = TC->getValue();
7466 
7467   // Guard against huge trip counts (this requires checking
7468   // for zero to handle the case where the trip count == -1 and the
7469   // addition wraps).
7470   if (!Result || Result->getValue().getActiveBits() > 32 ||
7471       Result->getValue().getActiveBits() == 0)
7472     return 1;
7473 
7474   return (unsigned)Result->getZExtValue();
7475 }
7476 
7477 /// Returns the largest constant divisor of the trip count of this loop as a
7478 /// normal unsigned value, if possible. This means that the actual trip count is
7479 /// always a multiple of the returned value (don't forget the trip count could
7480 /// very well be zero as well!).
7481 ///
7482 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7483 /// multiple of a constant (which is also the case if the trip count is simply
7484 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7485 /// if the trip count is very large (>= 2^32).
7486 ///
7487 /// As explained in the comments for getSmallConstantTripCount, this assumes
7488 /// that control exits the loop via ExitingBlock.
7489 unsigned
7490 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7491                                               const BasicBlock *ExitingBlock) {
7492   assert(ExitingBlock && "Must pass a non-null exiting block!");
7493   assert(L->isLoopExiting(ExitingBlock) &&
7494          "Exiting block must actually branch out of the loop!");
7495   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7496   return getSmallConstantTripMultiple(L, ExitCount);
7497 }
7498 
7499 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7500                                           const BasicBlock *ExitingBlock,
7501                                           ExitCountKind Kind) {
7502   switch (Kind) {
7503   case Exact:
7504   case SymbolicMaximum:
7505     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7506   case ConstantMaximum:
7507     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7508   };
7509   llvm_unreachable("Invalid ExitCountKind!");
7510 }
7511 
7512 const SCEV *
7513 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7514                                                  SCEVUnionPredicate &Preds) {
7515   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7516 }
7517 
7518 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7519                                                    ExitCountKind Kind) {
7520   switch (Kind) {
7521   case Exact:
7522     return getBackedgeTakenInfo(L).getExact(L, this);
7523   case ConstantMaximum:
7524     return getBackedgeTakenInfo(L).getConstantMax(this);
7525   case SymbolicMaximum:
7526     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7527   };
7528   llvm_unreachable("Invalid ExitCountKind!");
7529 }
7530 
7531 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7532   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7533 }
7534 
7535 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7536 static void PushLoopPHIs(const Loop *L,
7537                          SmallVectorImpl<Instruction *> &Worklist,
7538                          SmallPtrSetImpl<Instruction *> &Visited) {
7539   BasicBlock *Header = L->getHeader();
7540 
7541   // Push all Loop-header PHIs onto the Worklist stack.
7542   for (PHINode &PN : Header->phis())
7543     if (Visited.insert(&PN).second)
7544       Worklist.push_back(&PN);
7545 }
7546 
7547 const ScalarEvolution::BackedgeTakenInfo &
7548 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7549   auto &BTI = getBackedgeTakenInfo(L);
7550   if (BTI.hasFullInfo())
7551     return BTI;
7552 
7553   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7554 
7555   if (!Pair.second)
7556     return Pair.first->second;
7557 
7558   BackedgeTakenInfo Result =
7559       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7560 
7561   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7562 }
7563 
7564 ScalarEvolution::BackedgeTakenInfo &
7565 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7566   // Initially insert an invalid entry for this loop. If the insertion
7567   // succeeds, proceed to actually compute a backedge-taken count and
7568   // update the value. The temporary CouldNotCompute value tells SCEV
7569   // code elsewhere that it shouldn't attempt to request a new
7570   // backedge-taken count, which could result in infinite recursion.
7571   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7572       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7573   if (!Pair.second)
7574     return Pair.first->second;
7575 
7576   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7577   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7578   // must be cleared in this scope.
7579   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7580 
7581   // In product build, there are no usage of statistic.
7582   (void)NumTripCountsComputed;
7583   (void)NumTripCountsNotComputed;
7584 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7585   const SCEV *BEExact = Result.getExact(L, this);
7586   if (BEExact != getCouldNotCompute()) {
7587     assert(isLoopInvariant(BEExact, L) &&
7588            isLoopInvariant(Result.getConstantMax(this), L) &&
7589            "Computed backedge-taken count isn't loop invariant for loop!");
7590     ++NumTripCountsComputed;
7591   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7592              isa<PHINode>(L->getHeader()->begin())) {
7593     // Only count loops that have phi nodes as not being computable.
7594     ++NumTripCountsNotComputed;
7595   }
7596 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7597 
7598   // Now that we know more about the trip count for this loop, forget any
7599   // existing SCEV values for PHI nodes in this loop since they are only
7600   // conservative estimates made without the benefit of trip count
7601   // information. This is similar to the code in forgetLoop, except that
7602   // it handles SCEVUnknown PHI nodes specially.
7603   if (Result.hasAnyInfo()) {
7604     SmallVector<Instruction *, 16> Worklist;
7605     SmallPtrSet<Instruction *, 8> Discovered;
7606     SmallVector<const SCEV *, 8> ToForget;
7607     PushLoopPHIs(L, Worklist, Discovered);
7608     while (!Worklist.empty()) {
7609       Instruction *I = Worklist.pop_back_val();
7610 
7611       ValueExprMapType::iterator It =
7612         ValueExprMap.find_as(static_cast<Value *>(I));
7613       if (It != ValueExprMap.end()) {
7614         const SCEV *Old = It->second;
7615 
7616         // SCEVUnknown for a PHI either means that it has an unrecognized
7617         // structure, or it's a PHI that's in the progress of being computed
7618         // by createNodeForPHI.  In the former case, additional loop trip
7619         // count information isn't going to change anything. In the later
7620         // case, createNodeForPHI will perform the necessary updates on its
7621         // own when it gets to that point.
7622         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7623           eraseValueFromMap(It->first);
7624           ToForget.push_back(Old);
7625         }
7626         if (PHINode *PN = dyn_cast<PHINode>(I))
7627           ConstantEvolutionLoopExitValue.erase(PN);
7628       }
7629 
7630       // Since we don't need to invalidate anything for correctness and we're
7631       // only invalidating to make SCEV's results more precise, we get to stop
7632       // early to avoid invalidating too much.  This is especially important in
7633       // cases like:
7634       //
7635       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7636       // loop0:
7637       //   %pn0 = phi
7638       //   ...
7639       // loop1:
7640       //   %pn1 = phi
7641       //   ...
7642       //
7643       // where both loop0 and loop1's backedge taken count uses the SCEV
7644       // expression for %v.  If we don't have the early stop below then in cases
7645       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7646       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7647       // count for loop1, effectively nullifying SCEV's trip count cache.
7648       for (auto *U : I->users())
7649         if (auto *I = dyn_cast<Instruction>(U)) {
7650           auto *LoopForUser = LI.getLoopFor(I->getParent());
7651           if (LoopForUser && L->contains(LoopForUser) &&
7652               Discovered.insert(I).second)
7653             Worklist.push_back(I);
7654         }
7655     }
7656     forgetMemoizedResults(ToForget);
7657   }
7658 
7659   // Re-lookup the insert position, since the call to
7660   // computeBackedgeTakenCount above could result in a
7661   // recusive call to getBackedgeTakenInfo (on a different
7662   // loop), which would invalidate the iterator computed
7663   // earlier.
7664   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7665 }
7666 
7667 void ScalarEvolution::forgetAllLoops() {
7668   // This method is intended to forget all info about loops. It should
7669   // invalidate caches as if the following happened:
7670   // - The trip counts of all loops have changed arbitrarily
7671   // - Every llvm::Value has been updated in place to produce a different
7672   // result.
7673   BackedgeTakenCounts.clear();
7674   PredicatedBackedgeTakenCounts.clear();
7675   LoopPropertiesCache.clear();
7676   ConstantEvolutionLoopExitValue.clear();
7677   ValueExprMap.clear();
7678   ValuesAtScopes.clear();
7679   LoopDispositions.clear();
7680   BlockDispositions.clear();
7681   UnsignedRanges.clear();
7682   SignedRanges.clear();
7683   ExprValueMap.clear();
7684   HasRecMap.clear();
7685   MinTrailingZerosCache.clear();
7686   PredicatedSCEVRewrites.clear();
7687 }
7688 
7689 void ScalarEvolution::forgetLoop(const Loop *L) {
7690   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7691   SmallVector<Instruction *, 32> Worklist;
7692   SmallPtrSet<Instruction *, 16> Visited;
7693   SmallVector<const SCEV *, 16> ToForget;
7694 
7695   // Iterate over all the loops and sub-loops to drop SCEV information.
7696   while (!LoopWorklist.empty()) {
7697     auto *CurrL = LoopWorklist.pop_back_val();
7698 
7699     // Drop any stored trip count value.
7700     BackedgeTakenCounts.erase(CurrL);
7701     PredicatedBackedgeTakenCounts.erase(CurrL);
7702 
7703     // Drop information about predicated SCEV rewrites for this loop.
7704     for (auto I = PredicatedSCEVRewrites.begin();
7705          I != PredicatedSCEVRewrites.end();) {
7706       std::pair<const SCEV *, const Loop *> Entry = I->first;
7707       if (Entry.second == CurrL)
7708         PredicatedSCEVRewrites.erase(I++);
7709       else
7710         ++I;
7711     }
7712 
7713     auto LoopUsersItr = LoopUsers.find(CurrL);
7714     if (LoopUsersItr != LoopUsers.end()) {
7715       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
7716                 LoopUsersItr->second.end());
7717       LoopUsers.erase(LoopUsersItr);
7718     }
7719 
7720     // Drop information about expressions based on loop-header PHIs.
7721     PushLoopPHIs(CurrL, Worklist, Visited);
7722 
7723     while (!Worklist.empty()) {
7724       Instruction *I = Worklist.pop_back_val();
7725 
7726       ValueExprMapType::iterator It =
7727           ValueExprMap.find_as(static_cast<Value *>(I));
7728       if (It != ValueExprMap.end()) {
7729         eraseValueFromMap(It->first);
7730         ToForget.push_back(It->second);
7731         if (PHINode *PN = dyn_cast<PHINode>(I))
7732           ConstantEvolutionLoopExitValue.erase(PN);
7733       }
7734 
7735       PushDefUseChildren(I, Worklist, Visited);
7736     }
7737 
7738     LoopPropertiesCache.erase(CurrL);
7739     // Forget all contained loops too, to avoid dangling entries in the
7740     // ValuesAtScopes map.
7741     LoopWorklist.append(CurrL->begin(), CurrL->end());
7742   }
7743   forgetMemoizedResults(ToForget);
7744 }
7745 
7746 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7747   while (Loop *Parent = L->getParentLoop())
7748     L = Parent;
7749   forgetLoop(L);
7750 }
7751 
7752 void ScalarEvolution::forgetValue(Value *V) {
7753   Instruction *I = dyn_cast<Instruction>(V);
7754   if (!I) return;
7755 
7756   // Drop information about expressions based on loop-header PHIs.
7757   SmallVector<Instruction *, 16> Worklist;
7758   SmallPtrSet<Instruction *, 8> Visited;
7759   SmallVector<const SCEV *, 8> ToForget;
7760   Worklist.push_back(I);
7761   Visited.insert(I);
7762 
7763   while (!Worklist.empty()) {
7764     I = Worklist.pop_back_val();
7765     ValueExprMapType::iterator It =
7766       ValueExprMap.find_as(static_cast<Value *>(I));
7767     if (It != ValueExprMap.end()) {
7768       eraseValueFromMap(It->first);
7769       ToForget.push_back(It->second);
7770       if (PHINode *PN = dyn_cast<PHINode>(I))
7771         ConstantEvolutionLoopExitValue.erase(PN);
7772     }
7773 
7774     PushDefUseChildren(I, Worklist, Visited);
7775   }
7776   forgetMemoizedResults(ToForget);
7777 }
7778 
7779 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7780   LoopDispositions.clear();
7781 }
7782 
7783 /// Get the exact loop backedge taken count considering all loop exits. A
7784 /// computable result can only be returned for loops with all exiting blocks
7785 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7786 /// is never skipped. This is a valid assumption as long as the loop exits via
7787 /// that test. For precise results, it is the caller's responsibility to specify
7788 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7789 const SCEV *
7790 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7791                                              SCEVUnionPredicate *Preds) const {
7792   // If any exits were not computable, the loop is not computable.
7793   if (!isComplete() || ExitNotTaken.empty())
7794     return SE->getCouldNotCompute();
7795 
7796   const BasicBlock *Latch = L->getLoopLatch();
7797   // All exiting blocks we have collected must dominate the only backedge.
7798   if (!Latch)
7799     return SE->getCouldNotCompute();
7800 
7801   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7802   // count is simply a minimum out of all these calculated exit counts.
7803   SmallVector<const SCEV *, 2> Ops;
7804   for (auto &ENT : ExitNotTaken) {
7805     const SCEV *BECount = ENT.ExactNotTaken;
7806     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7807     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7808            "We should only have known counts for exiting blocks that dominate "
7809            "latch!");
7810 
7811     Ops.push_back(BECount);
7812 
7813     if (Preds && !ENT.hasAlwaysTruePredicate())
7814       Preds->add(ENT.Predicate.get());
7815 
7816     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7817            "Predicate should be always true!");
7818   }
7819 
7820   return SE->getUMinFromMismatchedTypes(Ops);
7821 }
7822 
7823 /// Get the exact not taken count for this loop exit.
7824 const SCEV *
7825 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7826                                              ScalarEvolution *SE) const {
7827   for (auto &ENT : ExitNotTaken)
7828     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7829       return ENT.ExactNotTaken;
7830 
7831   return SE->getCouldNotCompute();
7832 }
7833 
7834 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7835     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7836   for (auto &ENT : ExitNotTaken)
7837     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7838       return ENT.MaxNotTaken;
7839 
7840   return SE->getCouldNotCompute();
7841 }
7842 
7843 /// getConstantMax - Get the constant max backedge taken count for the loop.
7844 const SCEV *
7845 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7846   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7847     return !ENT.hasAlwaysTruePredicate();
7848   };
7849 
7850   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
7851     return SE->getCouldNotCompute();
7852 
7853   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7854           isa<SCEVConstant>(getConstantMax())) &&
7855          "No point in having a non-constant max backedge taken count!");
7856   return getConstantMax();
7857 }
7858 
7859 const SCEV *
7860 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7861                                                    ScalarEvolution *SE) {
7862   if (!SymbolicMax)
7863     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7864   return SymbolicMax;
7865 }
7866 
7867 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7868     ScalarEvolution *SE) const {
7869   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7870     return !ENT.hasAlwaysTruePredicate();
7871   };
7872   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7873 }
7874 
7875 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const {
7876   return Operands.contains(S);
7877 }
7878 
7879 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7880     : ExitLimit(E, E, false, None) {
7881 }
7882 
7883 ScalarEvolution::ExitLimit::ExitLimit(
7884     const SCEV *E, const SCEV *M, bool MaxOrZero,
7885     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7886     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7887   // If we prove the max count is zero, so is the symbolic bound.  This happens
7888   // in practice due to differences in a) how context sensitive we've chosen
7889   // to be and b) how we reason about bounds impied by UB.
7890   if (MaxNotTaken->isZero())
7891     ExactNotTaken = MaxNotTaken;
7892 
7893   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7894           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7895          "Exact is not allowed to be less precise than Max");
7896   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7897           isa<SCEVConstant>(MaxNotTaken)) &&
7898          "No point in having a non-constant max backedge taken count!");
7899   for (auto *PredSet : PredSetList)
7900     for (auto *P : *PredSet)
7901       addPredicate(P);
7902   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
7903          "Backedge count should be int");
7904   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
7905          "Max backedge count should be int");
7906 }
7907 
7908 ScalarEvolution::ExitLimit::ExitLimit(
7909     const SCEV *E, const SCEV *M, bool MaxOrZero,
7910     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7911     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7912 }
7913 
7914 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7915                                       bool MaxOrZero)
7916     : ExitLimit(E, M, MaxOrZero, None) {
7917 }
7918 
7919 class SCEVRecordOperands {
7920   SmallPtrSetImpl<const SCEV *> &Operands;
7921 
7922 public:
7923   SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands)
7924     : Operands(Operands) {}
7925   bool follow(const SCEV *S) {
7926     Operands.insert(S);
7927     return true;
7928   }
7929   bool isDone() { return false; }
7930 };
7931 
7932 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7933 /// computable exit into a persistent ExitNotTakenInfo array.
7934 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7935     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7936     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7937     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7938   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7939 
7940   ExitNotTaken.reserve(ExitCounts.size());
7941   std::transform(
7942       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7943       [&](const EdgeExitInfo &EEI) {
7944         BasicBlock *ExitBB = EEI.first;
7945         const ExitLimit &EL = EEI.second;
7946         if (EL.Predicates.empty())
7947           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7948                                   nullptr);
7949 
7950         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7951         for (auto *Pred : EL.Predicates)
7952           Predicate->add(Pred);
7953 
7954         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7955                                 std::move(Predicate));
7956       });
7957   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7958           isa<SCEVConstant>(ConstantMax)) &&
7959          "No point in having a non-constant max backedge taken count!");
7960 
7961   SCEVRecordOperands RecordOperands(Operands);
7962   SCEVTraversal<SCEVRecordOperands> ST(RecordOperands);
7963   if (!isa<SCEVCouldNotCompute>(ConstantMax))
7964     ST.visitAll(ConstantMax);
7965   for (auto &ENT : ExitNotTaken)
7966     if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken))
7967       ST.visitAll(ENT.ExactNotTaken);
7968 }
7969 
7970 /// Compute the number of times the backedge of the specified loop will execute.
7971 ScalarEvolution::BackedgeTakenInfo
7972 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7973                                            bool AllowPredicates) {
7974   SmallVector<BasicBlock *, 8> ExitingBlocks;
7975   L->getExitingBlocks(ExitingBlocks);
7976 
7977   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7978 
7979   SmallVector<EdgeExitInfo, 4> ExitCounts;
7980   bool CouldComputeBECount = true;
7981   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7982   const SCEV *MustExitMaxBECount = nullptr;
7983   const SCEV *MayExitMaxBECount = nullptr;
7984   bool MustExitMaxOrZero = false;
7985 
7986   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7987   // and compute maxBECount.
7988   // Do a union of all the predicates here.
7989   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7990     BasicBlock *ExitBB = ExitingBlocks[i];
7991 
7992     // We canonicalize untaken exits to br (constant), ignore them so that
7993     // proving an exit untaken doesn't negatively impact our ability to reason
7994     // about the loop as whole.
7995     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7996       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7997         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7998         if (ExitIfTrue == CI->isZero())
7999           continue;
8000       }
8001 
8002     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8003 
8004     assert((AllowPredicates || EL.Predicates.empty()) &&
8005            "Predicated exit limit when predicates are not allowed!");
8006 
8007     // 1. For each exit that can be computed, add an entry to ExitCounts.
8008     // CouldComputeBECount is true only if all exits can be computed.
8009     if (EL.ExactNotTaken == getCouldNotCompute())
8010       // We couldn't compute an exact value for this exit, so
8011       // we won't be able to compute an exact value for the loop.
8012       CouldComputeBECount = false;
8013     else
8014       ExitCounts.emplace_back(ExitBB, EL);
8015 
8016     // 2. Derive the loop's MaxBECount from each exit's max number of
8017     // non-exiting iterations. Partition the loop exits into two kinds:
8018     // LoopMustExits and LoopMayExits.
8019     //
8020     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8021     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8022     // MaxBECount is the minimum EL.MaxNotTaken of computable
8023     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8024     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
8025     // computable EL.MaxNotTaken.
8026     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
8027         DT.dominates(ExitBB, Latch)) {
8028       if (!MustExitMaxBECount) {
8029         MustExitMaxBECount = EL.MaxNotTaken;
8030         MustExitMaxOrZero = EL.MaxOrZero;
8031       } else {
8032         MustExitMaxBECount =
8033             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
8034       }
8035     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8036       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
8037         MayExitMaxBECount = EL.MaxNotTaken;
8038       else {
8039         MayExitMaxBECount =
8040             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
8041       }
8042     }
8043   }
8044   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8045     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8046   // The loop backedge will be taken the maximum or zero times if there's
8047   // a single exit that must be taken the maximum or zero times.
8048   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8049   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8050                            MaxBECount, MaxOrZero);
8051 }
8052 
8053 ScalarEvolution::ExitLimit
8054 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8055                                       bool AllowPredicates) {
8056   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8057   // If our exiting block does not dominate the latch, then its connection with
8058   // loop's exit limit may be far from trivial.
8059   const BasicBlock *Latch = L->getLoopLatch();
8060   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8061     return getCouldNotCompute();
8062 
8063   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8064   Instruction *Term = ExitingBlock->getTerminator();
8065   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8066     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8067     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8068     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8069            "It should have one successor in loop and one exit block!");
8070     // Proceed to the next level to examine the exit condition expression.
8071     return computeExitLimitFromCond(
8072         L, BI->getCondition(), ExitIfTrue,
8073         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8074   }
8075 
8076   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8077     // For switch, make sure that there is a single exit from the loop.
8078     BasicBlock *Exit = nullptr;
8079     for (auto *SBB : successors(ExitingBlock))
8080       if (!L->contains(SBB)) {
8081         if (Exit) // Multiple exit successors.
8082           return getCouldNotCompute();
8083         Exit = SBB;
8084       }
8085     assert(Exit && "Exiting block must have at least one exit");
8086     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8087                                                 /*ControlsExit=*/IsOnlyExit);
8088   }
8089 
8090   return getCouldNotCompute();
8091 }
8092 
8093 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8094     const Loop *L, Value *ExitCond, bool ExitIfTrue,
8095     bool ControlsExit, bool AllowPredicates) {
8096   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8097   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8098                                         ControlsExit, AllowPredicates);
8099 }
8100 
8101 Optional<ScalarEvolution::ExitLimit>
8102 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8103                                       bool ExitIfTrue, bool ControlsExit,
8104                                       bool AllowPredicates) {
8105   (void)this->L;
8106   (void)this->ExitIfTrue;
8107   (void)this->AllowPredicates;
8108 
8109   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8110          this->AllowPredicates == AllowPredicates &&
8111          "Variance in assumed invariant key components!");
8112   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8113   if (Itr == TripCountMap.end())
8114     return None;
8115   return Itr->second;
8116 }
8117 
8118 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8119                                              bool ExitIfTrue,
8120                                              bool ControlsExit,
8121                                              bool AllowPredicates,
8122                                              const ExitLimit &EL) {
8123   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8124          this->AllowPredicates == AllowPredicates &&
8125          "Variance in assumed invariant key components!");
8126 
8127   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8128   assert(InsertResult.second && "Expected successful insertion!");
8129   (void)InsertResult;
8130   (void)ExitIfTrue;
8131 }
8132 
8133 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8134     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8135     bool ControlsExit, bool AllowPredicates) {
8136 
8137   if (auto MaybeEL =
8138           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8139     return *MaybeEL;
8140 
8141   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8142                                               ControlsExit, AllowPredicates);
8143   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8144   return EL;
8145 }
8146 
8147 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8148     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8149     bool ControlsExit, bool AllowPredicates) {
8150   // Handle BinOp conditions (And, Or).
8151   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8152           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8153     return *LimitFromBinOp;
8154 
8155   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8156   // Proceed to the next level to examine the icmp.
8157   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8158     ExitLimit EL =
8159         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8160     if (EL.hasFullInfo() || !AllowPredicates)
8161       return EL;
8162 
8163     // Try again, but use SCEV predicates this time.
8164     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8165                                     /*AllowPredicates=*/true);
8166   }
8167 
8168   // Check for a constant condition. These are normally stripped out by
8169   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8170   // preserve the CFG and is temporarily leaving constant conditions
8171   // in place.
8172   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8173     if (ExitIfTrue == !CI->getZExtValue())
8174       // The backedge is always taken.
8175       return getCouldNotCompute();
8176     else
8177       // The backedge is never taken.
8178       return getZero(CI->getType());
8179   }
8180 
8181   // If it's not an integer or pointer comparison then compute it the hard way.
8182   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8183 }
8184 
8185 Optional<ScalarEvolution::ExitLimit>
8186 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8187     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8188     bool ControlsExit, bool AllowPredicates) {
8189   // Check if the controlling expression for this loop is an And or Or.
8190   Value *Op0, *Op1;
8191   bool IsAnd = false;
8192   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8193     IsAnd = true;
8194   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8195     IsAnd = false;
8196   else
8197     return None;
8198 
8199   // EitherMayExit is true in these two cases:
8200   //   br (and Op0 Op1), loop, exit
8201   //   br (or  Op0 Op1), exit, loop
8202   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8203   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
8204                                                  ControlsExit && !EitherMayExit,
8205                                                  AllowPredicates);
8206   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
8207                                                  ControlsExit && !EitherMayExit,
8208                                                  AllowPredicates);
8209 
8210   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8211   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8212   if (isa<ConstantInt>(Op1))
8213     return Op1 == NeutralElement ? EL0 : EL1;
8214   if (isa<ConstantInt>(Op0))
8215     return Op0 == NeutralElement ? EL1 : EL0;
8216 
8217   const SCEV *BECount = getCouldNotCompute();
8218   const SCEV *MaxBECount = getCouldNotCompute();
8219   if (EitherMayExit) {
8220     // Both conditions must be same for the loop to continue executing.
8221     // Choose the less conservative count.
8222     // If ExitCond is a short-circuit form (select), using
8223     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
8224     // To see the detailed examples, please see
8225     // test/Analysis/ScalarEvolution/exit-count-select.ll
8226     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
8227     if (!PoisonSafe)
8228       // Even if ExitCond is select, we can safely derive BECount using both
8229       // EL0 and EL1 in these cases:
8230       // (1) EL0.ExactNotTaken is non-zero
8231       // (2) EL1.ExactNotTaken is non-poison
8232       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
8233       //     it cannot be umin(0, ..))
8234       // The PoisonSafe assignment below is simplified and the assertion after
8235       // BECount calculation fully guarantees the condition (3).
8236       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
8237                    isa<SCEVConstant>(EL1.ExactNotTaken);
8238     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8239         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
8240       BECount =
8241           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
8242 
8243       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
8244       // it should have been simplified to zero (see the condition (3) above)
8245       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
8246              BECount->isZero());
8247     }
8248     if (EL0.MaxNotTaken == getCouldNotCompute())
8249       MaxBECount = EL1.MaxNotTaken;
8250     else if (EL1.MaxNotTaken == getCouldNotCompute())
8251       MaxBECount = EL0.MaxNotTaken;
8252     else
8253       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
8254   } else {
8255     // Both conditions must be same at the same time for the loop to exit.
8256     // For now, be conservative.
8257     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8258       BECount = EL0.ExactNotTaken;
8259   }
8260 
8261   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8262   // to be more aggressive when computing BECount than when computing
8263   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
8264   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
8265   // to not.
8266   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
8267       !isa<SCEVCouldNotCompute>(BECount))
8268     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
8269 
8270   return ExitLimit(BECount, MaxBECount, false,
8271                    { &EL0.Predicates, &EL1.Predicates });
8272 }
8273 
8274 ScalarEvolution::ExitLimit
8275 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8276                                           ICmpInst *ExitCond,
8277                                           bool ExitIfTrue,
8278                                           bool ControlsExit,
8279                                           bool AllowPredicates) {
8280   // If the condition was exit on true, convert the condition to exit on false
8281   ICmpInst::Predicate Pred;
8282   if (!ExitIfTrue)
8283     Pred = ExitCond->getPredicate();
8284   else
8285     Pred = ExitCond->getInversePredicate();
8286   const ICmpInst::Predicate OriginalPred = Pred;
8287 
8288   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8289   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8290 
8291   // Try to evaluate any dependencies out of the loop.
8292   LHS = getSCEVAtScope(LHS, L);
8293   RHS = getSCEVAtScope(RHS, L);
8294 
8295   // At this point, we would like to compute how many iterations of the
8296   // loop the predicate will return true for these inputs.
8297   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8298     // If there is a loop-invariant, force it into the RHS.
8299     std::swap(LHS, RHS);
8300     Pred = ICmpInst::getSwappedPredicate(Pred);
8301   }
8302 
8303   // Simplify the operands before analyzing them.
8304   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8305 
8306   // If we have a comparison of a chrec against a constant, try to use value
8307   // ranges to answer this query.
8308   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8309     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8310       if (AddRec->getLoop() == L) {
8311         // Form the constant range.
8312         ConstantRange CompRange =
8313             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8314 
8315         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8316         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8317       }
8318 
8319   // If this loop must exit based on this condition (or execute undefined
8320   // behaviour), and we can prove the test sequence produced must repeat
8321   // the same values on self-wrap of the IV, then we can infer that IV
8322   // doesn't self wrap because if it did, we'd have an infinite (undefined)
8323   // loop.
8324   if (ControlsExit && isLoopInvariant(RHS, L) && loopHasNoAbnormalExits(L) &&
8325       loopIsFiniteByAssumption(L)) {
8326 
8327     // TODO: We can peel off any functions which are invertible *in L*.  Loop
8328     // invariant terms are effectively constants for our purposes here.
8329     auto *InnerLHS = LHS;
8330     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
8331       InnerLHS = ZExt->getOperand();
8332     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
8333       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
8334       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
8335           StrideC && StrideC->getAPInt().isPowerOf2()) {
8336         auto Flags = AR->getNoWrapFlags();
8337         Flags = setFlags(Flags, SCEV::FlagNW);
8338         SmallVector<const SCEV*> Operands{AR->operands()};
8339         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
8340         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
8341       }
8342     }
8343   }
8344 
8345   switch (Pred) {
8346   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8347     // Convert to: while (X-Y != 0)
8348     if (LHS->getType()->isPointerTy()) {
8349       LHS = getLosslessPtrToIntExpr(LHS);
8350       if (isa<SCEVCouldNotCompute>(LHS))
8351         return LHS;
8352     }
8353     if (RHS->getType()->isPointerTy()) {
8354       RHS = getLosslessPtrToIntExpr(RHS);
8355       if (isa<SCEVCouldNotCompute>(RHS))
8356         return RHS;
8357     }
8358     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8359                                 AllowPredicates);
8360     if (EL.hasAnyInfo()) return EL;
8361     break;
8362   }
8363   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8364     // Convert to: while (X-Y == 0)
8365     if (LHS->getType()->isPointerTy()) {
8366       LHS = getLosslessPtrToIntExpr(LHS);
8367       if (isa<SCEVCouldNotCompute>(LHS))
8368         return LHS;
8369     }
8370     if (RHS->getType()->isPointerTy()) {
8371       RHS = getLosslessPtrToIntExpr(RHS);
8372       if (isa<SCEVCouldNotCompute>(RHS))
8373         return RHS;
8374     }
8375     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8376     if (EL.hasAnyInfo()) return EL;
8377     break;
8378   }
8379   case ICmpInst::ICMP_SLT:
8380   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8381     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8382     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8383                                     AllowPredicates);
8384     if (EL.hasAnyInfo()) return EL;
8385     break;
8386   }
8387   case ICmpInst::ICMP_SGT:
8388   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8389     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8390     ExitLimit EL =
8391         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8392                             AllowPredicates);
8393     if (EL.hasAnyInfo()) return EL;
8394     break;
8395   }
8396   default:
8397     break;
8398   }
8399 
8400   auto *ExhaustiveCount =
8401       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8402 
8403   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8404     return ExhaustiveCount;
8405 
8406   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8407                                       ExitCond->getOperand(1), L, OriginalPred);
8408 }
8409 
8410 ScalarEvolution::ExitLimit
8411 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8412                                                       SwitchInst *Switch,
8413                                                       BasicBlock *ExitingBlock,
8414                                                       bool ControlsExit) {
8415   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8416 
8417   // Give up if the exit is the default dest of a switch.
8418   if (Switch->getDefaultDest() == ExitingBlock)
8419     return getCouldNotCompute();
8420 
8421   assert(L->contains(Switch->getDefaultDest()) &&
8422          "Default case must not exit the loop!");
8423   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8424   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8425 
8426   // while (X != Y) --> while (X-Y != 0)
8427   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8428   if (EL.hasAnyInfo())
8429     return EL;
8430 
8431   return getCouldNotCompute();
8432 }
8433 
8434 static ConstantInt *
8435 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8436                                 ScalarEvolution &SE) {
8437   const SCEV *InVal = SE.getConstant(C);
8438   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8439   assert(isa<SCEVConstant>(Val) &&
8440          "Evaluation of SCEV at constant didn't fold correctly?");
8441   return cast<SCEVConstant>(Val)->getValue();
8442 }
8443 
8444 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8445     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8446   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8447   if (!RHS)
8448     return getCouldNotCompute();
8449 
8450   const BasicBlock *Latch = L->getLoopLatch();
8451   if (!Latch)
8452     return getCouldNotCompute();
8453 
8454   const BasicBlock *Predecessor = L->getLoopPredecessor();
8455   if (!Predecessor)
8456     return getCouldNotCompute();
8457 
8458   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8459   // Return LHS in OutLHS and shift_opt in OutOpCode.
8460   auto MatchPositiveShift =
8461       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8462 
8463     using namespace PatternMatch;
8464 
8465     ConstantInt *ShiftAmt;
8466     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8467       OutOpCode = Instruction::LShr;
8468     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8469       OutOpCode = Instruction::AShr;
8470     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8471       OutOpCode = Instruction::Shl;
8472     else
8473       return false;
8474 
8475     return ShiftAmt->getValue().isStrictlyPositive();
8476   };
8477 
8478   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8479   //
8480   // loop:
8481   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8482   //   %iv.shifted = lshr i32 %iv, <positive constant>
8483   //
8484   // Return true on a successful match.  Return the corresponding PHI node (%iv
8485   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8486   auto MatchShiftRecurrence =
8487       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8488     Optional<Instruction::BinaryOps> PostShiftOpCode;
8489 
8490     {
8491       Instruction::BinaryOps OpC;
8492       Value *V;
8493 
8494       // If we encounter a shift instruction, "peel off" the shift operation,
8495       // and remember that we did so.  Later when we inspect %iv's backedge
8496       // value, we will make sure that the backedge value uses the same
8497       // operation.
8498       //
8499       // Note: the peeled shift operation does not have to be the same
8500       // instruction as the one feeding into the PHI's backedge value.  We only
8501       // really care about it being the same *kind* of shift instruction --
8502       // that's all that is required for our later inferences to hold.
8503       if (MatchPositiveShift(LHS, V, OpC)) {
8504         PostShiftOpCode = OpC;
8505         LHS = V;
8506       }
8507     }
8508 
8509     PNOut = dyn_cast<PHINode>(LHS);
8510     if (!PNOut || PNOut->getParent() != L->getHeader())
8511       return false;
8512 
8513     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8514     Value *OpLHS;
8515 
8516     return
8517         // The backedge value for the PHI node must be a shift by a positive
8518         // amount
8519         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8520 
8521         // of the PHI node itself
8522         OpLHS == PNOut &&
8523 
8524         // and the kind of shift should be match the kind of shift we peeled
8525         // off, if any.
8526         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8527   };
8528 
8529   PHINode *PN;
8530   Instruction::BinaryOps OpCode;
8531   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8532     return getCouldNotCompute();
8533 
8534   const DataLayout &DL = getDataLayout();
8535 
8536   // The key rationale for this optimization is that for some kinds of shift
8537   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8538   // within a finite number of iterations.  If the condition guarding the
8539   // backedge (in the sense that the backedge is taken if the condition is true)
8540   // is false for the value the shift recurrence stabilizes to, then we know
8541   // that the backedge is taken only a finite number of times.
8542 
8543   ConstantInt *StableValue = nullptr;
8544   switch (OpCode) {
8545   default:
8546     llvm_unreachable("Impossible case!");
8547 
8548   case Instruction::AShr: {
8549     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8550     // bitwidth(K) iterations.
8551     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8552     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8553                                        Predecessor->getTerminator(), &DT);
8554     auto *Ty = cast<IntegerType>(RHS->getType());
8555     if (Known.isNonNegative())
8556       StableValue = ConstantInt::get(Ty, 0);
8557     else if (Known.isNegative())
8558       StableValue = ConstantInt::get(Ty, -1, true);
8559     else
8560       return getCouldNotCompute();
8561 
8562     break;
8563   }
8564   case Instruction::LShr:
8565   case Instruction::Shl:
8566     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8567     // stabilize to 0 in at most bitwidth(K) iterations.
8568     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8569     break;
8570   }
8571 
8572   auto *Result =
8573       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8574   assert(Result->getType()->isIntegerTy(1) &&
8575          "Otherwise cannot be an operand to a branch instruction");
8576 
8577   if (Result->isZeroValue()) {
8578     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8579     const SCEV *UpperBound =
8580         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8581     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8582   }
8583 
8584   return getCouldNotCompute();
8585 }
8586 
8587 /// Return true if we can constant fold an instruction of the specified type,
8588 /// assuming that all operands were constants.
8589 static bool CanConstantFold(const Instruction *I) {
8590   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8591       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8592       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8593     return true;
8594 
8595   if (const CallInst *CI = dyn_cast<CallInst>(I))
8596     if (const Function *F = CI->getCalledFunction())
8597       return canConstantFoldCallTo(CI, F);
8598   return false;
8599 }
8600 
8601 /// Determine whether this instruction can constant evolve within this loop
8602 /// assuming its operands can all constant evolve.
8603 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8604   // An instruction outside of the loop can't be derived from a loop PHI.
8605   if (!L->contains(I)) return false;
8606 
8607   if (isa<PHINode>(I)) {
8608     // We don't currently keep track of the control flow needed to evaluate
8609     // PHIs, so we cannot handle PHIs inside of loops.
8610     return L->getHeader() == I->getParent();
8611   }
8612 
8613   // If we won't be able to constant fold this expression even if the operands
8614   // are constants, bail early.
8615   return CanConstantFold(I);
8616 }
8617 
8618 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8619 /// recursing through each instruction operand until reaching a loop header phi.
8620 static PHINode *
8621 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8622                                DenseMap<Instruction *, PHINode *> &PHIMap,
8623                                unsigned Depth) {
8624   if (Depth > MaxConstantEvolvingDepth)
8625     return nullptr;
8626 
8627   // Otherwise, we can evaluate this instruction if all of its operands are
8628   // constant or derived from a PHI node themselves.
8629   PHINode *PHI = nullptr;
8630   for (Value *Op : UseInst->operands()) {
8631     if (isa<Constant>(Op)) continue;
8632 
8633     Instruction *OpInst = dyn_cast<Instruction>(Op);
8634     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8635 
8636     PHINode *P = dyn_cast<PHINode>(OpInst);
8637     if (!P)
8638       // If this operand is already visited, reuse the prior result.
8639       // We may have P != PHI if this is the deepest point at which the
8640       // inconsistent paths meet.
8641       P = PHIMap.lookup(OpInst);
8642     if (!P) {
8643       // Recurse and memoize the results, whether a phi is found or not.
8644       // This recursive call invalidates pointers into PHIMap.
8645       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8646       PHIMap[OpInst] = P;
8647     }
8648     if (!P)
8649       return nullptr;  // Not evolving from PHI
8650     if (PHI && PHI != P)
8651       return nullptr;  // Evolving from multiple different PHIs.
8652     PHI = P;
8653   }
8654   // This is a expression evolving from a constant PHI!
8655   return PHI;
8656 }
8657 
8658 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8659 /// in the loop that V is derived from.  We allow arbitrary operations along the
8660 /// way, but the operands of an operation must either be constants or a value
8661 /// derived from a constant PHI.  If this expression does not fit with these
8662 /// constraints, return null.
8663 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8664   Instruction *I = dyn_cast<Instruction>(V);
8665   if (!I || !canConstantEvolve(I, L)) return nullptr;
8666 
8667   if (PHINode *PN = dyn_cast<PHINode>(I))
8668     return PN;
8669 
8670   // Record non-constant instructions contained by the loop.
8671   DenseMap<Instruction *, PHINode *> PHIMap;
8672   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8673 }
8674 
8675 /// EvaluateExpression - Given an expression that passes the
8676 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8677 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8678 /// reason, return null.
8679 static Constant *EvaluateExpression(Value *V, const Loop *L,
8680                                     DenseMap<Instruction *, Constant *> &Vals,
8681                                     const DataLayout &DL,
8682                                     const TargetLibraryInfo *TLI) {
8683   // Convenient constant check, but redundant for recursive calls.
8684   if (Constant *C = dyn_cast<Constant>(V)) return C;
8685   Instruction *I = dyn_cast<Instruction>(V);
8686   if (!I) return nullptr;
8687 
8688   if (Constant *C = Vals.lookup(I)) return C;
8689 
8690   // An instruction inside the loop depends on a value outside the loop that we
8691   // weren't given a mapping for, or a value such as a call inside the loop.
8692   if (!canConstantEvolve(I, L)) return nullptr;
8693 
8694   // An unmapped PHI can be due to a branch or another loop inside this loop,
8695   // or due to this not being the initial iteration through a loop where we
8696   // couldn't compute the evolution of this particular PHI last time.
8697   if (isa<PHINode>(I)) return nullptr;
8698 
8699   std::vector<Constant*> Operands(I->getNumOperands());
8700 
8701   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8702     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8703     if (!Operand) {
8704       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8705       if (!Operands[i]) return nullptr;
8706       continue;
8707     }
8708     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8709     Vals[Operand] = C;
8710     if (!C) return nullptr;
8711     Operands[i] = C;
8712   }
8713 
8714   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8715     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8716                                            Operands[1], DL, TLI);
8717   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8718     if (!LI->isVolatile())
8719       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8720   }
8721   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8722 }
8723 
8724 
8725 // If every incoming value to PN except the one for BB is a specific Constant,
8726 // return that, else return nullptr.
8727 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8728   Constant *IncomingVal = nullptr;
8729 
8730   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8731     if (PN->getIncomingBlock(i) == BB)
8732       continue;
8733 
8734     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8735     if (!CurrentVal)
8736       return nullptr;
8737 
8738     if (IncomingVal != CurrentVal) {
8739       if (IncomingVal)
8740         return nullptr;
8741       IncomingVal = CurrentVal;
8742     }
8743   }
8744 
8745   return IncomingVal;
8746 }
8747 
8748 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8749 /// in the header of its containing loop, we know the loop executes a
8750 /// constant number of times, and the PHI node is just a recurrence
8751 /// involving constants, fold it.
8752 Constant *
8753 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8754                                                    const APInt &BEs,
8755                                                    const Loop *L) {
8756   auto I = ConstantEvolutionLoopExitValue.find(PN);
8757   if (I != ConstantEvolutionLoopExitValue.end())
8758     return I->second;
8759 
8760   if (BEs.ugt(MaxBruteForceIterations))
8761     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8762 
8763   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8764 
8765   DenseMap<Instruction *, Constant *> CurrentIterVals;
8766   BasicBlock *Header = L->getHeader();
8767   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8768 
8769   BasicBlock *Latch = L->getLoopLatch();
8770   if (!Latch)
8771     return nullptr;
8772 
8773   for (PHINode &PHI : Header->phis()) {
8774     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8775       CurrentIterVals[&PHI] = StartCST;
8776   }
8777   if (!CurrentIterVals.count(PN))
8778     return RetVal = nullptr;
8779 
8780   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8781 
8782   // Execute the loop symbolically to determine the exit value.
8783   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8784          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8785 
8786   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8787   unsigned IterationNum = 0;
8788   const DataLayout &DL = getDataLayout();
8789   for (; ; ++IterationNum) {
8790     if (IterationNum == NumIterations)
8791       return RetVal = CurrentIterVals[PN];  // Got exit value!
8792 
8793     // Compute the value of the PHIs for the next iteration.
8794     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8795     DenseMap<Instruction *, Constant *> NextIterVals;
8796     Constant *NextPHI =
8797         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8798     if (!NextPHI)
8799       return nullptr;        // Couldn't evaluate!
8800     NextIterVals[PN] = NextPHI;
8801 
8802     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8803 
8804     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8805     // cease to be able to evaluate one of them or if they stop evolving,
8806     // because that doesn't necessarily prevent us from computing PN.
8807     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8808     for (const auto &I : CurrentIterVals) {
8809       PHINode *PHI = dyn_cast<PHINode>(I.first);
8810       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8811       PHIsToCompute.emplace_back(PHI, I.second);
8812     }
8813     // We use two distinct loops because EvaluateExpression may invalidate any
8814     // iterators into CurrentIterVals.
8815     for (const auto &I : PHIsToCompute) {
8816       PHINode *PHI = I.first;
8817       Constant *&NextPHI = NextIterVals[PHI];
8818       if (!NextPHI) {   // Not already computed.
8819         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8820         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8821       }
8822       if (NextPHI != I.second)
8823         StoppedEvolving = false;
8824     }
8825 
8826     // If all entries in CurrentIterVals == NextIterVals then we can stop
8827     // iterating, the loop can't continue to change.
8828     if (StoppedEvolving)
8829       return RetVal = CurrentIterVals[PN];
8830 
8831     CurrentIterVals.swap(NextIterVals);
8832   }
8833 }
8834 
8835 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8836                                                           Value *Cond,
8837                                                           bool ExitWhen) {
8838   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8839   if (!PN) return getCouldNotCompute();
8840 
8841   // If the loop is canonicalized, the PHI will have exactly two entries.
8842   // That's the only form we support here.
8843   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8844 
8845   DenseMap<Instruction *, Constant *> CurrentIterVals;
8846   BasicBlock *Header = L->getHeader();
8847   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8848 
8849   BasicBlock *Latch = L->getLoopLatch();
8850   assert(Latch && "Should follow from NumIncomingValues == 2!");
8851 
8852   for (PHINode &PHI : Header->phis()) {
8853     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8854       CurrentIterVals[&PHI] = StartCST;
8855   }
8856   if (!CurrentIterVals.count(PN))
8857     return getCouldNotCompute();
8858 
8859   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8860   // the loop symbolically to determine when the condition gets a value of
8861   // "ExitWhen".
8862   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8863   const DataLayout &DL = getDataLayout();
8864   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8865     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8866         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8867 
8868     // Couldn't symbolically evaluate.
8869     if (!CondVal) return getCouldNotCompute();
8870 
8871     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8872       ++NumBruteForceTripCountsComputed;
8873       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8874     }
8875 
8876     // Update all the PHI nodes for the next iteration.
8877     DenseMap<Instruction *, Constant *> NextIterVals;
8878 
8879     // Create a list of which PHIs we need to compute. We want to do this before
8880     // calling EvaluateExpression on them because that may invalidate iterators
8881     // into CurrentIterVals.
8882     SmallVector<PHINode *, 8> PHIsToCompute;
8883     for (const auto &I : CurrentIterVals) {
8884       PHINode *PHI = dyn_cast<PHINode>(I.first);
8885       if (!PHI || PHI->getParent() != Header) continue;
8886       PHIsToCompute.push_back(PHI);
8887     }
8888     for (PHINode *PHI : PHIsToCompute) {
8889       Constant *&NextPHI = NextIterVals[PHI];
8890       if (NextPHI) continue;    // Already computed!
8891 
8892       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8893       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8894     }
8895     CurrentIterVals.swap(NextIterVals);
8896   }
8897 
8898   // Too many iterations were needed to evaluate.
8899   return getCouldNotCompute();
8900 }
8901 
8902 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8903   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8904       ValuesAtScopes[V];
8905   // Check to see if we've folded this expression at this loop before.
8906   for (auto &LS : Values)
8907     if (LS.first == L)
8908       return LS.second ? LS.second : V;
8909 
8910   Values.emplace_back(L, nullptr);
8911 
8912   // Otherwise compute it.
8913   const SCEV *C = computeSCEVAtScope(V, L);
8914   for (auto &LS : reverse(ValuesAtScopes[V]))
8915     if (LS.first == L) {
8916       LS.second = C;
8917       break;
8918     }
8919   return C;
8920 }
8921 
8922 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8923 /// will return Constants for objects which aren't represented by a
8924 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8925 /// Returns NULL if the SCEV isn't representable as a Constant.
8926 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8927   switch (V->getSCEVType()) {
8928   case scCouldNotCompute:
8929   case scAddRecExpr:
8930     return nullptr;
8931   case scConstant:
8932     return cast<SCEVConstant>(V)->getValue();
8933   case scUnknown:
8934     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8935   case scSignExtend: {
8936     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8937     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8938       return ConstantExpr::getSExt(CastOp, SS->getType());
8939     return nullptr;
8940   }
8941   case scZeroExtend: {
8942     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8943     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8944       return ConstantExpr::getZExt(CastOp, SZ->getType());
8945     return nullptr;
8946   }
8947   case scPtrToInt: {
8948     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8949     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8950       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8951 
8952     return nullptr;
8953   }
8954   case scTruncate: {
8955     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8956     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8957       return ConstantExpr::getTrunc(CastOp, ST->getType());
8958     return nullptr;
8959   }
8960   case scAddExpr: {
8961     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8962     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8963       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8964         unsigned AS = PTy->getAddressSpace();
8965         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8966         C = ConstantExpr::getBitCast(C, DestPtrTy);
8967       }
8968       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8969         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8970         if (!C2)
8971           return nullptr;
8972 
8973         // First pointer!
8974         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8975           unsigned AS = C2->getType()->getPointerAddressSpace();
8976           std::swap(C, C2);
8977           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8978           // The offsets have been converted to bytes.  We can add bytes to an
8979           // i8* by GEP with the byte count in the first index.
8980           C = ConstantExpr::getBitCast(C, DestPtrTy);
8981         }
8982 
8983         // Don't bother trying to sum two pointers. We probably can't
8984         // statically compute a load that results from it anyway.
8985         if (C2->getType()->isPointerTy())
8986           return nullptr;
8987 
8988         if (C->getType()->isPointerTy()) {
8989           C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
8990                                              C, C2);
8991         } else {
8992           C = ConstantExpr::getAdd(C, C2);
8993         }
8994       }
8995       return C;
8996     }
8997     return nullptr;
8998   }
8999   case scMulExpr: {
9000     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9001     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
9002       // Don't bother with pointers at all.
9003       if (C->getType()->isPointerTy())
9004         return nullptr;
9005       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
9006         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
9007         if (!C2 || C2->getType()->isPointerTy())
9008           return nullptr;
9009         C = ConstantExpr::getMul(C, C2);
9010       }
9011       return C;
9012     }
9013     return nullptr;
9014   }
9015   case scUDivExpr: {
9016     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
9017     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
9018       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
9019         if (LHS->getType() == RHS->getType())
9020           return ConstantExpr::getUDiv(LHS, RHS);
9021     return nullptr;
9022   }
9023   case scSMaxExpr:
9024   case scUMaxExpr:
9025   case scSMinExpr:
9026   case scUMinExpr:
9027     return nullptr; // TODO: smax, umax, smin, umax.
9028   }
9029   llvm_unreachable("Unknown SCEV kind!");
9030 }
9031 
9032 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9033   if (isa<SCEVConstant>(V)) return V;
9034 
9035   // If this instruction is evolved from a constant-evolving PHI, compute the
9036   // exit value from the loop without using SCEVs.
9037   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
9038     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
9039       if (PHINode *PN = dyn_cast<PHINode>(I)) {
9040         const Loop *CurrLoop = this->LI[I->getParent()];
9041         // Looking for loop exit value.
9042         if (CurrLoop && CurrLoop->getParentLoop() == L &&
9043             PN->getParent() == CurrLoop->getHeader()) {
9044           // Okay, there is no closed form solution for the PHI node.  Check
9045           // to see if the loop that contains it has a known backedge-taken
9046           // count.  If so, we may be able to force computation of the exit
9047           // value.
9048           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9049           // This trivial case can show up in some degenerate cases where
9050           // the incoming IR has not yet been fully simplified.
9051           if (BackedgeTakenCount->isZero()) {
9052             Value *InitValue = nullptr;
9053             bool MultipleInitValues = false;
9054             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9055               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9056                 if (!InitValue)
9057                   InitValue = PN->getIncomingValue(i);
9058                 else if (InitValue != PN->getIncomingValue(i)) {
9059                   MultipleInitValues = true;
9060                   break;
9061                 }
9062               }
9063             }
9064             if (!MultipleInitValues && InitValue)
9065               return getSCEV(InitValue);
9066           }
9067           // Do we have a loop invariant value flowing around the backedge
9068           // for a loop which must execute the backedge?
9069           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9070               isKnownPositive(BackedgeTakenCount) &&
9071               PN->getNumIncomingValues() == 2) {
9072 
9073             unsigned InLoopPred =
9074                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9075             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9076             if (CurrLoop->isLoopInvariant(BackedgeVal))
9077               return getSCEV(BackedgeVal);
9078           }
9079           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9080             // Okay, we know how many times the containing loop executes.  If
9081             // this is a constant evolving PHI node, get the final value at
9082             // the specified iteration number.
9083             Constant *RV = getConstantEvolutionLoopExitValue(
9084                 PN, BTCC->getAPInt(), CurrLoop);
9085             if (RV) return getSCEV(RV);
9086           }
9087         }
9088 
9089         // If there is a single-input Phi, evaluate it at our scope. If we can
9090         // prove that this replacement does not break LCSSA form, use new value.
9091         if (PN->getNumOperands() == 1) {
9092           const SCEV *Input = getSCEV(PN->getOperand(0));
9093           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
9094           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
9095           // for the simplest case just support constants.
9096           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
9097         }
9098       }
9099 
9100       // Okay, this is an expression that we cannot symbolically evaluate
9101       // into a SCEV.  Check to see if it's possible to symbolically evaluate
9102       // the arguments into constants, and if so, try to constant propagate the
9103       // result.  This is particularly useful for computing loop exit values.
9104       if (CanConstantFold(I)) {
9105         SmallVector<Constant *, 4> Operands;
9106         bool MadeImprovement = false;
9107         for (Value *Op : I->operands()) {
9108           if (Constant *C = dyn_cast<Constant>(Op)) {
9109             Operands.push_back(C);
9110             continue;
9111           }
9112 
9113           // If any of the operands is non-constant and if they are
9114           // non-integer and non-pointer, don't even try to analyze them
9115           // with scev techniques.
9116           if (!isSCEVable(Op->getType()))
9117             return V;
9118 
9119           const SCEV *OrigV = getSCEV(Op);
9120           const SCEV *OpV = getSCEVAtScope(OrigV, L);
9121           MadeImprovement |= OrigV != OpV;
9122 
9123           Constant *C = BuildConstantFromSCEV(OpV);
9124           if (!C) return V;
9125           if (C->getType() != Op->getType())
9126             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
9127                                                               Op->getType(),
9128                                                               false),
9129                                       C, Op->getType());
9130           Operands.push_back(C);
9131         }
9132 
9133         // Check to see if getSCEVAtScope actually made an improvement.
9134         if (MadeImprovement) {
9135           Constant *C = nullptr;
9136           const DataLayout &DL = getDataLayout();
9137           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
9138             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9139                                                 Operands[1], DL, &TLI);
9140           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
9141             if (!Load->isVolatile())
9142               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
9143                                                DL);
9144           } else
9145             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9146           if (!C) return V;
9147           return getSCEV(C);
9148         }
9149       }
9150     }
9151 
9152     // This is some other type of SCEVUnknown, just return it.
9153     return V;
9154   }
9155 
9156   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
9157     // Avoid performing the look-up in the common case where the specified
9158     // expression has no loop-variant portions.
9159     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
9160       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9161       if (OpAtScope != Comm->getOperand(i)) {
9162         // Okay, at least one of these operands is loop variant but might be
9163         // foldable.  Build a new instance of the folded commutative expression.
9164         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
9165                                             Comm->op_begin()+i);
9166         NewOps.push_back(OpAtScope);
9167 
9168         for (++i; i != e; ++i) {
9169           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9170           NewOps.push_back(OpAtScope);
9171         }
9172         if (isa<SCEVAddExpr>(Comm))
9173           return getAddExpr(NewOps, Comm->getNoWrapFlags());
9174         if (isa<SCEVMulExpr>(Comm))
9175           return getMulExpr(NewOps, Comm->getNoWrapFlags());
9176         if (isa<SCEVMinMaxExpr>(Comm))
9177           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
9178         llvm_unreachable("Unknown commutative SCEV type!");
9179       }
9180     }
9181     // If we got here, all operands are loop invariant.
9182     return Comm;
9183   }
9184 
9185   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
9186     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
9187     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
9188     if (LHS == Div->getLHS() && RHS == Div->getRHS())
9189       return Div;   // must be loop invariant
9190     return getUDivExpr(LHS, RHS);
9191   }
9192 
9193   // If this is a loop recurrence for a loop that does not contain L, then we
9194   // are dealing with the final value computed by the loop.
9195   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
9196     // First, attempt to evaluate each operand.
9197     // Avoid performing the look-up in the common case where the specified
9198     // expression has no loop-variant portions.
9199     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9200       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9201       if (OpAtScope == AddRec->getOperand(i))
9202         continue;
9203 
9204       // Okay, at least one of these operands is loop variant but might be
9205       // foldable.  Build a new instance of the folded commutative expression.
9206       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9207                                           AddRec->op_begin()+i);
9208       NewOps.push_back(OpAtScope);
9209       for (++i; i != e; ++i)
9210         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9211 
9212       const SCEV *FoldedRec =
9213         getAddRecExpr(NewOps, AddRec->getLoop(),
9214                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9215       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9216       // The addrec may be folded to a nonrecurrence, for example, if the
9217       // induction variable is multiplied by zero after constant folding. Go
9218       // ahead and return the folded value.
9219       if (!AddRec)
9220         return FoldedRec;
9221       break;
9222     }
9223 
9224     // If the scope is outside the addrec's loop, evaluate it by using the
9225     // loop exit value of the addrec.
9226     if (!AddRec->getLoop()->contains(L)) {
9227       // To evaluate this recurrence, we need to know how many times the AddRec
9228       // loop iterates.  Compute this now.
9229       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9230       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9231 
9232       // Then, evaluate the AddRec.
9233       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9234     }
9235 
9236     return AddRec;
9237   }
9238 
9239   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
9240     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9241     if (Op == Cast->getOperand())
9242       return Cast;  // must be loop invariant
9243     return getZeroExtendExpr(Op, Cast->getType());
9244   }
9245 
9246   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
9247     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9248     if (Op == Cast->getOperand())
9249       return Cast;  // must be loop invariant
9250     return getSignExtendExpr(Op, Cast->getType());
9251   }
9252 
9253   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
9254     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9255     if (Op == Cast->getOperand())
9256       return Cast;  // must be loop invariant
9257     return getTruncateExpr(Op, Cast->getType());
9258   }
9259 
9260   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
9261     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9262     if (Op == Cast->getOperand())
9263       return Cast; // must be loop invariant
9264     return getPtrToIntExpr(Op, Cast->getType());
9265   }
9266 
9267   llvm_unreachable("Unknown SCEV type!");
9268 }
9269 
9270 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9271   return getSCEVAtScope(getSCEV(V), L);
9272 }
9273 
9274 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9275   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9276     return stripInjectiveFunctions(ZExt->getOperand());
9277   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9278     return stripInjectiveFunctions(SExt->getOperand());
9279   return S;
9280 }
9281 
9282 /// Finds the minimum unsigned root of the following equation:
9283 ///
9284 ///     A * X = B (mod N)
9285 ///
9286 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9287 /// A and B isn't important.
9288 ///
9289 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9290 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9291                                                ScalarEvolution &SE) {
9292   uint32_t BW = A.getBitWidth();
9293   assert(BW == SE.getTypeSizeInBits(B->getType()));
9294   assert(A != 0 && "A must be non-zero.");
9295 
9296   // 1. D = gcd(A, N)
9297   //
9298   // The gcd of A and N may have only one prime factor: 2. The number of
9299   // trailing zeros in A is its multiplicity
9300   uint32_t Mult2 = A.countTrailingZeros();
9301   // D = 2^Mult2
9302 
9303   // 2. Check if B is divisible by D.
9304   //
9305   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9306   // is not less than multiplicity of this prime factor for D.
9307   if (SE.GetMinTrailingZeros(B) < Mult2)
9308     return SE.getCouldNotCompute();
9309 
9310   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9311   // modulo (N / D).
9312   //
9313   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9314   // (N / D) in general. The inverse itself always fits into BW bits, though,
9315   // so we immediately truncate it.
9316   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9317   APInt Mod(BW + 1, 0);
9318   Mod.setBit(BW - Mult2);  // Mod = N / D
9319   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9320 
9321   // 4. Compute the minimum unsigned root of the equation:
9322   // I * (B / D) mod (N / D)
9323   // To simplify the computation, we factor out the divide by D:
9324   // (I * B mod N) / D
9325   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9326   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9327 }
9328 
9329 /// For a given quadratic addrec, generate coefficients of the corresponding
9330 /// quadratic equation, multiplied by a common value to ensure that they are
9331 /// integers.
9332 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9333 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9334 /// were multiplied by, and BitWidth is the bit width of the original addrec
9335 /// coefficients.
9336 /// This function returns None if the addrec coefficients are not compile-
9337 /// time constants.
9338 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9339 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9340   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9341   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9342   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9343   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9344   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9345                     << *AddRec << '\n');
9346 
9347   // We currently can only solve this if the coefficients are constants.
9348   if (!LC || !MC || !NC) {
9349     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9350     return None;
9351   }
9352 
9353   APInt L = LC->getAPInt();
9354   APInt M = MC->getAPInt();
9355   APInt N = NC->getAPInt();
9356   assert(!N.isZero() && "This is not a quadratic addrec");
9357 
9358   unsigned BitWidth = LC->getAPInt().getBitWidth();
9359   unsigned NewWidth = BitWidth + 1;
9360   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9361                     << BitWidth << '\n');
9362   // The sign-extension (as opposed to a zero-extension) here matches the
9363   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9364   N = N.sext(NewWidth);
9365   M = M.sext(NewWidth);
9366   L = L.sext(NewWidth);
9367 
9368   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9369   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9370   //   L+M, L+2M+N, L+3M+3N, ...
9371   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9372   //
9373   // The equation Acc = 0 is then
9374   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9375   // In a quadratic form it becomes:
9376   //   N n^2 + (2M-N) n + 2L = 0.
9377 
9378   APInt A = N;
9379   APInt B = 2 * M - A;
9380   APInt C = 2 * L;
9381   APInt T = APInt(NewWidth, 2);
9382   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9383                     << "x + " << C << ", coeff bw: " << NewWidth
9384                     << ", multiplied by " << T << '\n');
9385   return std::make_tuple(A, B, C, T, BitWidth);
9386 }
9387 
9388 /// Helper function to compare optional APInts:
9389 /// (a) if X and Y both exist, return min(X, Y),
9390 /// (b) if neither X nor Y exist, return None,
9391 /// (c) if exactly one of X and Y exists, return that value.
9392 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9393   if (X.hasValue() && Y.hasValue()) {
9394     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9395     APInt XW = X->sextOrSelf(W);
9396     APInt YW = Y->sextOrSelf(W);
9397     return XW.slt(YW) ? *X : *Y;
9398   }
9399   if (!X.hasValue() && !Y.hasValue())
9400     return None;
9401   return X.hasValue() ? *X : *Y;
9402 }
9403 
9404 /// Helper function to truncate an optional APInt to a given BitWidth.
9405 /// When solving addrec-related equations, it is preferable to return a value
9406 /// that has the same bit width as the original addrec's coefficients. If the
9407 /// solution fits in the original bit width, truncate it (except for i1).
9408 /// Returning a value of a different bit width may inhibit some optimizations.
9409 ///
9410 /// In general, a solution to a quadratic equation generated from an addrec
9411 /// may require BW+1 bits, where BW is the bit width of the addrec's
9412 /// coefficients. The reason is that the coefficients of the quadratic
9413 /// equation are BW+1 bits wide (to avoid truncation when converting from
9414 /// the addrec to the equation).
9415 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9416   if (!X.hasValue())
9417     return None;
9418   unsigned W = X->getBitWidth();
9419   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9420     return X->trunc(BitWidth);
9421   return X;
9422 }
9423 
9424 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9425 /// iterations. The values L, M, N are assumed to be signed, and they
9426 /// should all have the same bit widths.
9427 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9428 /// where BW is the bit width of the addrec's coefficients.
9429 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9430 /// returned as such, otherwise the bit width of the returned value may
9431 /// be greater than BW.
9432 ///
9433 /// This function returns None if
9434 /// (a) the addrec coefficients are not constant, or
9435 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9436 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9437 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9438 static Optional<APInt>
9439 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9440   APInt A, B, C, M;
9441   unsigned BitWidth;
9442   auto T = GetQuadraticEquation(AddRec);
9443   if (!T.hasValue())
9444     return None;
9445 
9446   std::tie(A, B, C, M, BitWidth) = *T;
9447   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9448   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9449   if (!X.hasValue())
9450     return None;
9451 
9452   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9453   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9454   if (!V->isZero())
9455     return None;
9456 
9457   return TruncIfPossible(X, BitWidth);
9458 }
9459 
9460 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9461 /// iterations. The values M, N are assumed to be signed, and they
9462 /// should all have the same bit widths.
9463 /// Find the least n such that c(n) does not belong to the given range,
9464 /// while c(n-1) does.
9465 ///
9466 /// This function returns None if
9467 /// (a) the addrec coefficients are not constant, or
9468 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9469 ///     bounds of the range.
9470 static Optional<APInt>
9471 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9472                           const ConstantRange &Range, ScalarEvolution &SE) {
9473   assert(AddRec->getOperand(0)->isZero() &&
9474          "Starting value of addrec should be 0");
9475   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9476                     << Range << ", addrec " << *AddRec << '\n');
9477   // This case is handled in getNumIterationsInRange. Here we can assume that
9478   // we start in the range.
9479   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9480          "Addrec's initial value should be in range");
9481 
9482   APInt A, B, C, M;
9483   unsigned BitWidth;
9484   auto T = GetQuadraticEquation(AddRec);
9485   if (!T.hasValue())
9486     return None;
9487 
9488   // Be careful about the return value: there can be two reasons for not
9489   // returning an actual number. First, if no solutions to the equations
9490   // were found, and second, if the solutions don't leave the given range.
9491   // The first case means that the actual solution is "unknown", the second
9492   // means that it's known, but not valid. If the solution is unknown, we
9493   // cannot make any conclusions.
9494   // Return a pair: the optional solution and a flag indicating if the
9495   // solution was found.
9496   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9497     // Solve for signed overflow and unsigned overflow, pick the lower
9498     // solution.
9499     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9500                       << Bound << " (before multiplying by " << M << ")\n");
9501     Bound *= M; // The quadratic equation multiplier.
9502 
9503     Optional<APInt> SO = None;
9504     if (BitWidth > 1) {
9505       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9506                            "signed overflow\n");
9507       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9508     }
9509     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9510                          "unsigned overflow\n");
9511     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9512                                                               BitWidth+1);
9513 
9514     auto LeavesRange = [&] (const APInt &X) {
9515       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9516       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9517       if (Range.contains(V0->getValue()))
9518         return false;
9519       // X should be at least 1, so X-1 is non-negative.
9520       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9521       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9522       if (Range.contains(V1->getValue()))
9523         return true;
9524       return false;
9525     };
9526 
9527     // If SolveQuadraticEquationWrap returns None, it means that there can
9528     // be a solution, but the function failed to find it. We cannot treat it
9529     // as "no solution".
9530     if (!SO.hasValue() || !UO.hasValue())
9531       return { None, false };
9532 
9533     // Check the smaller value first to see if it leaves the range.
9534     // At this point, both SO and UO must have values.
9535     Optional<APInt> Min = MinOptional(SO, UO);
9536     if (LeavesRange(*Min))
9537       return { Min, true };
9538     Optional<APInt> Max = Min == SO ? UO : SO;
9539     if (LeavesRange(*Max))
9540       return { Max, true };
9541 
9542     // Solutions were found, but were eliminated, hence the "true".
9543     return { None, true };
9544   };
9545 
9546   std::tie(A, B, C, M, BitWidth) = *T;
9547   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9548   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9549   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9550   auto SL = SolveForBoundary(Lower);
9551   auto SU = SolveForBoundary(Upper);
9552   // If any of the solutions was unknown, no meaninigful conclusions can
9553   // be made.
9554   if (!SL.second || !SU.second)
9555     return None;
9556 
9557   // Claim: The correct solution is not some value between Min and Max.
9558   //
9559   // Justification: Assuming that Min and Max are different values, one of
9560   // them is when the first signed overflow happens, the other is when the
9561   // first unsigned overflow happens. Crossing the range boundary is only
9562   // possible via an overflow (treating 0 as a special case of it, modeling
9563   // an overflow as crossing k*2^W for some k).
9564   //
9565   // The interesting case here is when Min was eliminated as an invalid
9566   // solution, but Max was not. The argument is that if there was another
9567   // overflow between Min and Max, it would also have been eliminated if
9568   // it was considered.
9569   //
9570   // For a given boundary, it is possible to have two overflows of the same
9571   // type (signed/unsigned) without having the other type in between: this
9572   // can happen when the vertex of the parabola is between the iterations
9573   // corresponding to the overflows. This is only possible when the two
9574   // overflows cross k*2^W for the same k. In such case, if the second one
9575   // left the range (and was the first one to do so), the first overflow
9576   // would have to enter the range, which would mean that either we had left
9577   // the range before or that we started outside of it. Both of these cases
9578   // are contradictions.
9579   //
9580   // Claim: In the case where SolveForBoundary returns None, the correct
9581   // solution is not some value between the Max for this boundary and the
9582   // Min of the other boundary.
9583   //
9584   // Justification: Assume that we had such Max_A and Min_B corresponding
9585   // to range boundaries A and B and such that Max_A < Min_B. If there was
9586   // a solution between Max_A and Min_B, it would have to be caused by an
9587   // overflow corresponding to either A or B. It cannot correspond to B,
9588   // since Min_B is the first occurrence of such an overflow. If it
9589   // corresponded to A, it would have to be either a signed or an unsigned
9590   // overflow that is larger than both eliminated overflows for A. But
9591   // between the eliminated overflows and this overflow, the values would
9592   // cover the entire value space, thus crossing the other boundary, which
9593   // is a contradiction.
9594 
9595   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9596 }
9597 
9598 ScalarEvolution::ExitLimit
9599 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9600                               bool AllowPredicates) {
9601 
9602   // This is only used for loops with a "x != y" exit test. The exit condition
9603   // is now expressed as a single expression, V = x-y. So the exit test is
9604   // effectively V != 0.  We know and take advantage of the fact that this
9605   // expression only being used in a comparison by zero context.
9606 
9607   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9608   // If the value is a constant
9609   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9610     // If the value is already zero, the branch will execute zero times.
9611     if (C->getValue()->isZero()) return C;
9612     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9613   }
9614 
9615   const SCEVAddRecExpr *AddRec =
9616       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9617 
9618   if (!AddRec && AllowPredicates)
9619     // Try to make this an AddRec using runtime tests, in the first X
9620     // iterations of this loop, where X is the SCEV expression found by the
9621     // algorithm below.
9622     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9623 
9624   if (!AddRec || AddRec->getLoop() != L)
9625     return getCouldNotCompute();
9626 
9627   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9628   // the quadratic equation to solve it.
9629   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9630     // We can only use this value if the chrec ends up with an exact zero
9631     // value at this index.  When solving for "X*X != 5", for example, we
9632     // should not accept a root of 2.
9633     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9634       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9635       return ExitLimit(R, R, false, Predicates);
9636     }
9637     return getCouldNotCompute();
9638   }
9639 
9640   // Otherwise we can only handle this if it is affine.
9641   if (!AddRec->isAffine())
9642     return getCouldNotCompute();
9643 
9644   // If this is an affine expression, the execution count of this branch is
9645   // the minimum unsigned root of the following equation:
9646   //
9647   //     Start + Step*N = 0 (mod 2^BW)
9648   //
9649   // equivalent to:
9650   //
9651   //             Step*N = -Start (mod 2^BW)
9652   //
9653   // where BW is the common bit width of Start and Step.
9654 
9655   // Get the initial value for the loop.
9656   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9657   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9658 
9659   // For now we handle only constant steps.
9660   //
9661   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9662   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9663   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9664   // We have not yet seen any such cases.
9665   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9666   if (!StepC || StepC->getValue()->isZero())
9667     return getCouldNotCompute();
9668 
9669   // For positive steps (counting up until unsigned overflow):
9670   //   N = -Start/Step (as unsigned)
9671   // For negative steps (counting down to zero):
9672   //   N = Start/-Step
9673   // First compute the unsigned distance from zero in the direction of Step.
9674   bool CountDown = StepC->getAPInt().isNegative();
9675   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9676 
9677   // Handle unitary steps, which cannot wraparound.
9678   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9679   //   N = Distance (as unsigned)
9680   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9681     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9682     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
9683 
9684     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9685     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9686     // case, and see if we can improve the bound.
9687     //
9688     // Explicitly handling this here is necessary because getUnsignedRange
9689     // isn't context-sensitive; it doesn't know that we only care about the
9690     // range inside the loop.
9691     const SCEV *Zero = getZero(Distance->getType());
9692     const SCEV *One = getOne(Distance->getType());
9693     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9694     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9695       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9696       // as "unsigned_max(Distance + 1) - 1".
9697       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9698       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9699     }
9700     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9701   }
9702 
9703   // If the condition controls loop exit (the loop exits only if the expression
9704   // is true) and the addition is no-wrap we can use unsigned divide to
9705   // compute the backedge count.  In this case, the step may not divide the
9706   // distance, but we don't care because if the condition is "missed" the loop
9707   // will have undefined behavior due to wrapping.
9708   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9709       loopHasNoAbnormalExits(AddRec->getLoop())) {
9710     const SCEV *Exact =
9711         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9712     const SCEV *Max = getCouldNotCompute();
9713     if (Exact != getCouldNotCompute()) {
9714       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
9715       Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
9716     }
9717     return ExitLimit(Exact, Max, false, Predicates);
9718   }
9719 
9720   // Solve the general equation.
9721   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9722                                                getNegativeSCEV(Start), *this);
9723 
9724   const SCEV *M = E;
9725   if (E != getCouldNotCompute()) {
9726     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
9727     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
9728   }
9729   return ExitLimit(E, M, false, Predicates);
9730 }
9731 
9732 ScalarEvolution::ExitLimit
9733 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9734   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9735   // handle them yet except for the trivial case.  This could be expanded in the
9736   // future as needed.
9737 
9738   // If the value is a constant, check to see if it is known to be non-zero
9739   // already.  If so, the backedge will execute zero times.
9740   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9741     if (!C->getValue()->isZero())
9742       return getZero(C->getType());
9743     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9744   }
9745 
9746   // We could implement others, but I really doubt anyone writes loops like
9747   // this, and if they did, they would already be constant folded.
9748   return getCouldNotCompute();
9749 }
9750 
9751 std::pair<const BasicBlock *, const BasicBlock *>
9752 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9753     const {
9754   // If the block has a unique predecessor, then there is no path from the
9755   // predecessor to the block that does not go through the direct edge
9756   // from the predecessor to the block.
9757   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9758     return {Pred, BB};
9759 
9760   // A loop's header is defined to be a block that dominates the loop.
9761   // If the header has a unique predecessor outside the loop, it must be
9762   // a block that has exactly one successor that can reach the loop.
9763   if (const Loop *L = LI.getLoopFor(BB))
9764     return {L->getLoopPredecessor(), L->getHeader()};
9765 
9766   return {nullptr, nullptr};
9767 }
9768 
9769 /// SCEV structural equivalence is usually sufficient for testing whether two
9770 /// expressions are equal, however for the purposes of looking for a condition
9771 /// guarding a loop, it can be useful to be a little more general, since a
9772 /// front-end may have replicated the controlling expression.
9773 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9774   // Quick check to see if they are the same SCEV.
9775   if (A == B) return true;
9776 
9777   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9778     // Not all instructions that are "identical" compute the same value.  For
9779     // instance, two distinct alloca instructions allocating the same type are
9780     // identical and do not read memory; but compute distinct values.
9781     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9782   };
9783 
9784   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9785   // two different instructions with the same value. Check for this case.
9786   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9787     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9788       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9789         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9790           if (ComputesEqualValues(AI, BI))
9791             return true;
9792 
9793   // Otherwise assume they may have a different value.
9794   return false;
9795 }
9796 
9797 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9798                                            const SCEV *&LHS, const SCEV *&RHS,
9799                                            unsigned Depth) {
9800   bool Changed = false;
9801   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9802   // '0 != 0'.
9803   auto TrivialCase = [&](bool TriviallyTrue) {
9804     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9805     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9806     return true;
9807   };
9808   // If we hit the max recursion limit bail out.
9809   if (Depth >= 3)
9810     return false;
9811 
9812   // Canonicalize a constant to the right side.
9813   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9814     // Check for both operands constant.
9815     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9816       if (ConstantExpr::getICmp(Pred,
9817                                 LHSC->getValue(),
9818                                 RHSC->getValue())->isNullValue())
9819         return TrivialCase(false);
9820       else
9821         return TrivialCase(true);
9822     }
9823     // Otherwise swap the operands to put the constant on the right.
9824     std::swap(LHS, RHS);
9825     Pred = ICmpInst::getSwappedPredicate(Pred);
9826     Changed = true;
9827   }
9828 
9829   // If we're comparing an addrec with a value which is loop-invariant in the
9830   // addrec's loop, put the addrec on the left. Also make a dominance check,
9831   // as both operands could be addrecs loop-invariant in each other's loop.
9832   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9833     const Loop *L = AR->getLoop();
9834     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9835       std::swap(LHS, RHS);
9836       Pred = ICmpInst::getSwappedPredicate(Pred);
9837       Changed = true;
9838     }
9839   }
9840 
9841   // If there's a constant operand, canonicalize comparisons with boundary
9842   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9843   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9844     const APInt &RA = RC->getAPInt();
9845 
9846     bool SimplifiedByConstantRange = false;
9847 
9848     if (!ICmpInst::isEquality(Pred)) {
9849       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9850       if (ExactCR.isFullSet())
9851         return TrivialCase(true);
9852       else if (ExactCR.isEmptySet())
9853         return TrivialCase(false);
9854 
9855       APInt NewRHS;
9856       CmpInst::Predicate NewPred;
9857       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9858           ICmpInst::isEquality(NewPred)) {
9859         // We were able to convert an inequality to an equality.
9860         Pred = NewPred;
9861         RHS = getConstant(NewRHS);
9862         Changed = SimplifiedByConstantRange = true;
9863       }
9864     }
9865 
9866     if (!SimplifiedByConstantRange) {
9867       switch (Pred) {
9868       default:
9869         break;
9870       case ICmpInst::ICMP_EQ:
9871       case ICmpInst::ICMP_NE:
9872         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9873         if (!RA)
9874           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9875             if (const SCEVMulExpr *ME =
9876                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9877               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9878                   ME->getOperand(0)->isAllOnesValue()) {
9879                 RHS = AE->getOperand(1);
9880                 LHS = ME->getOperand(1);
9881                 Changed = true;
9882               }
9883         break;
9884 
9885 
9886         // The "Should have been caught earlier!" messages refer to the fact
9887         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9888         // should have fired on the corresponding cases, and canonicalized the
9889         // check to trivial case.
9890 
9891       case ICmpInst::ICMP_UGE:
9892         assert(!RA.isMinValue() && "Should have been caught earlier!");
9893         Pred = ICmpInst::ICMP_UGT;
9894         RHS = getConstant(RA - 1);
9895         Changed = true;
9896         break;
9897       case ICmpInst::ICMP_ULE:
9898         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9899         Pred = ICmpInst::ICMP_ULT;
9900         RHS = getConstant(RA + 1);
9901         Changed = true;
9902         break;
9903       case ICmpInst::ICMP_SGE:
9904         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9905         Pred = ICmpInst::ICMP_SGT;
9906         RHS = getConstant(RA - 1);
9907         Changed = true;
9908         break;
9909       case ICmpInst::ICMP_SLE:
9910         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9911         Pred = ICmpInst::ICMP_SLT;
9912         RHS = getConstant(RA + 1);
9913         Changed = true;
9914         break;
9915       }
9916     }
9917   }
9918 
9919   // Check for obvious equality.
9920   if (HasSameValue(LHS, RHS)) {
9921     if (ICmpInst::isTrueWhenEqual(Pred))
9922       return TrivialCase(true);
9923     if (ICmpInst::isFalseWhenEqual(Pred))
9924       return TrivialCase(false);
9925   }
9926 
9927   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9928   // adding or subtracting 1 from one of the operands.
9929   switch (Pred) {
9930   case ICmpInst::ICMP_SLE:
9931     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9932       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9933                        SCEV::FlagNSW);
9934       Pred = ICmpInst::ICMP_SLT;
9935       Changed = true;
9936     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9937       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9938                        SCEV::FlagNSW);
9939       Pred = ICmpInst::ICMP_SLT;
9940       Changed = true;
9941     }
9942     break;
9943   case ICmpInst::ICMP_SGE:
9944     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9945       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9946                        SCEV::FlagNSW);
9947       Pred = ICmpInst::ICMP_SGT;
9948       Changed = true;
9949     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9950       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9951                        SCEV::FlagNSW);
9952       Pred = ICmpInst::ICMP_SGT;
9953       Changed = true;
9954     }
9955     break;
9956   case ICmpInst::ICMP_ULE:
9957     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9958       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9959                        SCEV::FlagNUW);
9960       Pred = ICmpInst::ICMP_ULT;
9961       Changed = true;
9962     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9963       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9964       Pred = ICmpInst::ICMP_ULT;
9965       Changed = true;
9966     }
9967     break;
9968   case ICmpInst::ICMP_UGE:
9969     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9970       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9971       Pred = ICmpInst::ICMP_UGT;
9972       Changed = true;
9973     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9974       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9975                        SCEV::FlagNUW);
9976       Pred = ICmpInst::ICMP_UGT;
9977       Changed = true;
9978     }
9979     break;
9980   default:
9981     break;
9982   }
9983 
9984   // TODO: More simplifications are possible here.
9985 
9986   // Recursively simplify until we either hit a recursion limit or nothing
9987   // changes.
9988   if (Changed)
9989     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9990 
9991   return Changed;
9992 }
9993 
9994 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9995   return getSignedRangeMax(S).isNegative();
9996 }
9997 
9998 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9999   return getSignedRangeMin(S).isStrictlyPositive();
10000 }
10001 
10002 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10003   return !getSignedRangeMin(S).isNegative();
10004 }
10005 
10006 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10007   return !getSignedRangeMax(S).isStrictlyPositive();
10008 }
10009 
10010 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10011   return getUnsignedRangeMin(S) != 0;
10012 }
10013 
10014 std::pair<const SCEV *, const SCEV *>
10015 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10016   // Compute SCEV on entry of loop L.
10017   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10018   if (Start == getCouldNotCompute())
10019     return { Start, Start };
10020   // Compute post increment SCEV for loop L.
10021   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10022   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10023   return { Start, PostInc };
10024 }
10025 
10026 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10027                                           const SCEV *LHS, const SCEV *RHS) {
10028   // First collect all loops.
10029   SmallPtrSet<const Loop *, 8> LoopsUsed;
10030   getUsedLoops(LHS, LoopsUsed);
10031   getUsedLoops(RHS, LoopsUsed);
10032 
10033   if (LoopsUsed.empty())
10034     return false;
10035 
10036   // Domination relationship must be a linear order on collected loops.
10037 #ifndef NDEBUG
10038   for (auto *L1 : LoopsUsed)
10039     for (auto *L2 : LoopsUsed)
10040       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10041               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10042              "Domination relationship is not a linear order");
10043 #endif
10044 
10045   const Loop *MDL =
10046       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10047                         [&](const Loop *L1, const Loop *L2) {
10048          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10049        });
10050 
10051   // Get init and post increment value for LHS.
10052   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10053   // if LHS contains unknown non-invariant SCEV then bail out.
10054   if (SplitLHS.first == getCouldNotCompute())
10055     return false;
10056   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10057   // Get init and post increment value for RHS.
10058   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10059   // if RHS contains unknown non-invariant SCEV then bail out.
10060   if (SplitRHS.first == getCouldNotCompute())
10061     return false;
10062   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10063   // It is possible that init SCEV contains an invariant load but it does
10064   // not dominate MDL and is not available at MDL loop entry, so we should
10065   // check it here.
10066   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10067       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10068     return false;
10069 
10070   // It seems backedge guard check is faster than entry one so in some cases
10071   // it can speed up whole estimation by short circuit
10072   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10073                                      SplitRHS.second) &&
10074          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10075 }
10076 
10077 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10078                                        const SCEV *LHS, const SCEV *RHS) {
10079   // Canonicalize the inputs first.
10080   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10081 
10082   if (isKnownViaInduction(Pred, LHS, RHS))
10083     return true;
10084 
10085   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10086     return true;
10087 
10088   // Otherwise see what can be done with some simple reasoning.
10089   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10090 }
10091 
10092 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10093                                                   const SCEV *LHS,
10094                                                   const SCEV *RHS) {
10095   if (isKnownPredicate(Pred, LHS, RHS))
10096     return true;
10097   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10098     return false;
10099   return None;
10100 }
10101 
10102 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10103                                          const SCEV *LHS, const SCEV *RHS,
10104                                          const Instruction *CtxI) {
10105   // TODO: Analyze guards and assumes from Context's block.
10106   return isKnownPredicate(Pred, LHS, RHS) ||
10107          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10108 }
10109 
10110 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred,
10111                                                     const SCEV *LHS,
10112                                                     const SCEV *RHS,
10113                                                     const Instruction *CtxI) {
10114   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10115   if (KnownWithoutContext)
10116     return KnownWithoutContext;
10117 
10118   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10119     return true;
10120   else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10121                                           ICmpInst::getInversePredicate(Pred),
10122                                           LHS, RHS))
10123     return false;
10124   return None;
10125 }
10126 
10127 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10128                                               const SCEVAddRecExpr *LHS,
10129                                               const SCEV *RHS) {
10130   const Loop *L = LHS->getLoop();
10131   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10132          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10133 }
10134 
10135 Optional<ScalarEvolution::MonotonicPredicateType>
10136 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10137                                            ICmpInst::Predicate Pred) {
10138   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10139 
10140 #ifndef NDEBUG
10141   // Verify an invariant: inverting the predicate should turn a monotonically
10142   // increasing change to a monotonically decreasing one, and vice versa.
10143   if (Result) {
10144     auto ResultSwapped =
10145         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10146 
10147     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
10148     assert(ResultSwapped.getValue() != Result.getValue() &&
10149            "monotonicity should flip as we flip the predicate");
10150   }
10151 #endif
10152 
10153   return Result;
10154 }
10155 
10156 Optional<ScalarEvolution::MonotonicPredicateType>
10157 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10158                                                ICmpInst::Predicate Pred) {
10159   // A zero step value for LHS means the induction variable is essentially a
10160   // loop invariant value. We don't really depend on the predicate actually
10161   // flipping from false to true (for increasing predicates, and the other way
10162   // around for decreasing predicates), all we care about is that *if* the
10163   // predicate changes then it only changes from false to true.
10164   //
10165   // A zero step value in itself is not very useful, but there may be places
10166   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10167   // as general as possible.
10168 
10169   // Only handle LE/LT/GE/GT predicates.
10170   if (!ICmpInst::isRelational(Pred))
10171     return None;
10172 
10173   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10174   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10175          "Should be greater or less!");
10176 
10177   // Check that AR does not wrap.
10178   if (ICmpInst::isUnsigned(Pred)) {
10179     if (!LHS->hasNoUnsignedWrap())
10180       return None;
10181     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10182   } else {
10183     assert(ICmpInst::isSigned(Pred) &&
10184            "Relational predicate is either signed or unsigned!");
10185     if (!LHS->hasNoSignedWrap())
10186       return None;
10187 
10188     const SCEV *Step = LHS->getStepRecurrence(*this);
10189 
10190     if (isKnownNonNegative(Step))
10191       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10192 
10193     if (isKnownNonPositive(Step))
10194       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10195 
10196     return None;
10197   }
10198 }
10199 
10200 Optional<ScalarEvolution::LoopInvariantPredicate>
10201 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10202                                            const SCEV *LHS, const SCEV *RHS,
10203                                            const Loop *L) {
10204 
10205   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10206   if (!isLoopInvariant(RHS, L)) {
10207     if (!isLoopInvariant(LHS, L))
10208       return None;
10209 
10210     std::swap(LHS, RHS);
10211     Pred = ICmpInst::getSwappedPredicate(Pred);
10212   }
10213 
10214   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10215   if (!ArLHS || ArLHS->getLoop() != L)
10216     return None;
10217 
10218   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10219   if (!MonotonicType)
10220     return None;
10221   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10222   // true as the loop iterates, and the backedge is control dependent on
10223   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10224   //
10225   //   * if the predicate was false in the first iteration then the predicate
10226   //     is never evaluated again, since the loop exits without taking the
10227   //     backedge.
10228   //   * if the predicate was true in the first iteration then it will
10229   //     continue to be true for all future iterations since it is
10230   //     monotonically increasing.
10231   //
10232   // For both the above possibilities, we can replace the loop varying
10233   // predicate with its value on the first iteration of the loop (which is
10234   // loop invariant).
10235   //
10236   // A similar reasoning applies for a monotonically decreasing predicate, by
10237   // replacing true with false and false with true in the above two bullets.
10238   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10239   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10240 
10241   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10242     return None;
10243 
10244   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10245 }
10246 
10247 Optional<ScalarEvolution::LoopInvariantPredicate>
10248 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10249     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10250     const Instruction *CtxI, const SCEV *MaxIter) {
10251   // Try to prove the following set of facts:
10252   // - The predicate is monotonic in the iteration space.
10253   // - If the check does not fail on the 1st iteration:
10254   //   - No overflow will happen during first MaxIter iterations;
10255   //   - It will not fail on the MaxIter'th iteration.
10256   // If the check does fail on the 1st iteration, we leave the loop and no
10257   // other checks matter.
10258 
10259   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10260   if (!isLoopInvariant(RHS, L)) {
10261     if (!isLoopInvariant(LHS, L))
10262       return None;
10263 
10264     std::swap(LHS, RHS);
10265     Pred = ICmpInst::getSwappedPredicate(Pred);
10266   }
10267 
10268   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10269   if (!AR || AR->getLoop() != L)
10270     return None;
10271 
10272   // The predicate must be relational (i.e. <, <=, >=, >).
10273   if (!ICmpInst::isRelational(Pred))
10274     return None;
10275 
10276   // TODO: Support steps other than +/- 1.
10277   const SCEV *Step = AR->getStepRecurrence(*this);
10278   auto *One = getOne(Step->getType());
10279   auto *MinusOne = getNegativeSCEV(One);
10280   if (Step != One && Step != MinusOne)
10281     return None;
10282 
10283   // Type mismatch here means that MaxIter is potentially larger than max
10284   // unsigned value in start type, which mean we cannot prove no wrap for the
10285   // indvar.
10286   if (AR->getType() != MaxIter->getType())
10287     return None;
10288 
10289   // Value of IV on suggested last iteration.
10290   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10291   // Does it still meet the requirement?
10292   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10293     return None;
10294   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10295   // not exceed max unsigned value of this type), this effectively proves
10296   // that there is no wrap during the iteration. To prove that there is no
10297   // signed/unsigned wrap, we need to check that
10298   // Start <= Last for step = 1 or Start >= Last for step = -1.
10299   ICmpInst::Predicate NoOverflowPred =
10300       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10301   if (Step == MinusOne)
10302     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10303   const SCEV *Start = AR->getStart();
10304   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
10305     return None;
10306 
10307   // Everything is fine.
10308   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10309 }
10310 
10311 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10312     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10313   if (HasSameValue(LHS, RHS))
10314     return ICmpInst::isTrueWhenEqual(Pred);
10315 
10316   // This code is split out from isKnownPredicate because it is called from
10317   // within isLoopEntryGuardedByCond.
10318 
10319   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10320                          const ConstantRange &RangeRHS) {
10321     return RangeLHS.icmp(Pred, RangeRHS);
10322   };
10323 
10324   // The check at the top of the function catches the case where the values are
10325   // known to be equal.
10326   if (Pred == CmpInst::ICMP_EQ)
10327     return false;
10328 
10329   if (Pred == CmpInst::ICMP_NE) {
10330     if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10331         CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)))
10332       return true;
10333     auto *Diff = getMinusSCEV(LHS, RHS);
10334     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10335   }
10336 
10337   if (CmpInst::isSigned(Pred))
10338     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10339 
10340   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10341 }
10342 
10343 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10344                                                     const SCEV *LHS,
10345                                                     const SCEV *RHS) {
10346   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10347   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10348   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10349   // OutC1 and OutC2.
10350   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10351                                       APInt &OutC1, APInt &OutC2,
10352                                       SCEV::NoWrapFlags ExpectedFlags) {
10353     const SCEV *XNonConstOp, *XConstOp;
10354     const SCEV *YNonConstOp, *YConstOp;
10355     SCEV::NoWrapFlags XFlagsPresent;
10356     SCEV::NoWrapFlags YFlagsPresent;
10357 
10358     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10359       XConstOp = getZero(X->getType());
10360       XNonConstOp = X;
10361       XFlagsPresent = ExpectedFlags;
10362     }
10363     if (!isa<SCEVConstant>(XConstOp) ||
10364         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10365       return false;
10366 
10367     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10368       YConstOp = getZero(Y->getType());
10369       YNonConstOp = Y;
10370       YFlagsPresent = ExpectedFlags;
10371     }
10372 
10373     if (!isa<SCEVConstant>(YConstOp) ||
10374         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10375       return false;
10376 
10377     if (YNonConstOp != XNonConstOp)
10378       return false;
10379 
10380     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10381     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10382 
10383     return true;
10384   };
10385 
10386   APInt C1;
10387   APInt C2;
10388 
10389   switch (Pred) {
10390   default:
10391     break;
10392 
10393   case ICmpInst::ICMP_SGE:
10394     std::swap(LHS, RHS);
10395     LLVM_FALLTHROUGH;
10396   case ICmpInst::ICMP_SLE:
10397     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10398     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10399       return true;
10400 
10401     break;
10402 
10403   case ICmpInst::ICMP_SGT:
10404     std::swap(LHS, RHS);
10405     LLVM_FALLTHROUGH;
10406   case ICmpInst::ICMP_SLT:
10407     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10408     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10409       return true;
10410 
10411     break;
10412 
10413   case ICmpInst::ICMP_UGE:
10414     std::swap(LHS, RHS);
10415     LLVM_FALLTHROUGH;
10416   case ICmpInst::ICMP_ULE:
10417     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10418     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10419       return true;
10420 
10421     break;
10422 
10423   case ICmpInst::ICMP_UGT:
10424     std::swap(LHS, RHS);
10425     LLVM_FALLTHROUGH;
10426   case ICmpInst::ICMP_ULT:
10427     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10428     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10429       return true;
10430     break;
10431   }
10432 
10433   return false;
10434 }
10435 
10436 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10437                                                    const SCEV *LHS,
10438                                                    const SCEV *RHS) {
10439   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10440     return false;
10441 
10442   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10443   // the stack can result in exponential time complexity.
10444   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10445 
10446   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10447   //
10448   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10449   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10450   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10451   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10452   // use isKnownPredicate later if needed.
10453   return isKnownNonNegative(RHS) &&
10454          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10455          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10456 }
10457 
10458 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10459                                         ICmpInst::Predicate Pred,
10460                                         const SCEV *LHS, const SCEV *RHS) {
10461   // No need to even try if we know the module has no guards.
10462   if (!HasGuards)
10463     return false;
10464 
10465   return any_of(*BB, [&](const Instruction &I) {
10466     using namespace llvm::PatternMatch;
10467 
10468     Value *Condition;
10469     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10470                          m_Value(Condition))) &&
10471            isImpliedCond(Pred, LHS, RHS, Condition, false);
10472   });
10473 }
10474 
10475 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10476 /// protected by a conditional between LHS and RHS.  This is used to
10477 /// to eliminate casts.
10478 bool
10479 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10480                                              ICmpInst::Predicate Pred,
10481                                              const SCEV *LHS, const SCEV *RHS) {
10482   // Interpret a null as meaning no loop, where there is obviously no guard
10483   // (interprocedural conditions notwithstanding).
10484   if (!L) return true;
10485 
10486   if (VerifyIR)
10487     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10488            "This cannot be done on broken IR!");
10489 
10490 
10491   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10492     return true;
10493 
10494   BasicBlock *Latch = L->getLoopLatch();
10495   if (!Latch)
10496     return false;
10497 
10498   BranchInst *LoopContinuePredicate =
10499     dyn_cast<BranchInst>(Latch->getTerminator());
10500   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10501       isImpliedCond(Pred, LHS, RHS,
10502                     LoopContinuePredicate->getCondition(),
10503                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10504     return true;
10505 
10506   // We don't want more than one activation of the following loops on the stack
10507   // -- that can lead to O(n!) time complexity.
10508   if (WalkingBEDominatingConds)
10509     return false;
10510 
10511   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10512 
10513   // See if we can exploit a trip count to prove the predicate.
10514   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10515   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10516   if (LatchBECount != getCouldNotCompute()) {
10517     // We know that Latch branches back to the loop header exactly
10518     // LatchBECount times.  This means the backdege condition at Latch is
10519     // equivalent to  "{0,+,1} u< LatchBECount".
10520     Type *Ty = LatchBECount->getType();
10521     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10522     const SCEV *LoopCounter =
10523       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10524     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10525                       LatchBECount))
10526       return true;
10527   }
10528 
10529   // Check conditions due to any @llvm.assume intrinsics.
10530   for (auto &AssumeVH : AC.assumptions()) {
10531     if (!AssumeVH)
10532       continue;
10533     auto *CI = cast<CallInst>(AssumeVH);
10534     if (!DT.dominates(CI, Latch->getTerminator()))
10535       continue;
10536 
10537     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10538       return true;
10539   }
10540 
10541   // If the loop is not reachable from the entry block, we risk running into an
10542   // infinite loop as we walk up into the dom tree.  These loops do not matter
10543   // anyway, so we just return a conservative answer when we see them.
10544   if (!DT.isReachableFromEntry(L->getHeader()))
10545     return false;
10546 
10547   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10548     return true;
10549 
10550   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10551        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10552     assert(DTN && "should reach the loop header before reaching the root!");
10553 
10554     BasicBlock *BB = DTN->getBlock();
10555     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10556       return true;
10557 
10558     BasicBlock *PBB = BB->getSinglePredecessor();
10559     if (!PBB)
10560       continue;
10561 
10562     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10563     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10564       continue;
10565 
10566     Value *Condition = ContinuePredicate->getCondition();
10567 
10568     // If we have an edge `E` within the loop body that dominates the only
10569     // latch, the condition guarding `E` also guards the backedge.  This
10570     // reasoning works only for loops with a single latch.
10571 
10572     BasicBlockEdge DominatingEdge(PBB, BB);
10573     if (DominatingEdge.isSingleEdge()) {
10574       // We're constructively (and conservatively) enumerating edges within the
10575       // loop body that dominate the latch.  The dominator tree better agree
10576       // with us on this:
10577       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10578 
10579       if (isImpliedCond(Pred, LHS, RHS, Condition,
10580                         BB != ContinuePredicate->getSuccessor(0)))
10581         return true;
10582     }
10583   }
10584 
10585   return false;
10586 }
10587 
10588 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10589                                                      ICmpInst::Predicate Pred,
10590                                                      const SCEV *LHS,
10591                                                      const SCEV *RHS) {
10592   if (VerifyIR)
10593     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10594            "This cannot be done on broken IR!");
10595 
10596   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10597   // the facts (a >= b && a != b) separately. A typical situation is when the
10598   // non-strict comparison is known from ranges and non-equality is known from
10599   // dominating predicates. If we are proving strict comparison, we always try
10600   // to prove non-equality and non-strict comparison separately.
10601   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10602   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10603   bool ProvedNonStrictComparison = false;
10604   bool ProvedNonEquality = false;
10605 
10606   auto SplitAndProve =
10607     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10608     if (!ProvedNonStrictComparison)
10609       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10610     if (!ProvedNonEquality)
10611       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10612     if (ProvedNonStrictComparison && ProvedNonEquality)
10613       return true;
10614     return false;
10615   };
10616 
10617   if (ProvingStrictComparison) {
10618     auto ProofFn = [&](ICmpInst::Predicate P) {
10619       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10620     };
10621     if (SplitAndProve(ProofFn))
10622       return true;
10623   }
10624 
10625   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10626   auto ProveViaGuard = [&](const BasicBlock *Block) {
10627     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10628       return true;
10629     if (ProvingStrictComparison) {
10630       auto ProofFn = [&](ICmpInst::Predicate P) {
10631         return isImpliedViaGuard(Block, P, LHS, RHS);
10632       };
10633       if (SplitAndProve(ProofFn))
10634         return true;
10635     }
10636     return false;
10637   };
10638 
10639   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10640   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10641     const Instruction *CtxI = &BB->front();
10642     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
10643       return true;
10644     if (ProvingStrictComparison) {
10645       auto ProofFn = [&](ICmpInst::Predicate P) {
10646         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
10647       };
10648       if (SplitAndProve(ProofFn))
10649         return true;
10650     }
10651     return false;
10652   };
10653 
10654   // Starting at the block's predecessor, climb up the predecessor chain, as long
10655   // as there are predecessors that can be found that have unique successors
10656   // leading to the original block.
10657   const Loop *ContainingLoop = LI.getLoopFor(BB);
10658   const BasicBlock *PredBB;
10659   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10660     PredBB = ContainingLoop->getLoopPredecessor();
10661   else
10662     PredBB = BB->getSinglePredecessor();
10663   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10664        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10665     if (ProveViaGuard(Pair.first))
10666       return true;
10667 
10668     const BranchInst *LoopEntryPredicate =
10669         dyn_cast<BranchInst>(Pair.first->getTerminator());
10670     if (!LoopEntryPredicate ||
10671         LoopEntryPredicate->isUnconditional())
10672       continue;
10673 
10674     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10675                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10676       return true;
10677   }
10678 
10679   // Check conditions due to any @llvm.assume intrinsics.
10680   for (auto &AssumeVH : AC.assumptions()) {
10681     if (!AssumeVH)
10682       continue;
10683     auto *CI = cast<CallInst>(AssumeVH);
10684     if (!DT.dominates(CI, BB))
10685       continue;
10686 
10687     if (ProveViaCond(CI->getArgOperand(0), false))
10688       return true;
10689   }
10690 
10691   return false;
10692 }
10693 
10694 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10695                                                ICmpInst::Predicate Pred,
10696                                                const SCEV *LHS,
10697                                                const SCEV *RHS) {
10698   // Interpret a null as meaning no loop, where there is obviously no guard
10699   // (interprocedural conditions notwithstanding).
10700   if (!L)
10701     return false;
10702 
10703   // Both LHS and RHS must be available at loop entry.
10704   assert(isAvailableAtLoopEntry(LHS, L) &&
10705          "LHS is not available at Loop Entry");
10706   assert(isAvailableAtLoopEntry(RHS, L) &&
10707          "RHS is not available at Loop Entry");
10708 
10709   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10710     return true;
10711 
10712   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10713 }
10714 
10715 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10716                                     const SCEV *RHS,
10717                                     const Value *FoundCondValue, bool Inverse,
10718                                     const Instruction *CtxI) {
10719   // False conditions implies anything. Do not bother analyzing it further.
10720   if (FoundCondValue ==
10721       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10722     return true;
10723 
10724   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10725     return false;
10726 
10727   auto ClearOnExit =
10728       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10729 
10730   // Recursively handle And and Or conditions.
10731   const Value *Op0, *Op1;
10732   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10733     if (!Inverse)
10734       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
10735              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
10736   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10737     if (Inverse)
10738       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
10739              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
10740   }
10741 
10742   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10743   if (!ICI) return false;
10744 
10745   // Now that we found a conditional branch that dominates the loop or controls
10746   // the loop latch. Check to see if it is the comparison we are looking for.
10747   ICmpInst::Predicate FoundPred;
10748   if (Inverse)
10749     FoundPred = ICI->getInversePredicate();
10750   else
10751     FoundPred = ICI->getPredicate();
10752 
10753   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10754   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10755 
10756   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
10757 }
10758 
10759 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10760                                     const SCEV *RHS,
10761                                     ICmpInst::Predicate FoundPred,
10762                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10763                                     const Instruction *CtxI) {
10764   // Balance the types.
10765   if (getTypeSizeInBits(LHS->getType()) <
10766       getTypeSizeInBits(FoundLHS->getType())) {
10767     // For unsigned and equality predicates, try to prove that both found
10768     // operands fit into narrow unsigned range. If so, try to prove facts in
10769     // narrow types.
10770     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) {
10771       auto *NarrowType = LHS->getType();
10772       auto *WideType = FoundLHS->getType();
10773       auto BitWidth = getTypeSizeInBits(NarrowType);
10774       const SCEV *MaxValue = getZeroExtendExpr(
10775           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10776       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
10777                                           MaxValue) &&
10778           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
10779                                           MaxValue)) {
10780         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10781         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10782         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10783                                        TruncFoundRHS, CtxI))
10784           return true;
10785       }
10786     }
10787 
10788     if (LHS->getType()->isPointerTy())
10789       return false;
10790     if (CmpInst::isSigned(Pred)) {
10791       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10792       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10793     } else {
10794       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10795       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10796     }
10797   } else if (getTypeSizeInBits(LHS->getType()) >
10798       getTypeSizeInBits(FoundLHS->getType())) {
10799     if (FoundLHS->getType()->isPointerTy())
10800       return false;
10801     if (CmpInst::isSigned(FoundPred)) {
10802       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10803       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10804     } else {
10805       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10806       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10807     }
10808   }
10809   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10810                                     FoundRHS, CtxI);
10811 }
10812 
10813 bool ScalarEvolution::isImpliedCondBalancedTypes(
10814     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10815     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10816     const Instruction *CtxI) {
10817   assert(getTypeSizeInBits(LHS->getType()) ==
10818              getTypeSizeInBits(FoundLHS->getType()) &&
10819          "Types should be balanced!");
10820   // Canonicalize the query to match the way instcombine will have
10821   // canonicalized the comparison.
10822   if (SimplifyICmpOperands(Pred, LHS, RHS))
10823     if (LHS == RHS)
10824       return CmpInst::isTrueWhenEqual(Pred);
10825   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10826     if (FoundLHS == FoundRHS)
10827       return CmpInst::isFalseWhenEqual(FoundPred);
10828 
10829   // Check to see if we can make the LHS or RHS match.
10830   if (LHS == FoundRHS || RHS == FoundLHS) {
10831     if (isa<SCEVConstant>(RHS)) {
10832       std::swap(FoundLHS, FoundRHS);
10833       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10834     } else {
10835       std::swap(LHS, RHS);
10836       Pred = ICmpInst::getSwappedPredicate(Pred);
10837     }
10838   }
10839 
10840   // Check whether the found predicate is the same as the desired predicate.
10841   if (FoundPred == Pred)
10842     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
10843 
10844   // Check whether swapping the found predicate makes it the same as the
10845   // desired predicate.
10846   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10847     // We can write the implication
10848     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10849     // using one of the following ways:
10850     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10851     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10852     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10853     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10854     // Forms 1. and 2. require swapping the operands of one condition. Don't
10855     // do this if it would break canonical constant/addrec ordering.
10856     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10857       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10858                                    CtxI);
10859     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10860       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
10861 
10862     // There's no clear preference between forms 3. and 4., try both.  Avoid
10863     // forming getNotSCEV of pointer values as the resulting subtract is
10864     // not legal.
10865     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
10866         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10867                               FoundLHS, FoundRHS, CtxI))
10868       return true;
10869 
10870     if (!FoundLHS->getType()->isPointerTy() &&
10871         !FoundRHS->getType()->isPointerTy() &&
10872         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10873                               getNotSCEV(FoundRHS), CtxI))
10874       return true;
10875 
10876     return false;
10877   }
10878 
10879   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
10880                                    CmpInst::Predicate P2) {
10881     assert(P1 != P2 && "Handled earlier!");
10882     return CmpInst::isRelational(P2) &&
10883            P1 == CmpInst::getFlippedSignednessPredicate(P2);
10884   };
10885   if (IsSignFlippedPredicate(Pred, FoundPred)) {
10886     // Unsigned comparison is the same as signed comparison when both the
10887     // operands are non-negative or negative.
10888     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
10889         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
10890       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
10891     // Create local copies that we can freely swap and canonicalize our
10892     // conditions to "le/lt".
10893     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
10894     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
10895                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
10896     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
10897       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
10898       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
10899       std::swap(CanonicalLHS, CanonicalRHS);
10900       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
10901     }
10902     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
10903            "Must be!");
10904     assert((ICmpInst::isLT(CanonicalFoundPred) ||
10905             ICmpInst::isLE(CanonicalFoundPred)) &&
10906            "Must be!");
10907     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
10908       // Use implication:
10909       // x <u y && y >=s 0 --> x <s y.
10910       // If we can prove the left part, the right part is also proven.
10911       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
10912                                    CanonicalRHS, CanonicalFoundLHS,
10913                                    CanonicalFoundRHS);
10914     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
10915       // Use implication:
10916       // x <s y && y <s 0 --> x <u y.
10917       // If we can prove the left part, the right part is also proven.
10918       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
10919                                    CanonicalRHS, CanonicalFoundLHS,
10920                                    CanonicalFoundRHS);
10921   }
10922 
10923   // Check if we can make progress by sharpening ranges.
10924   if (FoundPred == ICmpInst::ICMP_NE &&
10925       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10926 
10927     const SCEVConstant *C = nullptr;
10928     const SCEV *V = nullptr;
10929 
10930     if (isa<SCEVConstant>(FoundLHS)) {
10931       C = cast<SCEVConstant>(FoundLHS);
10932       V = FoundRHS;
10933     } else {
10934       C = cast<SCEVConstant>(FoundRHS);
10935       V = FoundLHS;
10936     }
10937 
10938     // The guarding predicate tells us that C != V. If the known range
10939     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10940     // range we consider has to correspond to same signedness as the
10941     // predicate we're interested in folding.
10942 
10943     APInt Min = ICmpInst::isSigned(Pred) ?
10944         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10945 
10946     if (Min == C->getAPInt()) {
10947       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10948       // This is true even if (Min + 1) wraps around -- in case of
10949       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10950 
10951       APInt SharperMin = Min + 1;
10952 
10953       switch (Pred) {
10954         case ICmpInst::ICMP_SGE:
10955         case ICmpInst::ICMP_UGE:
10956           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10957           // RHS, we're done.
10958           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10959                                     CtxI))
10960             return true;
10961           LLVM_FALLTHROUGH;
10962 
10963         case ICmpInst::ICMP_SGT:
10964         case ICmpInst::ICMP_UGT:
10965           // We know from the range information that (V `Pred` Min ||
10966           // V == Min).  We know from the guarding condition that !(V
10967           // == Min).  This gives us
10968           //
10969           //       V `Pred` Min || V == Min && !(V == Min)
10970           //   =>  V `Pred` Min
10971           //
10972           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10973 
10974           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
10975             return true;
10976           break;
10977 
10978         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10979         case ICmpInst::ICMP_SLE:
10980         case ICmpInst::ICMP_ULE:
10981           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10982                                     LHS, V, getConstant(SharperMin), CtxI))
10983             return true;
10984           LLVM_FALLTHROUGH;
10985 
10986         case ICmpInst::ICMP_SLT:
10987         case ICmpInst::ICMP_ULT:
10988           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10989                                     LHS, V, getConstant(Min), CtxI))
10990             return true;
10991           break;
10992 
10993         default:
10994           // No change
10995           break;
10996       }
10997     }
10998   }
10999 
11000   // Check whether the actual condition is beyond sufficient.
11001   if (FoundPred == ICmpInst::ICMP_EQ)
11002     if (ICmpInst::isTrueWhenEqual(Pred))
11003       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11004         return true;
11005   if (Pred == ICmpInst::ICMP_NE)
11006     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11007       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11008         return true;
11009 
11010   // Otherwise assume the worst.
11011   return false;
11012 }
11013 
11014 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11015                                      const SCEV *&L, const SCEV *&R,
11016                                      SCEV::NoWrapFlags &Flags) {
11017   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11018   if (!AE || AE->getNumOperands() != 2)
11019     return false;
11020 
11021   L = AE->getOperand(0);
11022   R = AE->getOperand(1);
11023   Flags = AE->getNoWrapFlags();
11024   return true;
11025 }
11026 
11027 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
11028                                                            const SCEV *Less) {
11029   // We avoid subtracting expressions here because this function is usually
11030   // fairly deep in the call stack (i.e. is called many times).
11031 
11032   // X - X = 0.
11033   if (More == Less)
11034     return APInt(getTypeSizeInBits(More->getType()), 0);
11035 
11036   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11037     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11038     const auto *MAR = cast<SCEVAddRecExpr>(More);
11039 
11040     if (LAR->getLoop() != MAR->getLoop())
11041       return None;
11042 
11043     // We look at affine expressions only; not for correctness but to keep
11044     // getStepRecurrence cheap.
11045     if (!LAR->isAffine() || !MAR->isAffine())
11046       return None;
11047 
11048     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11049       return None;
11050 
11051     Less = LAR->getStart();
11052     More = MAR->getStart();
11053 
11054     // fall through
11055   }
11056 
11057   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11058     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11059     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11060     return M - L;
11061   }
11062 
11063   SCEV::NoWrapFlags Flags;
11064   const SCEV *LLess = nullptr, *RLess = nullptr;
11065   const SCEV *LMore = nullptr, *RMore = nullptr;
11066   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11067   // Compare (X + C1) vs X.
11068   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11069     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11070       if (RLess == More)
11071         return -(C1->getAPInt());
11072 
11073   // Compare X vs (X + C2).
11074   if (splitBinaryAdd(More, LMore, RMore, Flags))
11075     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11076       if (RMore == Less)
11077         return C2->getAPInt();
11078 
11079   // Compare (X + C1) vs (X + C2).
11080   if (C1 && C2 && RLess == RMore)
11081     return C2->getAPInt() - C1->getAPInt();
11082 
11083   return None;
11084 }
11085 
11086 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11087     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11088     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11089   // Try to recognize the following pattern:
11090   //
11091   //   FoundRHS = ...
11092   // ...
11093   // loop:
11094   //   FoundLHS = {Start,+,W}
11095   // context_bb: // Basic block from the same loop
11096   //   known(Pred, FoundLHS, FoundRHS)
11097   //
11098   // If some predicate is known in the context of a loop, it is also known on
11099   // each iteration of this loop, including the first iteration. Therefore, in
11100   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11101   // prove the original pred using this fact.
11102   if (!CtxI)
11103     return false;
11104   const BasicBlock *ContextBB = CtxI->getParent();
11105   // Make sure AR varies in the context block.
11106   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11107     const Loop *L = AR->getLoop();
11108     // Make sure that context belongs to the loop and executes on 1st iteration
11109     // (if it ever executes at all).
11110     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11111       return false;
11112     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11113       return false;
11114     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11115   }
11116 
11117   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11118     const Loop *L = AR->getLoop();
11119     // Make sure that context belongs to the loop and executes on 1st iteration
11120     // (if it ever executes at all).
11121     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11122       return false;
11123     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11124       return false;
11125     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11126   }
11127 
11128   return false;
11129 }
11130 
11131 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11132     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11133     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11134   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11135     return false;
11136 
11137   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11138   if (!AddRecLHS)
11139     return false;
11140 
11141   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11142   if (!AddRecFoundLHS)
11143     return false;
11144 
11145   // We'd like to let SCEV reason about control dependencies, so we constrain
11146   // both the inequalities to be about add recurrences on the same loop.  This
11147   // way we can use isLoopEntryGuardedByCond later.
11148 
11149   const Loop *L = AddRecFoundLHS->getLoop();
11150   if (L != AddRecLHS->getLoop())
11151     return false;
11152 
11153   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11154   //
11155   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11156   //                                                                  ... (2)
11157   //
11158   // Informal proof for (2), assuming (1) [*]:
11159   //
11160   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11161   //
11162   // Then
11163   //
11164   //       FoundLHS s< FoundRHS s< INT_MIN - C
11165   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11166   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11167   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11168   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11169   // <=>  FoundLHS + C s< FoundRHS + C
11170   //
11171   // [*]: (1) can be proved by ruling out overflow.
11172   //
11173   // [**]: This can be proved by analyzing all the four possibilities:
11174   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11175   //    (A s>= 0, B s>= 0).
11176   //
11177   // Note:
11178   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11179   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11180   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11181   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11182   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11183   // C)".
11184 
11185   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11186   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11187   if (!LDiff || !RDiff || *LDiff != *RDiff)
11188     return false;
11189 
11190   if (LDiff->isMinValue())
11191     return true;
11192 
11193   APInt FoundRHSLimit;
11194 
11195   if (Pred == CmpInst::ICMP_ULT) {
11196     FoundRHSLimit = -(*RDiff);
11197   } else {
11198     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11199     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11200   }
11201 
11202   // Try to prove (1) or (2), as needed.
11203   return isAvailableAtLoopEntry(FoundRHS, L) &&
11204          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11205                                   getConstant(FoundRHSLimit));
11206 }
11207 
11208 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11209                                         const SCEV *LHS, const SCEV *RHS,
11210                                         const SCEV *FoundLHS,
11211                                         const SCEV *FoundRHS, unsigned Depth) {
11212   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11213 
11214   auto ClearOnExit = make_scope_exit([&]() {
11215     if (LPhi) {
11216       bool Erased = PendingMerges.erase(LPhi);
11217       assert(Erased && "Failed to erase LPhi!");
11218       (void)Erased;
11219     }
11220     if (RPhi) {
11221       bool Erased = PendingMerges.erase(RPhi);
11222       assert(Erased && "Failed to erase RPhi!");
11223       (void)Erased;
11224     }
11225   });
11226 
11227   // Find respective Phis and check that they are not being pending.
11228   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11229     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11230       if (!PendingMerges.insert(Phi).second)
11231         return false;
11232       LPhi = Phi;
11233     }
11234   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11235     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11236       // If we detect a loop of Phi nodes being processed by this method, for
11237       // example:
11238       //
11239       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11240       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11241       //
11242       // we don't want to deal with a case that complex, so return conservative
11243       // answer false.
11244       if (!PendingMerges.insert(Phi).second)
11245         return false;
11246       RPhi = Phi;
11247     }
11248 
11249   // If none of LHS, RHS is a Phi, nothing to do here.
11250   if (!LPhi && !RPhi)
11251     return false;
11252 
11253   // If there is a SCEVUnknown Phi we are interested in, make it left.
11254   if (!LPhi) {
11255     std::swap(LHS, RHS);
11256     std::swap(FoundLHS, FoundRHS);
11257     std::swap(LPhi, RPhi);
11258     Pred = ICmpInst::getSwappedPredicate(Pred);
11259   }
11260 
11261   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11262   const BasicBlock *LBB = LPhi->getParent();
11263   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11264 
11265   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11266     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11267            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11268            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11269   };
11270 
11271   if (RPhi && RPhi->getParent() == LBB) {
11272     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11273     // If we compare two Phis from the same block, and for each entry block
11274     // the predicate is true for incoming values from this block, then the
11275     // predicate is also true for the Phis.
11276     for (const BasicBlock *IncBB : predecessors(LBB)) {
11277       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11278       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11279       if (!ProvedEasily(L, R))
11280         return false;
11281     }
11282   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11283     // Case two: RHS is also a Phi from the same basic block, and it is an
11284     // AddRec. It means that there is a loop which has both AddRec and Unknown
11285     // PHIs, for it we can compare incoming values of AddRec from above the loop
11286     // and latch with their respective incoming values of LPhi.
11287     // TODO: Generalize to handle loops with many inputs in a header.
11288     if (LPhi->getNumIncomingValues() != 2) return false;
11289 
11290     auto *RLoop = RAR->getLoop();
11291     auto *Predecessor = RLoop->getLoopPredecessor();
11292     assert(Predecessor && "Loop with AddRec with no predecessor?");
11293     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11294     if (!ProvedEasily(L1, RAR->getStart()))
11295       return false;
11296     auto *Latch = RLoop->getLoopLatch();
11297     assert(Latch && "Loop with AddRec with no latch?");
11298     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11299     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11300       return false;
11301   } else {
11302     // In all other cases go over inputs of LHS and compare each of them to RHS,
11303     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11304     // At this point RHS is either a non-Phi, or it is a Phi from some block
11305     // different from LBB.
11306     for (const BasicBlock *IncBB : predecessors(LBB)) {
11307       // Check that RHS is available in this block.
11308       if (!dominates(RHS, IncBB))
11309         return false;
11310       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11311       // Make sure L does not refer to a value from a potentially previous
11312       // iteration of a loop.
11313       if (!properlyDominates(L, IncBB))
11314         return false;
11315       if (!ProvedEasily(L, RHS))
11316         return false;
11317     }
11318   }
11319   return true;
11320 }
11321 
11322 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11323                                             const SCEV *LHS, const SCEV *RHS,
11324                                             const SCEV *FoundLHS,
11325                                             const SCEV *FoundRHS,
11326                                             const Instruction *CtxI) {
11327   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11328     return true;
11329 
11330   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11331     return true;
11332 
11333   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11334                                           CtxI))
11335     return true;
11336 
11337   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11338                                      FoundLHS, FoundRHS);
11339 }
11340 
11341 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11342 template <typename MinMaxExprType>
11343 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11344                                  const SCEV *Candidate) {
11345   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11346   if (!MinMaxExpr)
11347     return false;
11348 
11349   return is_contained(MinMaxExpr->operands(), Candidate);
11350 }
11351 
11352 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11353                                            ICmpInst::Predicate Pred,
11354                                            const SCEV *LHS, const SCEV *RHS) {
11355   // If both sides are affine addrecs for the same loop, with equal
11356   // steps, and we know the recurrences don't wrap, then we only
11357   // need to check the predicate on the starting values.
11358 
11359   if (!ICmpInst::isRelational(Pred))
11360     return false;
11361 
11362   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11363   if (!LAR)
11364     return false;
11365   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11366   if (!RAR)
11367     return false;
11368   if (LAR->getLoop() != RAR->getLoop())
11369     return false;
11370   if (!LAR->isAffine() || !RAR->isAffine())
11371     return false;
11372 
11373   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11374     return false;
11375 
11376   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11377                          SCEV::FlagNSW : SCEV::FlagNUW;
11378   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11379     return false;
11380 
11381   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11382 }
11383 
11384 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11385 /// expression?
11386 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11387                                         ICmpInst::Predicate Pred,
11388                                         const SCEV *LHS, const SCEV *RHS) {
11389   switch (Pred) {
11390   default:
11391     return false;
11392 
11393   case ICmpInst::ICMP_SGE:
11394     std::swap(LHS, RHS);
11395     LLVM_FALLTHROUGH;
11396   case ICmpInst::ICMP_SLE:
11397     return
11398         // min(A, ...) <= A
11399         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11400         // A <= max(A, ...)
11401         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11402 
11403   case ICmpInst::ICMP_UGE:
11404     std::swap(LHS, RHS);
11405     LLVM_FALLTHROUGH;
11406   case ICmpInst::ICMP_ULE:
11407     return
11408         // min(A, ...) <= A
11409         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11410         // A <= max(A, ...)
11411         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11412   }
11413 
11414   llvm_unreachable("covered switch fell through?!");
11415 }
11416 
11417 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11418                                              const SCEV *LHS, const SCEV *RHS,
11419                                              const SCEV *FoundLHS,
11420                                              const SCEV *FoundRHS,
11421                                              unsigned Depth) {
11422   assert(getTypeSizeInBits(LHS->getType()) ==
11423              getTypeSizeInBits(RHS->getType()) &&
11424          "LHS and RHS have different sizes?");
11425   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11426              getTypeSizeInBits(FoundRHS->getType()) &&
11427          "FoundLHS and FoundRHS have different sizes?");
11428   // We want to avoid hurting the compile time with analysis of too big trees.
11429   if (Depth > MaxSCEVOperationsImplicationDepth)
11430     return false;
11431 
11432   // We only want to work with GT comparison so far.
11433   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11434     Pred = CmpInst::getSwappedPredicate(Pred);
11435     std::swap(LHS, RHS);
11436     std::swap(FoundLHS, FoundRHS);
11437   }
11438 
11439   // For unsigned, try to reduce it to corresponding signed comparison.
11440   if (Pred == ICmpInst::ICMP_UGT)
11441     // We can replace unsigned predicate with its signed counterpart if all
11442     // involved values are non-negative.
11443     // TODO: We could have better support for unsigned.
11444     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11445       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11446       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11447       // use this fact to prove that LHS and RHS are non-negative.
11448       const SCEV *MinusOne = getMinusOne(LHS->getType());
11449       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11450                                 FoundRHS) &&
11451           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11452                                 FoundRHS))
11453         Pred = ICmpInst::ICMP_SGT;
11454     }
11455 
11456   if (Pred != ICmpInst::ICMP_SGT)
11457     return false;
11458 
11459   auto GetOpFromSExt = [&](const SCEV *S) {
11460     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11461       return Ext->getOperand();
11462     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11463     // the constant in some cases.
11464     return S;
11465   };
11466 
11467   // Acquire values from extensions.
11468   auto *OrigLHS = LHS;
11469   auto *OrigFoundLHS = FoundLHS;
11470   LHS = GetOpFromSExt(LHS);
11471   FoundLHS = GetOpFromSExt(FoundLHS);
11472 
11473   // Is the SGT predicate can be proved trivially or using the found context.
11474   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11475     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11476            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11477                                   FoundRHS, Depth + 1);
11478   };
11479 
11480   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11481     // We want to avoid creation of any new non-constant SCEV. Since we are
11482     // going to compare the operands to RHS, we should be certain that we don't
11483     // need any size extensions for this. So let's decline all cases when the
11484     // sizes of types of LHS and RHS do not match.
11485     // TODO: Maybe try to get RHS from sext to catch more cases?
11486     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11487       return false;
11488 
11489     // Should not overflow.
11490     if (!LHSAddExpr->hasNoSignedWrap())
11491       return false;
11492 
11493     auto *LL = LHSAddExpr->getOperand(0);
11494     auto *LR = LHSAddExpr->getOperand(1);
11495     auto *MinusOne = getMinusOne(RHS->getType());
11496 
11497     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11498     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11499       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11500     };
11501     // Try to prove the following rule:
11502     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11503     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11504     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11505       return true;
11506   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11507     Value *LL, *LR;
11508     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11509 
11510     using namespace llvm::PatternMatch;
11511 
11512     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11513       // Rules for division.
11514       // We are going to perform some comparisons with Denominator and its
11515       // derivative expressions. In general case, creating a SCEV for it may
11516       // lead to a complex analysis of the entire graph, and in particular it
11517       // can request trip count recalculation for the same loop. This would
11518       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11519       // this, we only want to create SCEVs that are constants in this section.
11520       // So we bail if Denominator is not a constant.
11521       if (!isa<ConstantInt>(LR))
11522         return false;
11523 
11524       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11525 
11526       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11527       // then a SCEV for the numerator already exists and matches with FoundLHS.
11528       auto *Numerator = getExistingSCEV(LL);
11529       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11530         return false;
11531 
11532       // Make sure that the numerator matches with FoundLHS and the denominator
11533       // is positive.
11534       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11535         return false;
11536 
11537       auto *DTy = Denominator->getType();
11538       auto *FRHSTy = FoundRHS->getType();
11539       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11540         // One of types is a pointer and another one is not. We cannot extend
11541         // them properly to a wider type, so let us just reject this case.
11542         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11543         // to avoid this check.
11544         return false;
11545 
11546       // Given that:
11547       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11548       auto *WTy = getWiderType(DTy, FRHSTy);
11549       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11550       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11551 
11552       // Try to prove the following rule:
11553       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11554       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11555       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11556       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11557       if (isKnownNonPositive(RHS) &&
11558           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11559         return true;
11560 
11561       // Try to prove the following rule:
11562       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11563       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11564       // If we divide it by Denominator > 2, then:
11565       // 1. If FoundLHS is negative, then the result is 0.
11566       // 2. If FoundLHS is non-negative, then the result is non-negative.
11567       // Anyways, the result is non-negative.
11568       auto *MinusOne = getMinusOne(WTy);
11569       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11570       if (isKnownNegative(RHS) &&
11571           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11572         return true;
11573     }
11574   }
11575 
11576   // If our expression contained SCEVUnknown Phis, and we split it down and now
11577   // need to prove something for them, try to prove the predicate for every
11578   // possible incoming values of those Phis.
11579   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11580     return true;
11581 
11582   return false;
11583 }
11584 
11585 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11586                                         const SCEV *LHS, const SCEV *RHS) {
11587   // zext x u<= sext x, sext x s<= zext x
11588   switch (Pred) {
11589   case ICmpInst::ICMP_SGE:
11590     std::swap(LHS, RHS);
11591     LLVM_FALLTHROUGH;
11592   case ICmpInst::ICMP_SLE: {
11593     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11594     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11595     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11596     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11597       return true;
11598     break;
11599   }
11600   case ICmpInst::ICMP_UGE:
11601     std::swap(LHS, RHS);
11602     LLVM_FALLTHROUGH;
11603   case ICmpInst::ICMP_ULE: {
11604     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11605     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11606     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11607     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11608       return true;
11609     break;
11610   }
11611   default:
11612     break;
11613   };
11614   return false;
11615 }
11616 
11617 bool
11618 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11619                                            const SCEV *LHS, const SCEV *RHS) {
11620   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11621          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11622          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11623          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11624          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11625 }
11626 
11627 bool
11628 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11629                                              const SCEV *LHS, const SCEV *RHS,
11630                                              const SCEV *FoundLHS,
11631                                              const SCEV *FoundRHS) {
11632   switch (Pred) {
11633   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11634   case ICmpInst::ICMP_EQ:
11635   case ICmpInst::ICMP_NE:
11636     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11637       return true;
11638     break;
11639   case ICmpInst::ICMP_SLT:
11640   case ICmpInst::ICMP_SLE:
11641     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11642         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11643       return true;
11644     break;
11645   case ICmpInst::ICMP_SGT:
11646   case ICmpInst::ICMP_SGE:
11647     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11648         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11649       return true;
11650     break;
11651   case ICmpInst::ICMP_ULT:
11652   case ICmpInst::ICMP_ULE:
11653     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11654         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11655       return true;
11656     break;
11657   case ICmpInst::ICMP_UGT:
11658   case ICmpInst::ICMP_UGE:
11659     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11660         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11661       return true;
11662     break;
11663   }
11664 
11665   // Maybe it can be proved via operations?
11666   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11667     return true;
11668 
11669   return false;
11670 }
11671 
11672 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11673                                                      const SCEV *LHS,
11674                                                      const SCEV *RHS,
11675                                                      const SCEV *FoundLHS,
11676                                                      const SCEV *FoundRHS) {
11677   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11678     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11679     // reduce the compile time impact of this optimization.
11680     return false;
11681 
11682   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11683   if (!Addend)
11684     return false;
11685 
11686   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11687 
11688   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11689   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11690   ConstantRange FoundLHSRange =
11691       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
11692 
11693   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11694   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11695 
11696   // We can also compute the range of values for `LHS` that satisfy the
11697   // consequent, "`LHS` `Pred` `RHS`":
11698   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11699   // The antecedent implies the consequent if every value of `LHS` that
11700   // satisfies the antecedent also satisfies the consequent.
11701   return LHSRange.icmp(Pred, ConstRHS);
11702 }
11703 
11704 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11705                                         bool IsSigned) {
11706   assert(isKnownPositive(Stride) && "Positive stride expected!");
11707 
11708   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11709   const SCEV *One = getOne(Stride->getType());
11710 
11711   if (IsSigned) {
11712     APInt MaxRHS = getSignedRangeMax(RHS);
11713     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11714     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11715 
11716     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11717     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11718   }
11719 
11720   APInt MaxRHS = getUnsignedRangeMax(RHS);
11721   APInt MaxValue = APInt::getMaxValue(BitWidth);
11722   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11723 
11724   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11725   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11726 }
11727 
11728 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11729                                         bool IsSigned) {
11730 
11731   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11732   const SCEV *One = getOne(Stride->getType());
11733 
11734   if (IsSigned) {
11735     APInt MinRHS = getSignedRangeMin(RHS);
11736     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11737     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11738 
11739     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11740     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11741   }
11742 
11743   APInt MinRHS = getUnsignedRangeMin(RHS);
11744   APInt MinValue = APInt::getMinValue(BitWidth);
11745   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11746 
11747   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11748   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11749 }
11750 
11751 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
11752   // umin(N, 1) + floor((N - umin(N, 1)) / D)
11753   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
11754   // expression fixes the case of N=0.
11755   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
11756   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
11757   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
11758 }
11759 
11760 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11761                                                     const SCEV *Stride,
11762                                                     const SCEV *End,
11763                                                     unsigned BitWidth,
11764                                                     bool IsSigned) {
11765   // The logic in this function assumes we can represent a positive stride.
11766   // If we can't, the backedge-taken count must be zero.
11767   if (IsSigned && BitWidth == 1)
11768     return getZero(Stride->getType());
11769 
11770   // This code has only been closely audited for negative strides in the
11771   // unsigned comparison case, it may be correct for signed comparison, but
11772   // that needs to be established.
11773   assert((!IsSigned || !isKnownNonPositive(Stride)) &&
11774          "Stride is expected strictly positive for signed case!");
11775 
11776   // Calculate the maximum backedge count based on the range of values
11777   // permitted by Start, End, and Stride.
11778   APInt MinStart =
11779       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11780 
11781   APInt MinStride =
11782       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11783 
11784   // We assume either the stride is positive, or the backedge-taken count
11785   // is zero. So force StrideForMaxBECount to be at least one.
11786   APInt One(BitWidth, 1);
11787   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
11788                                        : APIntOps::umax(One, MinStride);
11789 
11790   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11791                             : APInt::getMaxValue(BitWidth);
11792   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11793 
11794   // Although End can be a MAX expression we estimate MaxEnd considering only
11795   // the case End = RHS of the loop termination condition. This is safe because
11796   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11797   // taken count.
11798   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11799                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11800 
11801   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
11802   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
11803                     : APIntOps::umax(MaxEnd, MinStart);
11804 
11805   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
11806                          getConstant(StrideForMaxBECount) /* Step */);
11807 }
11808 
11809 ScalarEvolution::ExitLimit
11810 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11811                                   const Loop *L, bool IsSigned,
11812                                   bool ControlsExit, bool AllowPredicates) {
11813   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11814 
11815   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11816   bool PredicatedIV = false;
11817 
11818   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
11819     // Can we prove this loop *must* be UB if overflow of IV occurs?
11820     // Reasoning goes as follows:
11821     // * Suppose the IV did self wrap.
11822     // * If Stride evenly divides the iteration space, then once wrap
11823     //   occurs, the loop must revisit the same values.
11824     // * We know that RHS is invariant, and that none of those values
11825     //   caused this exit to be taken previously.  Thus, this exit is
11826     //   dynamically dead.
11827     // * If this is the sole exit, then a dead exit implies the loop
11828     //   must be infinite if there are no abnormal exits.
11829     // * If the loop were infinite, then it must either not be mustprogress
11830     //   or have side effects. Otherwise, it must be UB.
11831     // * It can't (by assumption), be UB so we have contradicted our
11832     //   premise and can conclude the IV did not in fact self-wrap.
11833     if (!isLoopInvariant(RHS, L))
11834       return false;
11835 
11836     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
11837     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
11838       return false;
11839 
11840     if (!ControlsExit || !loopHasNoAbnormalExits(L))
11841       return false;
11842 
11843     return loopIsFiniteByAssumption(L);
11844   };
11845 
11846   if (!IV) {
11847     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
11848       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
11849       if (AR && AR->getLoop() == L && AR->isAffine()) {
11850         auto canProveNUW = [&]() {
11851           if (!isLoopInvariant(RHS, L))
11852             return false;
11853 
11854           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
11855             // We need the sequence defined by AR to strictly increase in the
11856             // unsigned integer domain for the logic below to hold.
11857             return false;
11858 
11859           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
11860           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
11861           // If RHS <=u Limit, then there must exist a value V in the sequence
11862           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
11863           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
11864           // overflow occurs.  This limit also implies that a signed comparison
11865           // (in the wide bitwidth) is equivalent to an unsigned comparison as
11866           // the high bits on both sides must be zero.
11867           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
11868           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
11869           Limit = Limit.zext(OuterBitWidth);
11870           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
11871         };
11872         auto Flags = AR->getNoWrapFlags();
11873         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
11874           Flags = setFlags(Flags, SCEV::FlagNUW);
11875 
11876         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
11877         if (AR->hasNoUnsignedWrap()) {
11878           // Emulate what getZeroExtendExpr would have done during construction
11879           // if we'd been able to infer the fact just above at that time.
11880           const SCEV *Step = AR->getStepRecurrence(*this);
11881           Type *Ty = ZExt->getType();
11882           auto *S = getAddRecExpr(
11883             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
11884             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
11885           IV = dyn_cast<SCEVAddRecExpr>(S);
11886         }
11887       }
11888     }
11889   }
11890 
11891 
11892   if (!IV && AllowPredicates) {
11893     // Try to make this an AddRec using runtime tests, in the first X
11894     // iterations of this loop, where X is the SCEV expression found by the
11895     // algorithm below.
11896     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11897     PredicatedIV = true;
11898   }
11899 
11900   // Avoid weird loops
11901   if (!IV || IV->getLoop() != L || !IV->isAffine())
11902     return getCouldNotCompute();
11903 
11904   // A precondition of this method is that the condition being analyzed
11905   // reaches an exiting branch which dominates the latch.  Given that, we can
11906   // assume that an increment which violates the nowrap specification and
11907   // produces poison must cause undefined behavior when the resulting poison
11908   // value is branched upon and thus we can conclude that the backedge is
11909   // taken no more often than would be required to produce that poison value.
11910   // Note that a well defined loop can exit on the iteration which violates
11911   // the nowrap specification if there is another exit (either explicit or
11912   // implicit/exceptional) which causes the loop to execute before the
11913   // exiting instruction we're analyzing would trigger UB.
11914   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11915   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11916   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
11917 
11918   const SCEV *Stride = IV->getStepRecurrence(*this);
11919 
11920   bool PositiveStride = isKnownPositive(Stride);
11921 
11922   // Avoid negative or zero stride values.
11923   if (!PositiveStride) {
11924     // We can compute the correct backedge taken count for loops with unknown
11925     // strides if we can prove that the loop is not an infinite loop with side
11926     // effects. Here's the loop structure we are trying to handle -
11927     //
11928     // i = start
11929     // do {
11930     //   A[i] = i;
11931     //   i += s;
11932     // } while (i < end);
11933     //
11934     // The backedge taken count for such loops is evaluated as -
11935     // (max(end, start + stride) - start - 1) /u stride
11936     //
11937     // The additional preconditions that we need to check to prove correctness
11938     // of the above formula is as follows -
11939     //
11940     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11941     //    NoWrap flag).
11942     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
11943     //    no side effects within the loop)
11944     // c) loop has a single static exit (with no abnormal exits)
11945     //
11946     // Precondition a) implies that if the stride is negative, this is a single
11947     // trip loop. The backedge taken count formula reduces to zero in this case.
11948     //
11949     // Precondition b) and c) combine to imply that if rhs is invariant in L,
11950     // then a zero stride means the backedge can't be taken without executing
11951     // undefined behavior.
11952     //
11953     // The positive stride case is the same as isKnownPositive(Stride) returning
11954     // true (original behavior of the function).
11955     //
11956     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
11957         !loopHasNoAbnormalExits(L))
11958       return getCouldNotCompute();
11959 
11960     // This bailout is protecting the logic in computeMaxBECountForLT which
11961     // has not yet been sufficiently auditted or tested with negative strides.
11962     // We used to filter out all known-non-positive cases here, we're in the
11963     // process of being less restrictive bit by bit.
11964     if (IsSigned && isKnownNonPositive(Stride))
11965       return getCouldNotCompute();
11966 
11967     if (!isKnownNonZero(Stride)) {
11968       // If we have a step of zero, and RHS isn't invariant in L, we don't know
11969       // if it might eventually be greater than start and if so, on which
11970       // iteration.  We can't even produce a useful upper bound.
11971       if (!isLoopInvariant(RHS, L))
11972         return getCouldNotCompute();
11973 
11974       // We allow a potentially zero stride, but we need to divide by stride
11975       // below.  Since the loop can't be infinite and this check must control
11976       // the sole exit, we can infer the exit must be taken on the first
11977       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
11978       // we know the numerator in the divides below must be zero, so we can
11979       // pick an arbitrary non-zero value for the denominator (e.g. stride)
11980       // and produce the right result.
11981       // FIXME: Handle the case where Stride is poison?
11982       auto wouldZeroStrideBeUB = [&]() {
11983         // Proof by contradiction.  Suppose the stride were zero.  If we can
11984         // prove that the backedge *is* taken on the first iteration, then since
11985         // we know this condition controls the sole exit, we must have an
11986         // infinite loop.  We can't have a (well defined) infinite loop per
11987         // check just above.
11988         // Note: The (Start - Stride) term is used to get the start' term from
11989         // (start' + stride,+,stride). Remember that we only care about the
11990         // result of this expression when stride == 0 at runtime.
11991         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
11992         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
11993       };
11994       if (!wouldZeroStrideBeUB()) {
11995         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
11996       }
11997     }
11998   } else if (!Stride->isOne() && !NoWrap) {
11999     auto isUBOnWrap = [&]() {
12000       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12001       // follows trivially from the fact that every (un)signed-wrapped, but
12002       // not self-wrapped value must be LT than the last value before
12003       // (un)signed wrap.  Since we know that last value didn't exit, nor
12004       // will any smaller one.
12005       return canAssumeNoSelfWrap(IV);
12006     };
12007 
12008     // Avoid proven overflow cases: this will ensure that the backedge taken
12009     // count will not generate any unsigned overflow. Relaxed no-overflow
12010     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12011     // undefined behaviors like the case of C language.
12012     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12013       return getCouldNotCompute();
12014   }
12015 
12016   // On all paths just preceeding, we established the following invariant:
12017   //   IV can be assumed not to overflow up to and including the exiting
12018   //   iteration.  We proved this in one of two ways:
12019   //   1) We can show overflow doesn't occur before the exiting iteration
12020   //      1a) canIVOverflowOnLT, and b) step of one
12021   //   2) We can show that if overflow occurs, the loop must execute UB
12022   //      before any possible exit.
12023   // Note that we have not yet proved RHS invariant (in general).
12024 
12025   const SCEV *Start = IV->getStart();
12026 
12027   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12028   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12029   // Use integer-typed versions for actual computation; we can't subtract
12030   // pointers in general.
12031   const SCEV *OrigStart = Start;
12032   const SCEV *OrigRHS = RHS;
12033   if (Start->getType()->isPointerTy()) {
12034     Start = getLosslessPtrToIntExpr(Start);
12035     if (isa<SCEVCouldNotCompute>(Start))
12036       return Start;
12037   }
12038   if (RHS->getType()->isPointerTy()) {
12039     RHS = getLosslessPtrToIntExpr(RHS);
12040     if (isa<SCEVCouldNotCompute>(RHS))
12041       return RHS;
12042   }
12043 
12044   // When the RHS is not invariant, we do not know the end bound of the loop and
12045   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12046   // calculate the MaxBECount, given the start, stride and max value for the end
12047   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12048   // checked above).
12049   if (!isLoopInvariant(RHS, L)) {
12050     const SCEV *MaxBECount = computeMaxBECountForLT(
12051         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12052     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12053                      false /*MaxOrZero*/, Predicates);
12054   }
12055 
12056   // We use the expression (max(End,Start)-Start)/Stride to describe the
12057   // backedge count, as if the backedge is taken at least once max(End,Start)
12058   // is End and so the result is as above, and if not max(End,Start) is Start
12059   // so we get a backedge count of zero.
12060   const SCEV *BECount = nullptr;
12061   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12062   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12063   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12064   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12065   // Can we prove (max(RHS,Start) > Start - Stride?
12066   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12067       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12068     // In this case, we can use a refined formula for computing backedge taken
12069     // count.  The general formula remains:
12070     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12071     // We want to use the alternate formula:
12072     //   "((End - 1) - (Start - Stride)) /u Stride"
12073     // Let's do a quick case analysis to show these are equivalent under
12074     // our precondition that max(RHS,Start) > Start - Stride.
12075     // * For RHS <= Start, the backedge-taken count must be zero.
12076     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12077     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12078     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12079     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12080     //     this to the stride of 1 case.
12081     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12082     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12083     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12084     //   "((RHS - (Start - Stride) - 1) /u Stride".
12085     //   Our preconditions trivially imply no overflow in that form.
12086     const SCEV *MinusOne = getMinusOne(Stride->getType());
12087     const SCEV *Numerator =
12088         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12089     BECount = getUDivExpr(Numerator, Stride);
12090   }
12091 
12092   const SCEV *BECountIfBackedgeTaken = nullptr;
12093   if (!BECount) {
12094     auto canProveRHSGreaterThanEqualStart = [&]() {
12095       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12096       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12097         return true;
12098 
12099       // (RHS > Start - 1) implies RHS >= Start.
12100       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12101       //   "Start - 1" doesn't overflow.
12102       // * For signed comparison, if Start - 1 does overflow, it's equal
12103       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12104       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12105       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12106       //
12107       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12108       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12109       auto *StartMinusOne = getAddExpr(OrigStart,
12110                                        getMinusOne(OrigStart->getType()));
12111       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12112     };
12113 
12114     // If we know that RHS >= Start in the context of loop, then we know that
12115     // max(RHS, Start) = RHS at this point.
12116     const SCEV *End;
12117     if (canProveRHSGreaterThanEqualStart()) {
12118       End = RHS;
12119     } else {
12120       // If RHS < Start, the backedge will be taken zero times.  So in
12121       // general, we can write the backedge-taken count as:
12122       //
12123       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12124       //
12125       // We convert it to the following to make it more convenient for SCEV:
12126       //
12127       //     ceil(max(RHS, Start) - Start) / Stride
12128       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12129 
12130       // See what would happen if we assume the backedge is taken. This is
12131       // used to compute MaxBECount.
12132       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12133     }
12134 
12135     // At this point, we know:
12136     //
12137     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12138     // 2. The index variable doesn't overflow.
12139     //
12140     // Therefore, we know N exists such that
12141     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12142     // doesn't overflow.
12143     //
12144     // Using this information, try to prove whether the addition in
12145     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12146     const SCEV *One = getOne(Stride->getType());
12147     bool MayAddOverflow = [&] {
12148       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12149         if (StrideC->getAPInt().isPowerOf2()) {
12150           // Suppose Stride is a power of two, and Start/End are unsigned
12151           // integers.  Let UMAX be the largest representable unsigned
12152           // integer.
12153           //
12154           // By the preconditions of this function, we know
12155           // "(Start + Stride * N) >= End", and this doesn't overflow.
12156           // As a formula:
12157           //
12158           //   End <= (Start + Stride * N) <= UMAX
12159           //
12160           // Subtracting Start from all the terms:
12161           //
12162           //   End - Start <= Stride * N <= UMAX - Start
12163           //
12164           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12165           //
12166           //   End - Start <= Stride * N <= UMAX
12167           //
12168           // Stride * N is a multiple of Stride. Therefore,
12169           //
12170           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12171           //
12172           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12173           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12174           //
12175           //   End - Start <= Stride * N <= UMAX - Stride - 1
12176           //
12177           // Dropping the middle term:
12178           //
12179           //   End - Start <= UMAX - Stride - 1
12180           //
12181           // Adding Stride - 1 to both sides:
12182           //
12183           //   (End - Start) + (Stride - 1) <= UMAX
12184           //
12185           // In other words, the addition doesn't have unsigned overflow.
12186           //
12187           // A similar proof works if we treat Start/End as signed values.
12188           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12189           // use signed max instead of unsigned max. Note that we're trying
12190           // to prove a lack of unsigned overflow in either case.
12191           return false;
12192         }
12193       }
12194       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12195         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12196         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12197         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12198         //
12199         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12200         return false;
12201       }
12202       return true;
12203     }();
12204 
12205     const SCEV *Delta = getMinusSCEV(End, Start);
12206     if (!MayAddOverflow) {
12207       // floor((D + (S - 1)) / S)
12208       // We prefer this formulation if it's legal because it's fewer operations.
12209       BECount =
12210           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
12211     } else {
12212       BECount = getUDivCeilSCEV(Delta, Stride);
12213     }
12214   }
12215 
12216   const SCEV *MaxBECount;
12217   bool MaxOrZero = false;
12218   if (isa<SCEVConstant>(BECount)) {
12219     MaxBECount = BECount;
12220   } else if (BECountIfBackedgeTaken &&
12221              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
12222     // If we know exactly how many times the backedge will be taken if it's
12223     // taken at least once, then the backedge count will either be that or
12224     // zero.
12225     MaxBECount = BECountIfBackedgeTaken;
12226     MaxOrZero = true;
12227   } else {
12228     MaxBECount = computeMaxBECountForLT(
12229         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12230   }
12231 
12232   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
12233       !isa<SCEVCouldNotCompute>(BECount))
12234     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
12235 
12236   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
12237 }
12238 
12239 ScalarEvolution::ExitLimit
12240 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
12241                                      const Loop *L, bool IsSigned,
12242                                      bool ControlsExit, bool AllowPredicates) {
12243   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12244   // We handle only IV > Invariant
12245   if (!isLoopInvariant(RHS, L))
12246     return getCouldNotCompute();
12247 
12248   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12249   if (!IV && AllowPredicates)
12250     // Try to make this an AddRec using runtime tests, in the first X
12251     // iterations of this loop, where X is the SCEV expression found by the
12252     // algorithm below.
12253     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12254 
12255   // Avoid weird loops
12256   if (!IV || IV->getLoop() != L || !IV->isAffine())
12257     return getCouldNotCompute();
12258 
12259   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12260   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12261   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12262 
12263   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
12264 
12265   // Avoid negative or zero stride values
12266   if (!isKnownPositive(Stride))
12267     return getCouldNotCompute();
12268 
12269   // Avoid proven overflow cases: this will ensure that the backedge taken count
12270   // will not generate any unsigned overflow. Relaxed no-overflow conditions
12271   // exploit NoWrapFlags, allowing to optimize in presence of undefined
12272   // behaviors like the case of C language.
12273   if (!Stride->isOne() && !NoWrap)
12274     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
12275       return getCouldNotCompute();
12276 
12277   const SCEV *Start = IV->getStart();
12278   const SCEV *End = RHS;
12279   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
12280     // If we know that Start >= RHS in the context of loop, then we know that
12281     // min(RHS, Start) = RHS at this point.
12282     if (isLoopEntryGuardedByCond(
12283             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
12284       End = RHS;
12285     else
12286       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
12287   }
12288 
12289   if (Start->getType()->isPointerTy()) {
12290     Start = getLosslessPtrToIntExpr(Start);
12291     if (isa<SCEVCouldNotCompute>(Start))
12292       return Start;
12293   }
12294   if (End->getType()->isPointerTy()) {
12295     End = getLosslessPtrToIntExpr(End);
12296     if (isa<SCEVCouldNotCompute>(End))
12297       return End;
12298   }
12299 
12300   // Compute ((Start - End) + (Stride - 1)) / Stride.
12301   // FIXME: This can overflow. Holding off on fixing this for now;
12302   // howManyGreaterThans will hopefully be gone soon.
12303   const SCEV *One = getOne(Stride->getType());
12304   const SCEV *BECount = getUDivExpr(
12305       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
12306 
12307   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
12308                             : getUnsignedRangeMax(Start);
12309 
12310   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
12311                              : getUnsignedRangeMin(Stride);
12312 
12313   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
12314   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
12315                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
12316 
12317   // Although End can be a MIN expression we estimate MinEnd considering only
12318   // the case End = RHS. This is safe because in the other case (Start - End)
12319   // is zero, leading to a zero maximum backedge taken count.
12320   APInt MinEnd =
12321     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
12322              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
12323 
12324   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
12325                                ? BECount
12326                                : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
12327                                                  getConstant(MinStride));
12328 
12329   if (isa<SCEVCouldNotCompute>(MaxBECount))
12330     MaxBECount = BECount;
12331 
12332   return ExitLimit(BECount, MaxBECount, false, Predicates);
12333 }
12334 
12335 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
12336                                                     ScalarEvolution &SE) const {
12337   if (Range.isFullSet())  // Infinite loop.
12338     return SE.getCouldNotCompute();
12339 
12340   // If the start is a non-zero constant, shift the range to simplify things.
12341   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
12342     if (!SC->getValue()->isZero()) {
12343       SmallVector<const SCEV *, 4> Operands(operands());
12344       Operands[0] = SE.getZero(SC->getType());
12345       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
12346                                              getNoWrapFlags(FlagNW));
12347       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
12348         return ShiftedAddRec->getNumIterationsInRange(
12349             Range.subtract(SC->getAPInt()), SE);
12350       // This is strange and shouldn't happen.
12351       return SE.getCouldNotCompute();
12352     }
12353 
12354   // The only time we can solve this is when we have all constant indices.
12355   // Otherwise, we cannot determine the overflow conditions.
12356   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
12357     return SE.getCouldNotCompute();
12358 
12359   // Okay at this point we know that all elements of the chrec are constants and
12360   // that the start element is zero.
12361 
12362   // First check to see if the range contains zero.  If not, the first
12363   // iteration exits.
12364   unsigned BitWidth = SE.getTypeSizeInBits(getType());
12365   if (!Range.contains(APInt(BitWidth, 0)))
12366     return SE.getZero(getType());
12367 
12368   if (isAffine()) {
12369     // If this is an affine expression then we have this situation:
12370     //   Solve {0,+,A} in Range  ===  Ax in Range
12371 
12372     // We know that zero is in the range.  If A is positive then we know that
12373     // the upper value of the range must be the first possible exit value.
12374     // If A is negative then the lower of the range is the last possible loop
12375     // value.  Also note that we already checked for a full range.
12376     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
12377     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
12378 
12379     // The exit value should be (End+A)/A.
12380     APInt ExitVal = (End + A).udiv(A);
12381     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
12382 
12383     // Evaluate at the exit value.  If we really did fall out of the valid
12384     // range, then we computed our trip count, otherwise wrap around or other
12385     // things must have happened.
12386     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
12387     if (Range.contains(Val->getValue()))
12388       return SE.getCouldNotCompute();  // Something strange happened
12389 
12390     // Ensure that the previous value is in the range.  This is a sanity check.
12391     assert(Range.contains(
12392            EvaluateConstantChrecAtConstant(this,
12393            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
12394            "Linear scev computation is off in a bad way!");
12395     return SE.getConstant(ExitValue);
12396   }
12397 
12398   if (isQuadratic()) {
12399     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
12400       return SE.getConstant(S.getValue());
12401   }
12402 
12403   return SE.getCouldNotCompute();
12404 }
12405 
12406 const SCEVAddRecExpr *
12407 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
12408   assert(getNumOperands() > 1 && "AddRec with zero step?");
12409   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
12410   // but in this case we cannot guarantee that the value returned will be an
12411   // AddRec because SCEV does not have a fixed point where it stops
12412   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
12413   // may happen if we reach arithmetic depth limit while simplifying. So we
12414   // construct the returned value explicitly.
12415   SmallVector<const SCEV *, 3> Ops;
12416   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
12417   // (this + Step) is {A+B,+,B+C,+...,+,N}.
12418   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
12419     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
12420   // We know that the last operand is not a constant zero (otherwise it would
12421   // have been popped out earlier). This guarantees us that if the result has
12422   // the same last operand, then it will also not be popped out, meaning that
12423   // the returned value will be an AddRec.
12424   const SCEV *Last = getOperand(getNumOperands() - 1);
12425   assert(!Last->isZero() && "Recurrency with zero step?");
12426   Ops.push_back(Last);
12427   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
12428                                                SCEV::FlagAnyWrap));
12429 }
12430 
12431 // Return true when S contains at least an undef value.
12432 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
12433   return SCEVExprContains(S, [](const SCEV *S) {
12434     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12435       return isa<UndefValue>(SU->getValue());
12436     return false;
12437   });
12438 }
12439 
12440 /// Return the size of an element read or written by Inst.
12441 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12442   Type *Ty;
12443   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12444     Ty = Store->getValueOperand()->getType();
12445   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12446     Ty = Load->getType();
12447   else
12448     return nullptr;
12449 
12450   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12451   return getSizeOfExpr(ETy, Ty);
12452 }
12453 
12454 //===----------------------------------------------------------------------===//
12455 //                   SCEVCallbackVH Class Implementation
12456 //===----------------------------------------------------------------------===//
12457 
12458 void ScalarEvolution::SCEVCallbackVH::deleted() {
12459   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12460   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12461     SE->ConstantEvolutionLoopExitValue.erase(PN);
12462   SE->eraseValueFromMap(getValPtr());
12463   // this now dangles!
12464 }
12465 
12466 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12467   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12468 
12469   // Forget all the expressions associated with users of the old value,
12470   // so that future queries will recompute the expressions using the new
12471   // value.
12472   Value *Old = getValPtr();
12473   SmallVector<User *, 16> Worklist(Old->users());
12474   SmallPtrSet<User *, 8> Visited;
12475   while (!Worklist.empty()) {
12476     User *U = Worklist.pop_back_val();
12477     // Deleting the Old value will cause this to dangle. Postpone
12478     // that until everything else is done.
12479     if (U == Old)
12480       continue;
12481     if (!Visited.insert(U).second)
12482       continue;
12483     if (PHINode *PN = dyn_cast<PHINode>(U))
12484       SE->ConstantEvolutionLoopExitValue.erase(PN);
12485     SE->eraseValueFromMap(U);
12486     llvm::append_range(Worklist, U->users());
12487   }
12488   // Delete the Old value.
12489   if (PHINode *PN = dyn_cast<PHINode>(Old))
12490     SE->ConstantEvolutionLoopExitValue.erase(PN);
12491   SE->eraseValueFromMap(Old);
12492   // this now dangles!
12493 }
12494 
12495 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12496   : CallbackVH(V), SE(se) {}
12497 
12498 //===----------------------------------------------------------------------===//
12499 //                   ScalarEvolution Class Implementation
12500 //===----------------------------------------------------------------------===//
12501 
12502 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12503                                  AssumptionCache &AC, DominatorTree &DT,
12504                                  LoopInfo &LI)
12505     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12506       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12507       LoopDispositions(64), BlockDispositions(64) {
12508   // To use guards for proving predicates, we need to scan every instruction in
12509   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12510   // time if the IR does not actually contain any calls to
12511   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12512   //
12513   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12514   // to _add_ guards to the module when there weren't any before, and wants
12515   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12516   // efficient in lieu of being smart in that rather obscure case.
12517 
12518   auto *GuardDecl = F.getParent()->getFunction(
12519       Intrinsic::getName(Intrinsic::experimental_guard));
12520   HasGuards = GuardDecl && !GuardDecl->use_empty();
12521 }
12522 
12523 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12524     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12525       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12526       ValueExprMap(std::move(Arg.ValueExprMap)),
12527       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12528       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12529       PendingMerges(std::move(Arg.PendingMerges)),
12530       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12531       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12532       PredicatedBackedgeTakenCounts(
12533           std::move(Arg.PredicatedBackedgeTakenCounts)),
12534       ConstantEvolutionLoopExitValue(
12535           std::move(Arg.ConstantEvolutionLoopExitValue)),
12536       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12537       LoopDispositions(std::move(Arg.LoopDispositions)),
12538       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12539       BlockDispositions(std::move(Arg.BlockDispositions)),
12540       SCEVUsers(std::move(Arg.SCEVUsers)),
12541       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12542       SignedRanges(std::move(Arg.SignedRanges)),
12543       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12544       UniquePreds(std::move(Arg.UniquePreds)),
12545       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12546       LoopUsers(std::move(Arg.LoopUsers)),
12547       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12548       FirstUnknown(Arg.FirstUnknown) {
12549   Arg.FirstUnknown = nullptr;
12550 }
12551 
12552 ScalarEvolution::~ScalarEvolution() {
12553   // Iterate through all the SCEVUnknown instances and call their
12554   // destructors, so that they release their references to their values.
12555   for (SCEVUnknown *U = FirstUnknown; U;) {
12556     SCEVUnknown *Tmp = U;
12557     U = U->Next;
12558     Tmp->~SCEVUnknown();
12559   }
12560   FirstUnknown = nullptr;
12561 
12562   ExprValueMap.clear();
12563   ValueExprMap.clear();
12564   HasRecMap.clear();
12565   BackedgeTakenCounts.clear();
12566   PredicatedBackedgeTakenCounts.clear();
12567 
12568   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12569   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12570   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12571   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12572   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12573 }
12574 
12575 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12576   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12577 }
12578 
12579 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12580                           const Loop *L) {
12581   // Print all inner loops first
12582   for (Loop *I : *L)
12583     PrintLoopInfo(OS, SE, I);
12584 
12585   OS << "Loop ";
12586   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12587   OS << ": ";
12588 
12589   SmallVector<BasicBlock *, 8> ExitingBlocks;
12590   L->getExitingBlocks(ExitingBlocks);
12591   if (ExitingBlocks.size() != 1)
12592     OS << "<multiple exits> ";
12593 
12594   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12595     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12596   else
12597     OS << "Unpredictable backedge-taken count.\n";
12598 
12599   if (ExitingBlocks.size() > 1)
12600     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12601       OS << "  exit count for " << ExitingBlock->getName() << ": "
12602          << *SE->getExitCount(L, ExitingBlock) << "\n";
12603     }
12604 
12605   OS << "Loop ";
12606   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12607   OS << ": ";
12608 
12609   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12610     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12611     if (SE->isBackedgeTakenCountMaxOrZero(L))
12612       OS << ", actual taken count either this or zero.";
12613   } else {
12614     OS << "Unpredictable max backedge-taken count. ";
12615   }
12616 
12617   OS << "\n"
12618         "Loop ";
12619   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12620   OS << ": ";
12621 
12622   SCEVUnionPredicate Pred;
12623   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12624   if (!isa<SCEVCouldNotCompute>(PBT)) {
12625     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12626     OS << " Predicates:\n";
12627     Pred.print(OS, 4);
12628   } else {
12629     OS << "Unpredictable predicated backedge-taken count. ";
12630   }
12631   OS << "\n";
12632 
12633   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12634     OS << "Loop ";
12635     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12636     OS << ": ";
12637     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12638   }
12639 }
12640 
12641 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12642   switch (LD) {
12643   case ScalarEvolution::LoopVariant:
12644     return "Variant";
12645   case ScalarEvolution::LoopInvariant:
12646     return "Invariant";
12647   case ScalarEvolution::LoopComputable:
12648     return "Computable";
12649   }
12650   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12651 }
12652 
12653 void ScalarEvolution::print(raw_ostream &OS) const {
12654   // ScalarEvolution's implementation of the print method is to print
12655   // out SCEV values of all instructions that are interesting. Doing
12656   // this potentially causes it to create new SCEV objects though,
12657   // which technically conflicts with the const qualifier. This isn't
12658   // observable from outside the class though, so casting away the
12659   // const isn't dangerous.
12660   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12661 
12662   if (ClassifyExpressions) {
12663     OS << "Classifying expressions for: ";
12664     F.printAsOperand(OS, /*PrintType=*/false);
12665     OS << "\n";
12666     for (Instruction &I : instructions(F))
12667       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12668         OS << I << '\n';
12669         OS << "  -->  ";
12670         const SCEV *SV = SE.getSCEV(&I);
12671         SV->print(OS);
12672         if (!isa<SCEVCouldNotCompute>(SV)) {
12673           OS << " U: ";
12674           SE.getUnsignedRange(SV).print(OS);
12675           OS << " S: ";
12676           SE.getSignedRange(SV).print(OS);
12677         }
12678 
12679         const Loop *L = LI.getLoopFor(I.getParent());
12680 
12681         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12682         if (AtUse != SV) {
12683           OS << "  -->  ";
12684           AtUse->print(OS);
12685           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12686             OS << " U: ";
12687             SE.getUnsignedRange(AtUse).print(OS);
12688             OS << " S: ";
12689             SE.getSignedRange(AtUse).print(OS);
12690           }
12691         }
12692 
12693         if (L) {
12694           OS << "\t\t" "Exits: ";
12695           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12696           if (!SE.isLoopInvariant(ExitValue, L)) {
12697             OS << "<<Unknown>>";
12698           } else {
12699             OS << *ExitValue;
12700           }
12701 
12702           bool First = true;
12703           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12704             if (First) {
12705               OS << "\t\t" "LoopDispositions: { ";
12706               First = false;
12707             } else {
12708               OS << ", ";
12709             }
12710 
12711             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12712             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12713           }
12714 
12715           for (auto *InnerL : depth_first(L)) {
12716             if (InnerL == L)
12717               continue;
12718             if (First) {
12719               OS << "\t\t" "LoopDispositions: { ";
12720               First = false;
12721             } else {
12722               OS << ", ";
12723             }
12724 
12725             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12726             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12727           }
12728 
12729           OS << " }";
12730         }
12731 
12732         OS << "\n";
12733       }
12734   }
12735 
12736   OS << "Determining loop execution counts for: ";
12737   F.printAsOperand(OS, /*PrintType=*/false);
12738   OS << "\n";
12739   for (Loop *I : LI)
12740     PrintLoopInfo(OS, &SE, I);
12741 }
12742 
12743 ScalarEvolution::LoopDisposition
12744 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12745   auto &Values = LoopDispositions[S];
12746   for (auto &V : Values) {
12747     if (V.getPointer() == L)
12748       return V.getInt();
12749   }
12750   Values.emplace_back(L, LoopVariant);
12751   LoopDisposition D = computeLoopDisposition(S, L);
12752   auto &Values2 = LoopDispositions[S];
12753   for (auto &V : llvm::reverse(Values2)) {
12754     if (V.getPointer() == L) {
12755       V.setInt(D);
12756       break;
12757     }
12758   }
12759   return D;
12760 }
12761 
12762 ScalarEvolution::LoopDisposition
12763 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12764   switch (S->getSCEVType()) {
12765   case scConstant:
12766     return LoopInvariant;
12767   case scPtrToInt:
12768   case scTruncate:
12769   case scZeroExtend:
12770   case scSignExtend:
12771     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12772   case scAddRecExpr: {
12773     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12774 
12775     // If L is the addrec's loop, it's computable.
12776     if (AR->getLoop() == L)
12777       return LoopComputable;
12778 
12779     // Add recurrences are never invariant in the function-body (null loop).
12780     if (!L)
12781       return LoopVariant;
12782 
12783     // Everything that is not defined at loop entry is variant.
12784     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12785       return LoopVariant;
12786     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12787            " dominate the contained loop's header?");
12788 
12789     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12790     if (AR->getLoop()->contains(L))
12791       return LoopInvariant;
12792 
12793     // This recurrence is variant w.r.t. L if any of its operands
12794     // are variant.
12795     for (auto *Op : AR->operands())
12796       if (!isLoopInvariant(Op, L))
12797         return LoopVariant;
12798 
12799     // Otherwise it's loop-invariant.
12800     return LoopInvariant;
12801   }
12802   case scAddExpr:
12803   case scMulExpr:
12804   case scUMaxExpr:
12805   case scSMaxExpr:
12806   case scUMinExpr:
12807   case scSMinExpr: {
12808     bool HasVarying = false;
12809     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12810       LoopDisposition D = getLoopDisposition(Op, L);
12811       if (D == LoopVariant)
12812         return LoopVariant;
12813       if (D == LoopComputable)
12814         HasVarying = true;
12815     }
12816     return HasVarying ? LoopComputable : LoopInvariant;
12817   }
12818   case scUDivExpr: {
12819     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12820     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12821     if (LD == LoopVariant)
12822       return LoopVariant;
12823     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12824     if (RD == LoopVariant)
12825       return LoopVariant;
12826     return (LD == LoopInvariant && RD == LoopInvariant) ?
12827            LoopInvariant : LoopComputable;
12828   }
12829   case scUnknown:
12830     // All non-instruction values are loop invariant.  All instructions are loop
12831     // invariant if they are not contained in the specified loop.
12832     // Instructions are never considered invariant in the function body
12833     // (null loop) because they are defined within the "loop".
12834     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12835       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12836     return LoopInvariant;
12837   case scCouldNotCompute:
12838     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12839   }
12840   llvm_unreachable("Unknown SCEV kind!");
12841 }
12842 
12843 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12844   return getLoopDisposition(S, L) == LoopInvariant;
12845 }
12846 
12847 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12848   return getLoopDisposition(S, L) == LoopComputable;
12849 }
12850 
12851 ScalarEvolution::BlockDisposition
12852 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12853   auto &Values = BlockDispositions[S];
12854   for (auto &V : Values) {
12855     if (V.getPointer() == BB)
12856       return V.getInt();
12857   }
12858   Values.emplace_back(BB, DoesNotDominateBlock);
12859   BlockDisposition D = computeBlockDisposition(S, BB);
12860   auto &Values2 = BlockDispositions[S];
12861   for (auto &V : llvm::reverse(Values2)) {
12862     if (V.getPointer() == BB) {
12863       V.setInt(D);
12864       break;
12865     }
12866   }
12867   return D;
12868 }
12869 
12870 ScalarEvolution::BlockDisposition
12871 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12872   switch (S->getSCEVType()) {
12873   case scConstant:
12874     return ProperlyDominatesBlock;
12875   case scPtrToInt:
12876   case scTruncate:
12877   case scZeroExtend:
12878   case scSignExtend:
12879     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12880   case scAddRecExpr: {
12881     // This uses a "dominates" query instead of "properly dominates" query
12882     // to test for proper dominance too, because the instruction which
12883     // produces the addrec's value is a PHI, and a PHI effectively properly
12884     // dominates its entire containing block.
12885     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12886     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12887       return DoesNotDominateBlock;
12888 
12889     // Fall through into SCEVNAryExpr handling.
12890     LLVM_FALLTHROUGH;
12891   }
12892   case scAddExpr:
12893   case scMulExpr:
12894   case scUMaxExpr:
12895   case scSMaxExpr:
12896   case scUMinExpr:
12897   case scSMinExpr: {
12898     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12899     bool Proper = true;
12900     for (const SCEV *NAryOp : NAry->operands()) {
12901       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12902       if (D == DoesNotDominateBlock)
12903         return DoesNotDominateBlock;
12904       if (D == DominatesBlock)
12905         Proper = false;
12906     }
12907     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12908   }
12909   case scUDivExpr: {
12910     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12911     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12912     BlockDisposition LD = getBlockDisposition(LHS, BB);
12913     if (LD == DoesNotDominateBlock)
12914       return DoesNotDominateBlock;
12915     BlockDisposition RD = getBlockDisposition(RHS, BB);
12916     if (RD == DoesNotDominateBlock)
12917       return DoesNotDominateBlock;
12918     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12919       ProperlyDominatesBlock : DominatesBlock;
12920   }
12921   case scUnknown:
12922     if (Instruction *I =
12923           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12924       if (I->getParent() == BB)
12925         return DominatesBlock;
12926       if (DT.properlyDominates(I->getParent(), BB))
12927         return ProperlyDominatesBlock;
12928       return DoesNotDominateBlock;
12929     }
12930     return ProperlyDominatesBlock;
12931   case scCouldNotCompute:
12932     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12933   }
12934   llvm_unreachable("Unknown SCEV kind!");
12935 }
12936 
12937 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12938   return getBlockDisposition(S, BB) >= DominatesBlock;
12939 }
12940 
12941 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12942   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12943 }
12944 
12945 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12946   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12947 }
12948 
12949 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
12950   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
12951   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
12952 
12953   while (!Worklist.empty()) {
12954     const SCEV *Curr = Worklist.pop_back_val();
12955     auto Users = SCEVUsers.find(Curr);
12956     if (Users != SCEVUsers.end())
12957       for (auto *User : Users->second)
12958         if (ToForget.insert(User).second)
12959           Worklist.push_back(User);
12960   }
12961 
12962   for (auto *S : ToForget)
12963     forgetMemoizedResultsImpl(S);
12964 
12965   for (auto I = PredicatedSCEVRewrites.begin();
12966        I != PredicatedSCEVRewrites.end();) {
12967     std::pair<const SCEV *, const Loop *> Entry = I->first;
12968     if (ToForget.count(Entry.first))
12969       PredicatedSCEVRewrites.erase(I++);
12970     else
12971       ++I;
12972   }
12973 
12974   auto RemoveSCEVFromBackedgeMap = [&ToForget](
12975       DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12976         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12977           BackedgeTakenInfo &BEInfo = I->second;
12978           if (any_of(ToForget,
12979                      [&BEInfo](const SCEV *S) { return BEInfo.hasOperand(S); }))
12980             Map.erase(I++);
12981           else
12982             ++I;
12983         }
12984   };
12985 
12986   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12987   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12988 }
12989 
12990 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
12991   ValuesAtScopes.erase(S);
12992   LoopDispositions.erase(S);
12993   BlockDispositions.erase(S);
12994   UnsignedRanges.erase(S);
12995   SignedRanges.erase(S);
12996   ExprValueMap.erase(S);
12997   HasRecMap.erase(S);
12998   MinTrailingZerosCache.erase(S);
12999 }
13000 
13001 void
13002 ScalarEvolution::getUsedLoops(const SCEV *S,
13003                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13004   struct FindUsedLoops {
13005     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13006         : LoopsUsed(LoopsUsed) {}
13007     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13008     bool follow(const SCEV *S) {
13009       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13010         LoopsUsed.insert(AR->getLoop());
13011       return true;
13012     }
13013 
13014     bool isDone() const { return false; }
13015   };
13016 
13017   FindUsedLoops F(LoopsUsed);
13018   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13019 }
13020 
13021 void ScalarEvolution::verify() const {
13022   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13023   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13024 
13025   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13026 
13027   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13028   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13029     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13030 
13031     const SCEV *visitConstant(const SCEVConstant *Constant) {
13032       return SE.getConstant(Constant->getAPInt());
13033     }
13034 
13035     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13036       return SE.getUnknown(Expr->getValue());
13037     }
13038 
13039     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13040       return SE.getCouldNotCompute();
13041     }
13042   };
13043 
13044   SCEVMapper SCM(SE2);
13045 
13046   while (!LoopStack.empty()) {
13047     auto *L = LoopStack.pop_back_val();
13048     llvm::append_range(LoopStack, *L);
13049 
13050     auto *CurBECount = SCM.visit(
13051         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
13052     auto *NewBECount = SE2.getBackedgeTakenCount(L);
13053 
13054     if (CurBECount == SE2.getCouldNotCompute() ||
13055         NewBECount == SE2.getCouldNotCompute()) {
13056       // NB! This situation is legal, but is very suspicious -- whatever pass
13057       // change the loop to make a trip count go from could not compute to
13058       // computable or vice-versa *should have* invalidated SCEV.  However, we
13059       // choose not to assert here (for now) since we don't want false
13060       // positives.
13061       continue;
13062     }
13063 
13064     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
13065       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13066       // not propagate undef aggressively).  This means we can (and do) fail
13067       // verification in cases where a transform makes the trip count of a loop
13068       // go from "undef" to "undef+1" (say).  The transform is fine, since in
13069       // both cases the loop iterates "undef" times, but SCEV thinks we
13070       // increased the trip count of the loop by 1 incorrectly.
13071       continue;
13072     }
13073 
13074     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13075         SE.getTypeSizeInBits(NewBECount->getType()))
13076       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13077     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13078              SE.getTypeSizeInBits(NewBECount->getType()))
13079       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13080 
13081     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
13082 
13083     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13084     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
13085       dbgs() << "Trip Count for " << *L << " Changed!\n";
13086       dbgs() << "Old: " << *CurBECount << "\n";
13087       dbgs() << "New: " << *NewBECount << "\n";
13088       dbgs() << "Delta: " << *Delta << "\n";
13089       std::abort();
13090     }
13091   }
13092 
13093   // Collect all valid loops currently in LoopInfo.
13094   SmallPtrSet<Loop *, 32> ValidLoops;
13095   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13096   while (!Worklist.empty()) {
13097     Loop *L = Worklist.pop_back_val();
13098     if (ValidLoops.contains(L))
13099       continue;
13100     ValidLoops.insert(L);
13101     Worklist.append(L->begin(), L->end());
13102   }
13103   // Check for SCEV expressions referencing invalid/deleted loops.
13104   for (auto &KV : ValueExprMap) {
13105     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
13106     if (!AR)
13107       continue;
13108     assert(ValidLoops.contains(AR->getLoop()) &&
13109            "AddRec references invalid loop");
13110   }
13111 
13112   // Verify intergity of SCEV users.
13113   for (const auto &S : UniqueSCEVs) {
13114     SmallVector<const SCEV *, 4> Ops;
13115     collectUniqueOps(&S, Ops);
13116     for (const auto *Op : Ops) {
13117       // We do not store dependencies of constants.
13118       if (isa<SCEVConstant>(Op))
13119         continue;
13120       auto It = SCEVUsers.find(Op);
13121       if (It != SCEVUsers.end() && It->second.count(&S))
13122         continue;
13123       dbgs() << "Use of operand  " << *Op << " by user " << S
13124              << " is not being tracked!\n";
13125       std::abort();
13126     }
13127   }
13128 }
13129 
13130 bool ScalarEvolution::invalidate(
13131     Function &F, const PreservedAnalyses &PA,
13132     FunctionAnalysisManager::Invalidator &Inv) {
13133   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13134   // of its dependencies is invalidated.
13135   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13136   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13137          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13138          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13139          Inv.invalidate<LoopAnalysis>(F, PA);
13140 }
13141 
13142 AnalysisKey ScalarEvolutionAnalysis::Key;
13143 
13144 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13145                                              FunctionAnalysisManager &AM) {
13146   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13147                          AM.getResult<AssumptionAnalysis>(F),
13148                          AM.getResult<DominatorTreeAnalysis>(F),
13149                          AM.getResult<LoopAnalysis>(F));
13150 }
13151 
13152 PreservedAnalyses
13153 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13154   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13155   return PreservedAnalyses::all();
13156 }
13157 
13158 PreservedAnalyses
13159 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13160   // For compatibility with opt's -analyze feature under legacy pass manager
13161   // which was not ported to NPM. This keeps tests using
13162   // update_analyze_test_checks.py working.
13163   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13164      << F.getName() << "':\n";
13165   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13166   return PreservedAnalyses::all();
13167 }
13168 
13169 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13170                       "Scalar Evolution Analysis", false, true)
13171 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13172 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13173 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13174 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13175 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13176                     "Scalar Evolution Analysis", false, true)
13177 
13178 char ScalarEvolutionWrapperPass::ID = 0;
13179 
13180 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13181   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13182 }
13183 
13184 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13185   SE.reset(new ScalarEvolution(
13186       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13187       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13188       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13189       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13190   return false;
13191 }
13192 
13193 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13194 
13195 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13196   SE->print(OS);
13197 }
13198 
13199 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13200   if (!VerifySCEV)
13201     return;
13202 
13203   SE->verify();
13204 }
13205 
13206 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13207   AU.setPreservesAll();
13208   AU.addRequiredTransitive<AssumptionCacheTracker>();
13209   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13210   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13211   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13212 }
13213 
13214 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13215                                                         const SCEV *RHS) {
13216   FoldingSetNodeID ID;
13217   assert(LHS->getType() == RHS->getType() &&
13218          "Type mismatch between LHS and RHS");
13219   // Unique this node based on the arguments
13220   ID.AddInteger(SCEVPredicate::P_Equal);
13221   ID.AddPointer(LHS);
13222   ID.AddPointer(RHS);
13223   void *IP = nullptr;
13224   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13225     return S;
13226   SCEVEqualPredicate *Eq = new (SCEVAllocator)
13227       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
13228   UniquePreds.InsertNode(Eq, IP);
13229   return Eq;
13230 }
13231 
13232 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13233     const SCEVAddRecExpr *AR,
13234     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13235   FoldingSetNodeID ID;
13236   // Unique this node based on the arguments
13237   ID.AddInteger(SCEVPredicate::P_Wrap);
13238   ID.AddPointer(AR);
13239   ID.AddInteger(AddedFlags);
13240   void *IP = nullptr;
13241   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13242     return S;
13243   auto *OF = new (SCEVAllocator)
13244       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13245   UniquePreds.InsertNode(OF, IP);
13246   return OF;
13247 }
13248 
13249 namespace {
13250 
13251 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13252 public:
13253 
13254   /// Rewrites \p S in the context of a loop L and the SCEV predication
13255   /// infrastructure.
13256   ///
13257   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13258   /// equivalences present in \p Pred.
13259   ///
13260   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13261   /// \p NewPreds such that the result will be an AddRecExpr.
13262   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13263                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13264                              SCEVUnionPredicate *Pred) {
13265     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13266     return Rewriter.visit(S);
13267   }
13268 
13269   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13270     if (Pred) {
13271       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
13272       for (auto *Pred : ExprPreds)
13273         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
13274           if (IPred->getLHS() == Expr)
13275             return IPred->getRHS();
13276     }
13277     return convertToAddRecWithPreds(Expr);
13278   }
13279 
13280   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13281     const SCEV *Operand = visit(Expr->getOperand());
13282     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13283     if (AR && AR->getLoop() == L && AR->isAffine()) {
13284       // This couldn't be folded because the operand didn't have the nuw
13285       // flag. Add the nusw flag as an assumption that we could make.
13286       const SCEV *Step = AR->getStepRecurrence(SE);
13287       Type *Ty = Expr->getType();
13288       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13289         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13290                                 SE.getSignExtendExpr(Step, Ty), L,
13291                                 AR->getNoWrapFlags());
13292     }
13293     return SE.getZeroExtendExpr(Operand, Expr->getType());
13294   }
13295 
13296   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13297     const SCEV *Operand = visit(Expr->getOperand());
13298     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13299     if (AR && AR->getLoop() == L && AR->isAffine()) {
13300       // This couldn't be folded because the operand didn't have the nsw
13301       // flag. Add the nssw flag as an assumption that we could make.
13302       const SCEV *Step = AR->getStepRecurrence(SE);
13303       Type *Ty = Expr->getType();
13304       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13305         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13306                                 SE.getSignExtendExpr(Step, Ty), L,
13307                                 AR->getNoWrapFlags());
13308     }
13309     return SE.getSignExtendExpr(Operand, Expr->getType());
13310   }
13311 
13312 private:
13313   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13314                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13315                         SCEVUnionPredicate *Pred)
13316       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13317 
13318   bool addOverflowAssumption(const SCEVPredicate *P) {
13319     if (!NewPreds) {
13320       // Check if we've already made this assumption.
13321       return Pred && Pred->implies(P);
13322     }
13323     NewPreds->insert(P);
13324     return true;
13325   }
13326 
13327   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13328                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13329     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13330     return addOverflowAssumption(A);
13331   }
13332 
13333   // If \p Expr represents a PHINode, we try to see if it can be represented
13334   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13335   // to add this predicate as a runtime overflow check, we return the AddRec.
13336   // If \p Expr does not meet these conditions (is not a PHI node, or we
13337   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13338   // return \p Expr.
13339   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13340     if (!isa<PHINode>(Expr->getValue()))
13341       return Expr;
13342     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13343     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13344     if (!PredicatedRewrite)
13345       return Expr;
13346     for (auto *P : PredicatedRewrite->second){
13347       // Wrap predicates from outer loops are not supported.
13348       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13349         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
13350         if (L != AR->getLoop())
13351           return Expr;
13352       }
13353       if (!addOverflowAssumption(P))
13354         return Expr;
13355     }
13356     return PredicatedRewrite->first;
13357   }
13358 
13359   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13360   SCEVUnionPredicate *Pred;
13361   const Loop *L;
13362 };
13363 
13364 } // end anonymous namespace
13365 
13366 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13367                                                    SCEVUnionPredicate &Preds) {
13368   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13369 }
13370 
13371 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13372     const SCEV *S, const Loop *L,
13373     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13374   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13375   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13376   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13377 
13378   if (!AddRec)
13379     return nullptr;
13380 
13381   // Since the transformation was successful, we can now transfer the SCEV
13382   // predicates.
13383   for (auto *P : TransformPreds)
13384     Preds.insert(P);
13385 
13386   return AddRec;
13387 }
13388 
13389 /// SCEV predicates
13390 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13391                              SCEVPredicateKind Kind)
13392     : FastID(ID), Kind(Kind) {}
13393 
13394 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13395                                        const SCEV *LHS, const SCEV *RHS)
13396     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13397   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13398   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13399 }
13400 
13401 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13402   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13403 
13404   if (!Op)
13405     return false;
13406 
13407   return Op->LHS == LHS && Op->RHS == RHS;
13408 }
13409 
13410 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13411 
13412 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13413 
13414 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13415   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13416 }
13417 
13418 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13419                                      const SCEVAddRecExpr *AR,
13420                                      IncrementWrapFlags Flags)
13421     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13422 
13423 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13424 
13425 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13426   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13427 
13428   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13429 }
13430 
13431 bool SCEVWrapPredicate::isAlwaysTrue() const {
13432   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13433   IncrementWrapFlags IFlags = Flags;
13434 
13435   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13436     IFlags = clearFlags(IFlags, IncrementNSSW);
13437 
13438   return IFlags == IncrementAnyWrap;
13439 }
13440 
13441 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13442   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13443   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13444     OS << "<nusw>";
13445   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13446     OS << "<nssw>";
13447   OS << "\n";
13448 }
13449 
13450 SCEVWrapPredicate::IncrementWrapFlags
13451 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13452                                    ScalarEvolution &SE) {
13453   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13454   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13455 
13456   // We can safely transfer the NSW flag as NSSW.
13457   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13458     ImpliedFlags = IncrementNSSW;
13459 
13460   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13461     // If the increment is positive, the SCEV NUW flag will also imply the
13462     // WrapPredicate NUSW flag.
13463     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13464       if (Step->getValue()->getValue().isNonNegative())
13465         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13466   }
13467 
13468   return ImpliedFlags;
13469 }
13470 
13471 /// Union predicates don't get cached so create a dummy set ID for it.
13472 SCEVUnionPredicate::SCEVUnionPredicate()
13473     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13474 
13475 bool SCEVUnionPredicate::isAlwaysTrue() const {
13476   return all_of(Preds,
13477                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13478 }
13479 
13480 ArrayRef<const SCEVPredicate *>
13481 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13482   auto I = SCEVToPreds.find(Expr);
13483   if (I == SCEVToPreds.end())
13484     return ArrayRef<const SCEVPredicate *>();
13485   return I->second;
13486 }
13487 
13488 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13489   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13490     return all_of(Set->Preds,
13491                   [this](const SCEVPredicate *I) { return this->implies(I); });
13492 
13493   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13494   if (ScevPredsIt == SCEVToPreds.end())
13495     return false;
13496   auto &SCEVPreds = ScevPredsIt->second;
13497 
13498   return any_of(SCEVPreds,
13499                 [N](const SCEVPredicate *I) { return I->implies(N); });
13500 }
13501 
13502 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13503 
13504 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13505   for (auto Pred : Preds)
13506     Pred->print(OS, Depth);
13507 }
13508 
13509 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13510   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13511     for (auto Pred : Set->Preds)
13512       add(Pred);
13513     return;
13514   }
13515 
13516   if (implies(N))
13517     return;
13518 
13519   const SCEV *Key = N->getExpr();
13520   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13521                 " associated expression!");
13522 
13523   SCEVToPreds[Key].push_back(N);
13524   Preds.push_back(N);
13525 }
13526 
13527 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13528                                                      Loop &L)
13529     : SE(SE), L(L) {}
13530 
13531 void ScalarEvolution::registerUser(const SCEV *User,
13532                                    ArrayRef<const SCEV *> Ops) {
13533   for (auto *Op : Ops)
13534     // We do not expect that forgetting cached data for SCEVConstants will ever
13535     // open any prospects for sharpening or introduce any correctness issues,
13536     // so we don't bother storing their dependencies.
13537     if (!isa<SCEVConstant>(Op))
13538       SCEVUsers[Op].insert(User);
13539 }
13540 
13541 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13542   const SCEV *Expr = SE.getSCEV(V);
13543   RewriteEntry &Entry = RewriteMap[Expr];
13544 
13545   // If we already have an entry and the version matches, return it.
13546   if (Entry.second && Generation == Entry.first)
13547     return Entry.second;
13548 
13549   // We found an entry but it's stale. Rewrite the stale entry
13550   // according to the current predicate.
13551   if (Entry.second)
13552     Expr = Entry.second;
13553 
13554   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13555   Entry = {Generation, NewSCEV};
13556 
13557   return NewSCEV;
13558 }
13559 
13560 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13561   if (!BackedgeCount) {
13562     SCEVUnionPredicate BackedgePred;
13563     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13564     addPredicate(BackedgePred);
13565   }
13566   return BackedgeCount;
13567 }
13568 
13569 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13570   if (Preds.implies(&Pred))
13571     return;
13572   Preds.add(&Pred);
13573   updateGeneration();
13574 }
13575 
13576 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13577   return Preds;
13578 }
13579 
13580 void PredicatedScalarEvolution::updateGeneration() {
13581   // If the generation number wrapped recompute everything.
13582   if (++Generation == 0) {
13583     for (auto &II : RewriteMap) {
13584       const SCEV *Rewritten = II.second.second;
13585       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13586     }
13587   }
13588 }
13589 
13590 void PredicatedScalarEvolution::setNoOverflow(
13591     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13592   const SCEV *Expr = getSCEV(V);
13593   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13594 
13595   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13596 
13597   // Clear the statically implied flags.
13598   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13599   addPredicate(*SE.getWrapPredicate(AR, Flags));
13600 
13601   auto II = FlagsMap.insert({V, Flags});
13602   if (!II.second)
13603     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13604 }
13605 
13606 bool PredicatedScalarEvolution::hasNoOverflow(
13607     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13608   const SCEV *Expr = getSCEV(V);
13609   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13610 
13611   Flags = SCEVWrapPredicate::clearFlags(
13612       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13613 
13614   auto II = FlagsMap.find(V);
13615 
13616   if (II != FlagsMap.end())
13617     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13618 
13619   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13620 }
13621 
13622 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13623   const SCEV *Expr = this->getSCEV(V);
13624   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13625   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13626 
13627   if (!New)
13628     return nullptr;
13629 
13630   for (auto *P : NewPreds)
13631     Preds.add(P);
13632 
13633   updateGeneration();
13634   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13635   return New;
13636 }
13637 
13638 PredicatedScalarEvolution::PredicatedScalarEvolution(
13639     const PredicatedScalarEvolution &Init)
13640     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13641       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13642   for (auto I : Init.FlagsMap)
13643     FlagsMap.insert(I);
13644 }
13645 
13646 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13647   // For each block.
13648   for (auto *BB : L.getBlocks())
13649     for (auto &I : *BB) {
13650       if (!SE.isSCEVable(I.getType()))
13651         continue;
13652 
13653       auto *Expr = SE.getSCEV(&I);
13654       auto II = RewriteMap.find(Expr);
13655 
13656       if (II == RewriteMap.end())
13657         continue;
13658 
13659       // Don't print things that are not interesting.
13660       if (II->second.second == Expr)
13661         continue;
13662 
13663       OS.indent(Depth) << "[PSE]" << I << ":\n";
13664       OS.indent(Depth + 2) << *Expr << "\n";
13665       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13666     }
13667 }
13668 
13669 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13670 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13671 // for URem with constant power-of-2 second operands.
13672 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13673 // 4, A / B becomes X / 8).
13674 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13675                                 const SCEV *&RHS) {
13676   // Try to match 'zext (trunc A to iB) to iY', which is used
13677   // for URem with constant power-of-2 second operands. Make sure the size of
13678   // the operand A matches the size of the whole expressions.
13679   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13680     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13681       LHS = Trunc->getOperand();
13682       // Bail out if the type of the LHS is larger than the type of the
13683       // expression for now.
13684       if (getTypeSizeInBits(LHS->getType()) >
13685           getTypeSizeInBits(Expr->getType()))
13686         return false;
13687       if (LHS->getType() != Expr->getType())
13688         LHS = getZeroExtendExpr(LHS, Expr->getType());
13689       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13690                         << getTypeSizeInBits(Trunc->getType()));
13691       return true;
13692     }
13693   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13694   if (Add == nullptr || Add->getNumOperands() != 2)
13695     return false;
13696 
13697   const SCEV *A = Add->getOperand(1);
13698   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13699 
13700   if (Mul == nullptr)
13701     return false;
13702 
13703   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13704     // (SomeExpr + (-(SomeExpr / B) * B)).
13705     if (Expr == getURemExpr(A, B)) {
13706       LHS = A;
13707       RHS = B;
13708       return true;
13709     }
13710     return false;
13711   };
13712 
13713   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13714   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13715     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13716            MatchURemWithDivisor(Mul->getOperand(2));
13717 
13718   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13719   if (Mul->getNumOperands() == 2)
13720     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13721            MatchURemWithDivisor(Mul->getOperand(0)) ||
13722            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13723            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13724   return false;
13725 }
13726 
13727 const SCEV *
13728 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13729   SmallVector<BasicBlock*, 16> ExitingBlocks;
13730   L->getExitingBlocks(ExitingBlocks);
13731 
13732   // Form an expression for the maximum exit count possible for this loop. We
13733   // merge the max and exact information to approximate a version of
13734   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13735   SmallVector<const SCEV*, 4> ExitCounts;
13736   for (BasicBlock *ExitingBB : ExitingBlocks) {
13737     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13738     if (isa<SCEVCouldNotCompute>(ExitCount))
13739       ExitCount = getExitCount(L, ExitingBB,
13740                                   ScalarEvolution::ConstantMaximum);
13741     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13742       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13743              "We should only have known counts for exiting blocks that "
13744              "dominate latch!");
13745       ExitCounts.push_back(ExitCount);
13746     }
13747   }
13748   if (ExitCounts.empty())
13749     return getCouldNotCompute();
13750   return getUMinFromMismatchedTypes(ExitCounts);
13751 }
13752 
13753 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
13754 /// in the map. It skips AddRecExpr because we cannot guarantee that the
13755 /// replacement is loop invariant in the loop of the AddRec.
13756 ///
13757 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
13758 /// supported.
13759 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13760   const DenseMap<const SCEV *, const SCEV *> &Map;
13761 
13762 public:
13763   SCEVLoopGuardRewriter(ScalarEvolution &SE,
13764                         DenseMap<const SCEV *, const SCEV *> &M)
13765       : SCEVRewriteVisitor(SE), Map(M) {}
13766 
13767   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13768 
13769   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13770     auto I = Map.find(Expr);
13771     if (I == Map.end())
13772       return Expr;
13773     return I->second;
13774   }
13775 
13776   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13777     auto I = Map.find(Expr);
13778     if (I == Map.end())
13779       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
13780           Expr);
13781     return I->second;
13782   }
13783 };
13784 
13785 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13786   SmallVector<const SCEV *> ExprsToRewrite;
13787   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13788                               const SCEV *RHS,
13789                               DenseMap<const SCEV *, const SCEV *>
13790                                   &RewriteMap) {
13791     // WARNING: It is generally unsound to apply any wrap flags to the proposed
13792     // replacement SCEV which isn't directly implied by the structure of that
13793     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
13794     // legal.  See the scoping rules for flags in the header to understand why.
13795 
13796     // If LHS is a constant, apply information to the other expression.
13797     if (isa<SCEVConstant>(LHS)) {
13798       std::swap(LHS, RHS);
13799       Predicate = CmpInst::getSwappedPredicate(Predicate);
13800     }
13801 
13802     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
13803     // create this form when combining two checks of the form (X u< C2 + C1) and
13804     // (X >=u C1).
13805     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
13806                                  &ExprsToRewrite]() {
13807       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
13808       if (!AddExpr || AddExpr->getNumOperands() != 2)
13809         return false;
13810 
13811       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
13812       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
13813       auto *C2 = dyn_cast<SCEVConstant>(RHS);
13814       if (!C1 || !C2 || !LHSUnknown)
13815         return false;
13816 
13817       auto ExactRegion =
13818           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
13819               .sub(C1->getAPInt());
13820 
13821       // Bail out, unless we have a non-wrapping, monotonic range.
13822       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
13823         return false;
13824       auto I = RewriteMap.find(LHSUnknown);
13825       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
13826       RewriteMap[LHSUnknown] = getUMaxExpr(
13827           getConstant(ExactRegion.getUnsignedMin()),
13828           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
13829       ExprsToRewrite.push_back(LHSUnknown);
13830       return true;
13831     };
13832     if (MatchRangeCheckIdiom())
13833       return;
13834 
13835     // If we have LHS == 0, check if LHS is computing a property of some unknown
13836     // SCEV %v which we can rewrite %v to express explicitly.
13837     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13838     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13839         RHSC->getValue()->isNullValue()) {
13840       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13841       // explicitly express that.
13842       const SCEV *URemLHS = nullptr;
13843       const SCEV *URemRHS = nullptr;
13844       if (matchURem(LHS, URemLHS, URemRHS)) {
13845         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13846           auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
13847           RewriteMap[LHSUnknown] = Multiple;
13848           ExprsToRewrite.push_back(LHSUnknown);
13849           return;
13850         }
13851       }
13852     }
13853 
13854     // Do not apply information for constants or if RHS contains an AddRec.
13855     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
13856       return;
13857 
13858     // If RHS is SCEVUnknown, make sure the information is applied to it.
13859     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
13860       std::swap(LHS, RHS);
13861       Predicate = CmpInst::getSwappedPredicate(Predicate);
13862     }
13863 
13864     // Limit to expressions that can be rewritten.
13865     if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
13866       return;
13867 
13868     // Check whether LHS has already been rewritten. In that case we want to
13869     // chain further rewrites onto the already rewritten value.
13870     auto I = RewriteMap.find(LHS);
13871     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13872 
13873     const SCEV *RewrittenRHS = nullptr;
13874     switch (Predicate) {
13875     case CmpInst::ICMP_ULT:
13876       RewrittenRHS =
13877           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13878       break;
13879     case CmpInst::ICMP_SLT:
13880       RewrittenRHS =
13881           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13882       break;
13883     case CmpInst::ICMP_ULE:
13884       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
13885       break;
13886     case CmpInst::ICMP_SLE:
13887       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
13888       break;
13889     case CmpInst::ICMP_UGT:
13890       RewrittenRHS =
13891           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13892       break;
13893     case CmpInst::ICMP_SGT:
13894       RewrittenRHS =
13895           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13896       break;
13897     case CmpInst::ICMP_UGE:
13898       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
13899       break;
13900     case CmpInst::ICMP_SGE:
13901       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
13902       break;
13903     case CmpInst::ICMP_EQ:
13904       if (isa<SCEVConstant>(RHS))
13905         RewrittenRHS = RHS;
13906       break;
13907     case CmpInst::ICMP_NE:
13908       if (isa<SCEVConstant>(RHS) &&
13909           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13910         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
13911       break;
13912     default:
13913       break;
13914     }
13915 
13916     if (RewrittenRHS) {
13917       RewriteMap[LHS] = RewrittenRHS;
13918       if (LHS == RewrittenLHS)
13919         ExprsToRewrite.push_back(LHS);
13920     }
13921   };
13922   // Starting at the loop predecessor, climb up the predecessor chain, as long
13923   // as there are predecessors that can be found that have unique successors
13924   // leading to the original header.
13925   // TODO: share this logic with isLoopEntryGuardedByCond.
13926   DenseMap<const SCEV *, const SCEV *> RewriteMap;
13927   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13928            L->getLoopPredecessor(), L->getHeader());
13929        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13930 
13931     const BranchInst *LoopEntryPredicate =
13932         dyn_cast<BranchInst>(Pair.first->getTerminator());
13933     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13934       continue;
13935 
13936     bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second;
13937     SmallVector<Value *, 8> Worklist;
13938     SmallPtrSet<Value *, 8> Visited;
13939     Worklist.push_back(LoopEntryPredicate->getCondition());
13940     while (!Worklist.empty()) {
13941       Value *Cond = Worklist.pop_back_val();
13942       if (!Visited.insert(Cond).second)
13943         continue;
13944 
13945       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13946         auto Predicate =
13947             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
13948         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13949                          getSCEV(Cmp->getOperand(1)), RewriteMap);
13950         continue;
13951       }
13952 
13953       Value *L, *R;
13954       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
13955                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
13956         Worklist.push_back(L);
13957         Worklist.push_back(R);
13958       }
13959     }
13960   }
13961 
13962   // Also collect information from assumptions dominating the loop.
13963   for (auto &AssumeVH : AC.assumptions()) {
13964     if (!AssumeVH)
13965       continue;
13966     auto *AssumeI = cast<CallInst>(AssumeVH);
13967     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13968     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13969       continue;
13970     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13971                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13972   }
13973 
13974   if (RewriteMap.empty())
13975     return Expr;
13976 
13977   // Now that all rewrite information is collect, rewrite the collected
13978   // expressions with the information in the map. This applies information to
13979   // sub-expressions.
13980   if (ExprsToRewrite.size() > 1) {
13981     for (const SCEV *Expr : ExprsToRewrite) {
13982       const SCEV *RewriteTo = RewriteMap[Expr];
13983       RewriteMap.erase(Expr);
13984       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13985       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
13986     }
13987   }
13988 
13989   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13990   return Rewriter.visit(Expr);
13991 }
13992