1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionDivision.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/InitializePasses.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/KnownBits.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <climits>
128 #include <cstddef>
129 #include <cstdint>
130 #include <cstdlib>
131 #include <map>
132 #include <memory>
133 #include <tuple>
134 #include <utility>
135 #include <vector>
136 
137 using namespace llvm;
138 using namespace PatternMatch;
139 
140 #define DEBUG_TYPE "scalar-evolution"
141 
142 STATISTIC(NumArrayLenItCounts,
143           "Number of trip counts computed with array length");
144 STATISTIC(NumTripCountsComputed,
145           "Number of loops with predictable loop counts");
146 STATISTIC(NumTripCountsNotComputed,
147           "Number of loops without predictable loop counts");
148 STATISTIC(NumBruteForceTripCountsComputed,
149           "Number of loops with trip counts computed by force");
150 
151 static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153                         cl::ZeroOrMore,
154                         cl::desc("Maximum number of iterations SCEV will "
155                                  "symbolically execute a constant "
156                                  "derived loop"),
157                         cl::init(100));
158 
159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
160 static cl::opt<bool> VerifySCEV(
161     "verify-scev", cl::Hidden,
162     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 static cl::opt<bool> VerifySCEVStrict(
164     "verify-scev-strict", cl::Hidden,
165     cl::desc("Enable stricter verification with -verify-scev is passed"));
166 static cl::opt<bool>
167     VerifySCEVMap("verify-scev-maps", cl::Hidden,
168                   cl::desc("Verify no dangling value in ScalarEvolution's "
169                            "ExprValueMap (slow)"));
170 
171 static cl::opt<bool> VerifyIR(
172     "scev-verify-ir", cl::Hidden,
173     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
174     cl::init(false));
175 
176 static cl::opt<unsigned> MulOpsInlineThreshold(
177     "scev-mulops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
179     cl::init(32));
180 
181 static cl::opt<unsigned> AddOpsInlineThreshold(
182     "scev-addops-inline-threshold", cl::Hidden,
183     cl::desc("Threshold for inlining addition operands into a SCEV"),
184     cl::init(500));
185 
186 static cl::opt<unsigned> MaxSCEVCompareDepth(
187     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
189     cl::init(32));
190 
191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
192     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
194     cl::init(2));
195 
196 static cl::opt<unsigned> MaxValueCompareDepth(
197     "scalar-evolution-max-value-compare-depth", cl::Hidden,
198     cl::desc("Maximum depth of recursive value complexity comparisons"),
199     cl::init(2));
200 
201 static cl::opt<unsigned>
202     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
203                   cl::desc("Maximum depth of recursive arithmetics"),
204                   cl::init(32));
205 
206 static cl::opt<unsigned> MaxConstantEvolvingDepth(
207     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
208     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
209 
210 static cl::opt<unsigned>
211     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
212                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
213                  cl::init(8));
214 
215 static cl::opt<unsigned>
216     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
217                   cl::desc("Max coefficients in AddRec during evolving"),
218                   cl::init(8));
219 
220 static cl::opt<unsigned>
221     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
222                   cl::desc("Size of the expression which is considered huge"),
223                   cl::init(4096));
224 
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227     cl::Hidden, cl::init(true),
228     cl::desc("When printing analysis, include information on every instruction"));
229 
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232     cl::init(false),
233     cl::desc("Use more powerful methods of sharpening expression ranges. May "
234              "be costly in terms of compile time"));
235 
236 //===----------------------------------------------------------------------===//
237 //                           SCEV class definitions
238 //===----------------------------------------------------------------------===//
239 
240 //===----------------------------------------------------------------------===//
241 // Implementation of the SCEV class.
242 //
243 
244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
245 LLVM_DUMP_METHOD void SCEV::dump() const {
246   print(dbgs());
247   dbgs() << '\n';
248 }
249 #endif
250 
251 void SCEV::print(raw_ostream &OS) const {
252   switch (getSCEVType()) {
253   case scConstant:
254     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
255     return;
256   case scPtrToInt: {
257     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
258     const SCEV *Op = PtrToInt->getOperand();
259     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
260        << *PtrToInt->getType() << ")";
261     return;
262   }
263   case scTruncate: {
264     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
265     const SCEV *Op = Trunc->getOperand();
266     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
267        << *Trunc->getType() << ")";
268     return;
269   }
270   case scZeroExtend: {
271     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
272     const SCEV *Op = ZExt->getOperand();
273     OS << "(zext " << *Op->getType() << " " << *Op << " to "
274        << *ZExt->getType() << ")";
275     return;
276   }
277   case scSignExtend: {
278     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
279     const SCEV *Op = SExt->getOperand();
280     OS << "(sext " << *Op->getType() << " " << *Op << " to "
281        << *SExt->getType() << ")";
282     return;
283   }
284   case scAddRecExpr: {
285     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
286     OS << "{" << *AR->getOperand(0);
287     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
288       OS << ",+," << *AR->getOperand(i);
289     OS << "}<";
290     if (AR->hasNoUnsignedWrap())
291       OS << "nuw><";
292     if (AR->hasNoSignedWrap())
293       OS << "nsw><";
294     if (AR->hasNoSelfWrap() &&
295         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
296       OS << "nw><";
297     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
298     OS << ">";
299     return;
300   }
301   case scAddExpr:
302   case scMulExpr:
303   case scUMaxExpr:
304   case scSMaxExpr:
305   case scUMinExpr:
306   case scSMinExpr: {
307     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
308     const char *OpStr = nullptr;
309     switch (NAry->getSCEVType()) {
310     case scAddExpr: OpStr = " + "; break;
311     case scMulExpr: OpStr = " * "; break;
312     case scUMaxExpr: OpStr = " umax "; break;
313     case scSMaxExpr: OpStr = " smax "; break;
314     case scUMinExpr:
315       OpStr = " umin ";
316       break;
317     case scSMinExpr:
318       OpStr = " smin ";
319       break;
320     default:
321       llvm_unreachable("There are no other nary expression types.");
322     }
323     OS << "(";
324     ListSeparator LS(OpStr);
325     for (const SCEV *Op : NAry->operands())
326       OS << LS << *Op;
327     OS << ")";
328     switch (NAry->getSCEVType()) {
329     case scAddExpr:
330     case scMulExpr:
331       if (NAry->hasNoUnsignedWrap())
332         OS << "<nuw>";
333       if (NAry->hasNoSignedWrap())
334         OS << "<nsw>";
335       break;
336     default:
337       // Nothing to print for other nary expressions.
338       break;
339     }
340     return;
341   }
342   case scUDivExpr: {
343     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
344     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
345     return;
346   }
347   case scUnknown: {
348     const SCEVUnknown *U = cast<SCEVUnknown>(this);
349     Type *AllocTy;
350     if (U->isSizeOf(AllocTy)) {
351       OS << "sizeof(" << *AllocTy << ")";
352       return;
353     }
354     if (U->isAlignOf(AllocTy)) {
355       OS << "alignof(" << *AllocTy << ")";
356       return;
357     }
358 
359     Type *CTy;
360     Constant *FieldNo;
361     if (U->isOffsetOf(CTy, FieldNo)) {
362       OS << "offsetof(" << *CTy << ", ";
363       FieldNo->printAsOperand(OS, false);
364       OS << ")";
365       return;
366     }
367 
368     // Otherwise just print it normally.
369     U->getValue()->printAsOperand(OS, false);
370     return;
371   }
372   case scCouldNotCompute:
373     OS << "***COULDNOTCOMPUTE***";
374     return;
375   }
376   llvm_unreachable("Unknown SCEV kind!");
377 }
378 
379 Type *SCEV::getType() const {
380   switch (getSCEVType()) {
381   case scConstant:
382     return cast<SCEVConstant>(this)->getType();
383   case scPtrToInt:
384   case scTruncate:
385   case scZeroExtend:
386   case scSignExtend:
387     return cast<SCEVCastExpr>(this)->getType();
388   case scAddRecExpr:
389   case scMulExpr:
390   case scUMaxExpr:
391   case scSMaxExpr:
392   case scUMinExpr:
393   case scSMinExpr:
394     return cast<SCEVNAryExpr>(this)->getType();
395   case scAddExpr:
396     return cast<SCEVAddExpr>(this)->getType();
397   case scUDivExpr:
398     return cast<SCEVUDivExpr>(this)->getType();
399   case scUnknown:
400     return cast<SCEVUnknown>(this)->getType();
401   case scCouldNotCompute:
402     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
403   }
404   llvm_unreachable("Unknown SCEV kind!");
405 }
406 
407 bool SCEV::isZero() const {
408   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
409     return SC->getValue()->isZero();
410   return false;
411 }
412 
413 bool SCEV::isOne() const {
414   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
415     return SC->getValue()->isOne();
416   return false;
417 }
418 
419 bool SCEV::isAllOnesValue() const {
420   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
421     return SC->getValue()->isMinusOne();
422   return false;
423 }
424 
425 bool SCEV::isNonConstantNegative() const {
426   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
427   if (!Mul) return false;
428 
429   // If there is a constant factor, it will be first.
430   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
431   if (!SC) return false;
432 
433   // Return true if the value is negative, this matches things like (-42 * V).
434   return SC->getAPInt().isNegative();
435 }
436 
437 SCEVCouldNotCompute::SCEVCouldNotCompute() :
438   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
439 
440 bool SCEVCouldNotCompute::classof(const SCEV *S) {
441   return S->getSCEVType() == scCouldNotCompute;
442 }
443 
444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
445   FoldingSetNodeID ID;
446   ID.AddInteger(scConstant);
447   ID.AddPointer(V);
448   void *IP = nullptr;
449   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
450   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
451   UniqueSCEVs.InsertNode(S, IP);
452   return S;
453 }
454 
455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
456   return getConstant(ConstantInt::get(getContext(), Val));
457 }
458 
459 const SCEV *
460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
461   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
462   return getConstant(ConstantInt::get(ITy, V, isSigned));
463 }
464 
465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
466                            const SCEV *op, Type *ty)
467     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
468   Operands[0] = op;
469 }
470 
471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
472                                    Type *ITy)
473     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
474   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
475          "Must be a non-bit-width-changing pointer-to-integer cast!");
476 }
477 
478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
479                                            SCEVTypes SCEVTy, const SCEV *op,
480                                            Type *ty)
481     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
482 
483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
484                                    Type *ty)
485     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
486   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
487          "Cannot truncate non-integer value!");
488 }
489 
490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
491                                        const SCEV *op, Type *ty)
492     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
493   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
494          "Cannot zero extend non-integer value!");
495 }
496 
497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
498                                        const SCEV *op, Type *ty)
499     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
500   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
501          "Cannot sign extend non-integer value!");
502 }
503 
504 void SCEVUnknown::deleted() {
505   // Clear this SCEVUnknown from various maps.
506   SE->forgetMemoizedResults(this);
507 
508   // Remove this SCEVUnknown from the uniquing map.
509   SE->UniqueSCEVs.RemoveNode(this);
510 
511   // Release the value.
512   setValPtr(nullptr);
513 }
514 
515 void SCEVUnknown::allUsesReplacedWith(Value *New) {
516   // Remove this SCEVUnknown from the uniquing map.
517   SE->UniqueSCEVs.RemoveNode(this);
518 
519   // Update this SCEVUnknown to point to the new value. This is needed
520   // because there may still be outstanding SCEVs which still point to
521   // this SCEVUnknown.
522   setValPtr(New);
523 }
524 
525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
526   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
527     if (VCE->getOpcode() == Instruction::PtrToInt)
528       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
529         if (CE->getOpcode() == Instruction::GetElementPtr &&
530             CE->getOperand(0)->isNullValue() &&
531             CE->getNumOperands() == 2)
532           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
533             if (CI->isOne()) {
534               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
535                                  ->getElementType();
536               return true;
537             }
538 
539   return false;
540 }
541 
542 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
543   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
544     if (VCE->getOpcode() == Instruction::PtrToInt)
545       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
546         if (CE->getOpcode() == Instruction::GetElementPtr &&
547             CE->getOperand(0)->isNullValue()) {
548           Type *Ty =
549             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
550           if (StructType *STy = dyn_cast<StructType>(Ty))
551             if (!STy->isPacked() &&
552                 CE->getNumOperands() == 3 &&
553                 CE->getOperand(1)->isNullValue()) {
554               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
555                 if (CI->isOne() &&
556                     STy->getNumElements() == 2 &&
557                     STy->getElementType(0)->isIntegerTy(1)) {
558                   AllocTy = STy->getElementType(1);
559                   return true;
560                 }
561             }
562         }
563 
564   return false;
565 }
566 
567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
568   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
569     if (VCE->getOpcode() == Instruction::PtrToInt)
570       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
571         if (CE->getOpcode() == Instruction::GetElementPtr &&
572             CE->getNumOperands() == 3 &&
573             CE->getOperand(0)->isNullValue() &&
574             CE->getOperand(1)->isNullValue()) {
575           Type *Ty =
576             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
577           // Ignore vector types here so that ScalarEvolutionExpander doesn't
578           // emit getelementptrs that index into vectors.
579           if (Ty->isStructTy() || Ty->isArrayTy()) {
580             CTy = Ty;
581             FieldNo = CE->getOperand(2);
582             return true;
583           }
584         }
585 
586   return false;
587 }
588 
589 //===----------------------------------------------------------------------===//
590 //                               SCEV Utilities
591 //===----------------------------------------------------------------------===//
592 
593 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
594 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
595 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
596 /// have been previously deemed to be "equally complex" by this routine.  It is
597 /// intended to avoid exponential time complexity in cases like:
598 ///
599 ///   %a = f(%x, %y)
600 ///   %b = f(%a, %a)
601 ///   %c = f(%b, %b)
602 ///
603 ///   %d = f(%x, %y)
604 ///   %e = f(%d, %d)
605 ///   %f = f(%e, %e)
606 ///
607 ///   CompareValueComplexity(%f, %c)
608 ///
609 /// Since we do not continue running this routine on expression trees once we
610 /// have seen unequal values, there is no need to track them in the cache.
611 static int
612 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
613                        const LoopInfo *const LI, Value *LV, Value *RV,
614                        unsigned Depth) {
615   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
616     return 0;
617 
618   // Order pointer values after integer values. This helps SCEVExpander form
619   // GEPs.
620   bool LIsPointer = LV->getType()->isPointerTy(),
621        RIsPointer = RV->getType()->isPointerTy();
622   if (LIsPointer != RIsPointer)
623     return (int)LIsPointer - (int)RIsPointer;
624 
625   // Compare getValueID values.
626   unsigned LID = LV->getValueID(), RID = RV->getValueID();
627   if (LID != RID)
628     return (int)LID - (int)RID;
629 
630   // Sort arguments by their position.
631   if (const auto *LA = dyn_cast<Argument>(LV)) {
632     const auto *RA = cast<Argument>(RV);
633     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
634     return (int)LArgNo - (int)RArgNo;
635   }
636 
637   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
638     const auto *RGV = cast<GlobalValue>(RV);
639 
640     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
641       auto LT = GV->getLinkage();
642       return !(GlobalValue::isPrivateLinkage(LT) ||
643                GlobalValue::isInternalLinkage(LT));
644     };
645 
646     // Use the names to distinguish the two values, but only if the
647     // names are semantically important.
648     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
649       return LGV->getName().compare(RGV->getName());
650   }
651 
652   // For instructions, compare their loop depth, and their operand count.  This
653   // is pretty loose.
654   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
655     const auto *RInst = cast<Instruction>(RV);
656 
657     // Compare loop depths.
658     const BasicBlock *LParent = LInst->getParent(),
659                      *RParent = RInst->getParent();
660     if (LParent != RParent) {
661       unsigned LDepth = LI->getLoopDepth(LParent),
662                RDepth = LI->getLoopDepth(RParent);
663       if (LDepth != RDepth)
664         return (int)LDepth - (int)RDepth;
665     }
666 
667     // Compare the number of operands.
668     unsigned LNumOps = LInst->getNumOperands(),
669              RNumOps = RInst->getNumOperands();
670     if (LNumOps != RNumOps)
671       return (int)LNumOps - (int)RNumOps;
672 
673     for (unsigned Idx : seq(0u, LNumOps)) {
674       int Result =
675           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
676                                  RInst->getOperand(Idx), Depth + 1);
677       if (Result != 0)
678         return Result;
679     }
680   }
681 
682   EqCacheValue.unionSets(LV, RV);
683   return 0;
684 }
685 
686 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
687 // than RHS, respectively. A three-way result allows recursive comparisons to be
688 // more efficient.
689 // If the max analysis depth was reached, return None, assuming we do not know
690 // if they are equivalent for sure.
691 static Optional<int>
692 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
693                       EquivalenceClasses<const Value *> &EqCacheValue,
694                       const LoopInfo *const LI, const SCEV *LHS,
695                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
696   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
697   if (LHS == RHS)
698     return 0;
699 
700   // Primarily, sort the SCEVs by their getSCEVType().
701   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
702   if (LType != RType)
703     return (int)LType - (int)RType;
704 
705   if (EqCacheSCEV.isEquivalent(LHS, RHS))
706     return 0;
707 
708   if (Depth > MaxSCEVCompareDepth)
709     return None;
710 
711   // Aside from the getSCEVType() ordering, the particular ordering
712   // isn't very important except that it's beneficial to be consistent,
713   // so that (a + b) and (b + a) don't end up as different expressions.
714   switch (LType) {
715   case scUnknown: {
716     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
717     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
718 
719     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
720                                    RU->getValue(), Depth + 1);
721     if (X == 0)
722       EqCacheSCEV.unionSets(LHS, RHS);
723     return X;
724   }
725 
726   case scConstant: {
727     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
728     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
729 
730     // Compare constant values.
731     const APInt &LA = LC->getAPInt();
732     const APInt &RA = RC->getAPInt();
733     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
734     if (LBitWidth != RBitWidth)
735       return (int)LBitWidth - (int)RBitWidth;
736     return LA.ult(RA) ? -1 : 1;
737   }
738 
739   case scAddRecExpr: {
740     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
741     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
742 
743     // There is always a dominance between two recs that are used by one SCEV,
744     // so we can safely sort recs by loop header dominance. We require such
745     // order in getAddExpr.
746     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
747     if (LLoop != RLoop) {
748       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
749       assert(LHead != RHead && "Two loops share the same header?");
750       if (DT.dominates(LHead, RHead))
751         return 1;
752       else
753         assert(DT.dominates(RHead, LHead) &&
754                "No dominance between recurrences used by one SCEV?");
755       return -1;
756     }
757 
758     // Addrec complexity grows with operand count.
759     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
760     if (LNumOps != RNumOps)
761       return (int)LNumOps - (int)RNumOps;
762 
763     // Lexicographically compare.
764     for (unsigned i = 0; i != LNumOps; ++i) {
765       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
766                                      LA->getOperand(i), RA->getOperand(i), DT,
767                                      Depth + 1);
768       if (X != 0)
769         return X;
770     }
771     EqCacheSCEV.unionSets(LHS, RHS);
772     return 0;
773   }
774 
775   case scAddExpr:
776   case scMulExpr:
777   case scSMaxExpr:
778   case scUMaxExpr:
779   case scSMinExpr:
780   case scUMinExpr: {
781     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
782     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
783 
784     // Lexicographically compare n-ary expressions.
785     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
786     if (LNumOps != RNumOps)
787       return (int)LNumOps - (int)RNumOps;
788 
789     for (unsigned i = 0; i != LNumOps; ++i) {
790       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
791                                      LC->getOperand(i), RC->getOperand(i), DT,
792                                      Depth + 1);
793       if (X != 0)
794         return X;
795     }
796     EqCacheSCEV.unionSets(LHS, RHS);
797     return 0;
798   }
799 
800   case scUDivExpr: {
801     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
802     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
803 
804     // Lexicographically compare udiv expressions.
805     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
806                                    RC->getLHS(), DT, Depth + 1);
807     if (X != 0)
808       return X;
809     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
810                               RC->getRHS(), DT, Depth + 1);
811     if (X == 0)
812       EqCacheSCEV.unionSets(LHS, RHS);
813     return X;
814   }
815 
816   case scPtrToInt:
817   case scTruncate:
818   case scZeroExtend:
819   case scSignExtend: {
820     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
821     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
822 
823     // Compare cast expressions by operand.
824     auto X =
825         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
826                               RC->getOperand(), DT, Depth + 1);
827     if (X == 0)
828       EqCacheSCEV.unionSets(LHS, RHS);
829     return X;
830   }
831 
832   case scCouldNotCompute:
833     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
834   }
835   llvm_unreachable("Unknown SCEV kind!");
836 }
837 
838 /// Given a list of SCEV objects, order them by their complexity, and group
839 /// objects of the same complexity together by value.  When this routine is
840 /// finished, we know that any duplicates in the vector are consecutive and that
841 /// complexity is monotonically increasing.
842 ///
843 /// Note that we go take special precautions to ensure that we get deterministic
844 /// results from this routine.  In other words, we don't want the results of
845 /// this to depend on where the addresses of various SCEV objects happened to
846 /// land in memory.
847 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
848                               LoopInfo *LI, DominatorTree &DT) {
849   if (Ops.size() < 2) return;  // Noop
850 
851   EquivalenceClasses<const SCEV *> EqCacheSCEV;
852   EquivalenceClasses<const Value *> EqCacheValue;
853 
854   // Whether LHS has provably less complexity than RHS.
855   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
856     auto Complexity =
857         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
858     return Complexity && *Complexity < 0;
859   };
860   if (Ops.size() == 2) {
861     // This is the common case, which also happens to be trivially simple.
862     // Special case it.
863     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
864     if (IsLessComplex(RHS, LHS))
865       std::swap(LHS, RHS);
866     return;
867   }
868 
869   // Do the rough sort by complexity.
870   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
871     return IsLessComplex(LHS, RHS);
872   });
873 
874   // Now that we are sorted by complexity, group elements of the same
875   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
876   // be extremely short in practice.  Note that we take this approach because we
877   // do not want to depend on the addresses of the objects we are grouping.
878   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
879     const SCEV *S = Ops[i];
880     unsigned Complexity = S->getSCEVType();
881 
882     // If there are any objects of the same complexity and same value as this
883     // one, group them.
884     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
885       if (Ops[j] == S) { // Found a duplicate.
886         // Move it to immediately after i'th element.
887         std::swap(Ops[i+1], Ops[j]);
888         ++i;   // no need to rescan it.
889         if (i == e-2) return;  // Done!
890       }
891     }
892   }
893 }
894 
895 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
896 /// least HugeExprThreshold nodes).
897 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
898   return any_of(Ops, [](const SCEV *S) {
899     return S->getExpressionSize() >= HugeExprThreshold;
900   });
901 }
902 
903 //===----------------------------------------------------------------------===//
904 //                      Simple SCEV method implementations
905 //===----------------------------------------------------------------------===//
906 
907 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
908 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
909                                        ScalarEvolution &SE,
910                                        Type *ResultTy) {
911   // Handle the simplest case efficiently.
912   if (K == 1)
913     return SE.getTruncateOrZeroExtend(It, ResultTy);
914 
915   // We are using the following formula for BC(It, K):
916   //
917   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
918   //
919   // Suppose, W is the bitwidth of the return value.  We must be prepared for
920   // overflow.  Hence, we must assure that the result of our computation is
921   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
922   // safe in modular arithmetic.
923   //
924   // However, this code doesn't use exactly that formula; the formula it uses
925   // is something like the following, where T is the number of factors of 2 in
926   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
927   // exponentiation:
928   //
929   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
930   //
931   // This formula is trivially equivalent to the previous formula.  However,
932   // this formula can be implemented much more efficiently.  The trick is that
933   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
934   // arithmetic.  To do exact division in modular arithmetic, all we have
935   // to do is multiply by the inverse.  Therefore, this step can be done at
936   // width W.
937   //
938   // The next issue is how to safely do the division by 2^T.  The way this
939   // is done is by doing the multiplication step at a width of at least W + T
940   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
941   // when we perform the division by 2^T (which is equivalent to a right shift
942   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
943   // truncated out after the division by 2^T.
944   //
945   // In comparison to just directly using the first formula, this technique
946   // is much more efficient; using the first formula requires W * K bits,
947   // but this formula less than W + K bits. Also, the first formula requires
948   // a division step, whereas this formula only requires multiplies and shifts.
949   //
950   // It doesn't matter whether the subtraction step is done in the calculation
951   // width or the input iteration count's width; if the subtraction overflows,
952   // the result must be zero anyway.  We prefer here to do it in the width of
953   // the induction variable because it helps a lot for certain cases; CodeGen
954   // isn't smart enough to ignore the overflow, which leads to much less
955   // efficient code if the width of the subtraction is wider than the native
956   // register width.
957   //
958   // (It's possible to not widen at all by pulling out factors of 2 before
959   // the multiplication; for example, K=2 can be calculated as
960   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
961   // extra arithmetic, so it's not an obvious win, and it gets
962   // much more complicated for K > 3.)
963 
964   // Protection from insane SCEVs; this bound is conservative,
965   // but it probably doesn't matter.
966   if (K > 1000)
967     return SE.getCouldNotCompute();
968 
969   unsigned W = SE.getTypeSizeInBits(ResultTy);
970 
971   // Calculate K! / 2^T and T; we divide out the factors of two before
972   // multiplying for calculating K! / 2^T to avoid overflow.
973   // Other overflow doesn't matter because we only care about the bottom
974   // W bits of the result.
975   APInt OddFactorial(W, 1);
976   unsigned T = 1;
977   for (unsigned i = 3; i <= K; ++i) {
978     APInt Mult(W, i);
979     unsigned TwoFactors = Mult.countTrailingZeros();
980     T += TwoFactors;
981     Mult.lshrInPlace(TwoFactors);
982     OddFactorial *= Mult;
983   }
984 
985   // We need at least W + T bits for the multiplication step
986   unsigned CalculationBits = W + T;
987 
988   // Calculate 2^T, at width T+W.
989   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
990 
991   // Calculate the multiplicative inverse of K! / 2^T;
992   // this multiplication factor will perform the exact division by
993   // K! / 2^T.
994   APInt Mod = APInt::getSignedMinValue(W+1);
995   APInt MultiplyFactor = OddFactorial.zext(W+1);
996   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
997   MultiplyFactor = MultiplyFactor.trunc(W);
998 
999   // Calculate the product, at width T+W
1000   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1001                                                       CalculationBits);
1002   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1003   for (unsigned i = 1; i != K; ++i) {
1004     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1005     Dividend = SE.getMulExpr(Dividend,
1006                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1007   }
1008 
1009   // Divide by 2^T
1010   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1011 
1012   // Truncate the result, and divide by K! / 2^T.
1013 
1014   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1015                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1016 }
1017 
1018 /// Return the value of this chain of recurrences at the specified iteration
1019 /// number.  We can evaluate this recurrence by multiplying each element in the
1020 /// chain by the binomial coefficient corresponding to it.  In other words, we
1021 /// can evaluate {A,+,B,+,C,+,D} as:
1022 ///
1023 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1024 ///
1025 /// where BC(It, k) stands for binomial coefficient.
1026 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1027                                                 ScalarEvolution &SE) const {
1028   const SCEV *Result = getStart();
1029   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1030     // The computation is correct in the face of overflow provided that the
1031     // multiplication is performed _after_ the evaluation of the binomial
1032     // coefficient.
1033     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1034     if (isa<SCEVCouldNotCompute>(Coeff))
1035       return Coeff;
1036 
1037     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1038   }
1039   return Result;
1040 }
1041 
1042 //===----------------------------------------------------------------------===//
1043 //                    SCEV Expression folder implementations
1044 //===----------------------------------------------------------------------===//
1045 
1046 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty,
1047                                              unsigned Depth) {
1048   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1049   assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once.");
1050 
1051   // We could be called with an integer-typed operands during SCEV rewrites.
1052   // Since the operand is an integer already, just perform zext/trunc/self cast.
1053   if (!Op->getType()->isPointerTy())
1054     return getTruncateOrZeroExtend(Op, Ty);
1055 
1056   // What would be an ID for such a SCEV cast expression?
1057   FoldingSetNodeID ID;
1058   ID.AddInteger(scPtrToInt);
1059   ID.AddPointer(Op);
1060 
1061   void *IP = nullptr;
1062 
1063   // Is there already an expression for such a cast?
1064   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1065     return getTruncateOrZeroExtend(S, Ty);
1066 
1067   // If not, is this expression something we can't reduce any further?
1068   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1069     Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1070     assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(
1071                Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
1072            "We can only model ptrtoint if SCEV's effective (integer) type is "
1073            "sufficiently wide to represent all possible pointer values.");
1074 
1075     // Perform some basic constant folding. If the operand of the ptr2int cast
1076     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1077     // left as-is), but produce a zero constant.
1078     // NOTE: We could handle a more general case, but lack motivational cases.
1079     if (isa<ConstantPointerNull>(U->getValue()))
1080       return getZero(Ty);
1081 
1082     // Create an explicit cast node.
1083     // We can reuse the existing insert position since if we get here,
1084     // we won't have made any changes which would invalidate it.
1085     SCEV *S = new (SCEVAllocator)
1086         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1087     UniqueSCEVs.InsertNode(S, IP);
1088     addToLoopUseLists(S);
1089     return getTruncateOrZeroExtend(S, Ty);
1090   }
1091 
1092   assert(Depth == 0 &&
1093          "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.");
1094 
1095   // Otherwise, we've got some expression that is more complex than just a
1096   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1097   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1098   // only, and the expressions must otherwise be integer-typed.
1099   // So sink the cast down to the SCEVUnknown's.
1100 
1101   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1102   /// which computes a pointer-typed value, and rewrites the whole expression
1103   /// tree so that *all* the computations are done on integers, and the only
1104   /// pointer-typed operands in the expression are SCEVUnknown.
1105   class SCEVPtrToIntSinkingRewriter
1106       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1107     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1108 
1109   public:
1110     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1111 
1112     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1113       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1114       return Rewriter.visit(Scev);
1115     }
1116 
1117     const SCEV *visit(const SCEV *S) {
1118       Type *STy = S->getType();
1119       // If the expression is not pointer-typed, just keep it as-is.
1120       if (!STy->isPointerTy())
1121         return S;
1122       // Else, recursively sink the cast down into it.
1123       return Base::visit(S);
1124     }
1125 
1126     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1127       SmallVector<const SCEV *, 2> Operands;
1128       bool Changed = false;
1129       for (auto *Op : Expr->operands()) {
1130         Operands.push_back(visit(Op));
1131         Changed |= Op != Operands.back();
1132       }
1133       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1134     }
1135 
1136     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1137       SmallVector<const SCEV *, 2> Operands;
1138       bool Changed = false;
1139       for (auto *Op : Expr->operands()) {
1140         Operands.push_back(visit(Op));
1141         Changed |= Op != Operands.back();
1142       }
1143       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1144     }
1145 
1146     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1147       Type *ExprPtrTy = Expr->getType();
1148       assert(ExprPtrTy->isPointerTy() &&
1149              "Should only reach pointer-typed SCEVUnknown's.");
1150       Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy);
1151       return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1);
1152     }
1153   };
1154 
1155   // And actually perform the cast sinking.
1156   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1157   assert(IntOp->getType()->isIntegerTy() &&
1158          "We must have succeeded in sinking the cast, "
1159          "and ending up with an integer-typed expression!");
1160   return getTruncateOrZeroExtend(IntOp, Ty);
1161 }
1162 
1163 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1164                                              unsigned Depth) {
1165   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1166          "This is not a truncating conversion!");
1167   assert(isSCEVable(Ty) &&
1168          "This is not a conversion to a SCEVable type!");
1169   Ty = getEffectiveSCEVType(Ty);
1170 
1171   FoldingSetNodeID ID;
1172   ID.AddInteger(scTruncate);
1173   ID.AddPointer(Op);
1174   ID.AddPointer(Ty);
1175   void *IP = nullptr;
1176   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1177 
1178   // Fold if the operand is constant.
1179   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1180     return getConstant(
1181       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1182 
1183   // trunc(trunc(x)) --> trunc(x)
1184   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1185     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1186 
1187   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1188   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1189     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1190 
1191   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1192   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1193     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1194 
1195   if (Depth > MaxCastDepth) {
1196     SCEV *S =
1197         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1198     UniqueSCEVs.InsertNode(S, IP);
1199     addToLoopUseLists(S);
1200     return S;
1201   }
1202 
1203   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1204   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1205   // if after transforming we have at most one truncate, not counting truncates
1206   // that replace other casts.
1207   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1208     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1209     SmallVector<const SCEV *, 4> Operands;
1210     unsigned numTruncs = 0;
1211     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1212          ++i) {
1213       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1214       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1215           isa<SCEVTruncateExpr>(S))
1216         numTruncs++;
1217       Operands.push_back(S);
1218     }
1219     if (numTruncs < 2) {
1220       if (isa<SCEVAddExpr>(Op))
1221         return getAddExpr(Operands);
1222       else if (isa<SCEVMulExpr>(Op))
1223         return getMulExpr(Operands);
1224       else
1225         llvm_unreachable("Unexpected SCEV type for Op.");
1226     }
1227     // Although we checked in the beginning that ID is not in the cache, it is
1228     // possible that during recursion and different modification ID was inserted
1229     // into the cache. So if we find it, just return it.
1230     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1231       return S;
1232   }
1233 
1234   // If the input value is a chrec scev, truncate the chrec's operands.
1235   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1236     SmallVector<const SCEV *, 4> Operands;
1237     for (const SCEV *Op : AddRec->operands())
1238       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1239     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1240   }
1241 
1242   // Return zero if truncating to known zeros.
1243   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1244   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1245     return getZero(Ty);
1246 
1247   // The cast wasn't folded; create an explicit cast node. We can reuse
1248   // the existing insert position since if we get here, we won't have
1249   // made any changes which would invalidate it.
1250   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1251                                                  Op, Ty);
1252   UniqueSCEVs.InsertNode(S, IP);
1253   addToLoopUseLists(S);
1254   return S;
1255 }
1256 
1257 // Get the limit of a recurrence such that incrementing by Step cannot cause
1258 // signed overflow as long as the value of the recurrence within the
1259 // loop does not exceed this limit before incrementing.
1260 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1261                                                  ICmpInst::Predicate *Pred,
1262                                                  ScalarEvolution *SE) {
1263   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1264   if (SE->isKnownPositive(Step)) {
1265     *Pred = ICmpInst::ICMP_SLT;
1266     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1267                            SE->getSignedRangeMax(Step));
1268   }
1269   if (SE->isKnownNegative(Step)) {
1270     *Pred = ICmpInst::ICMP_SGT;
1271     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1272                            SE->getSignedRangeMin(Step));
1273   }
1274   return nullptr;
1275 }
1276 
1277 // Get the limit of a recurrence such that incrementing by Step cannot cause
1278 // unsigned overflow as long as the value of the recurrence within the loop does
1279 // not exceed this limit before incrementing.
1280 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1281                                                    ICmpInst::Predicate *Pred,
1282                                                    ScalarEvolution *SE) {
1283   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1284   *Pred = ICmpInst::ICMP_ULT;
1285 
1286   return SE->getConstant(APInt::getMinValue(BitWidth) -
1287                          SE->getUnsignedRangeMax(Step));
1288 }
1289 
1290 namespace {
1291 
1292 struct ExtendOpTraitsBase {
1293   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1294                                                           unsigned);
1295 };
1296 
1297 // Used to make code generic over signed and unsigned overflow.
1298 template <typename ExtendOp> struct ExtendOpTraits {
1299   // Members present:
1300   //
1301   // static const SCEV::NoWrapFlags WrapType;
1302   //
1303   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1304   //
1305   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1306   //                                           ICmpInst::Predicate *Pred,
1307   //                                           ScalarEvolution *SE);
1308 };
1309 
1310 template <>
1311 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1312   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1313 
1314   static const GetExtendExprTy GetExtendExpr;
1315 
1316   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1317                                              ICmpInst::Predicate *Pred,
1318                                              ScalarEvolution *SE) {
1319     return getSignedOverflowLimitForStep(Step, Pred, SE);
1320   }
1321 };
1322 
1323 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1324     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1325 
1326 template <>
1327 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1328   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1329 
1330   static const GetExtendExprTy GetExtendExpr;
1331 
1332   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1333                                              ICmpInst::Predicate *Pred,
1334                                              ScalarEvolution *SE) {
1335     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1336   }
1337 };
1338 
1339 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1340     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1341 
1342 } // end anonymous namespace
1343 
1344 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1345 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1346 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1347 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1348 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1349 // expression "Step + sext/zext(PreIncAR)" is congruent with
1350 // "sext/zext(PostIncAR)"
1351 template <typename ExtendOpTy>
1352 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1353                                         ScalarEvolution *SE, unsigned Depth) {
1354   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1355   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1356 
1357   const Loop *L = AR->getLoop();
1358   const SCEV *Start = AR->getStart();
1359   const SCEV *Step = AR->getStepRecurrence(*SE);
1360 
1361   // Check for a simple looking step prior to loop entry.
1362   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1363   if (!SA)
1364     return nullptr;
1365 
1366   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1367   // subtraction is expensive. For this purpose, perform a quick and dirty
1368   // difference, by checking for Step in the operand list.
1369   SmallVector<const SCEV *, 4> DiffOps;
1370   for (const SCEV *Op : SA->operands())
1371     if (Op != Step)
1372       DiffOps.push_back(Op);
1373 
1374   if (DiffOps.size() == SA->getNumOperands())
1375     return nullptr;
1376 
1377   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1378   // `Step`:
1379 
1380   // 1. NSW/NUW flags on the step increment.
1381   auto PreStartFlags =
1382     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1383   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1384   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1385       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1386 
1387   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1388   // "S+X does not sign/unsign-overflow".
1389   //
1390 
1391   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1392   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1393       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1394     return PreStart;
1395 
1396   // 2. Direct overflow check on the step operation's expression.
1397   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1398   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1399   const SCEV *OperandExtendedStart =
1400       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1401                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1402   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1403     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1404       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1405       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1406       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1407       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1408     }
1409     return PreStart;
1410   }
1411 
1412   // 3. Loop precondition.
1413   ICmpInst::Predicate Pred;
1414   const SCEV *OverflowLimit =
1415       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1416 
1417   if (OverflowLimit &&
1418       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1419     return PreStart;
1420 
1421   return nullptr;
1422 }
1423 
1424 // Get the normalized zero or sign extended expression for this AddRec's Start.
1425 template <typename ExtendOpTy>
1426 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1427                                         ScalarEvolution *SE,
1428                                         unsigned Depth) {
1429   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1430 
1431   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1432   if (!PreStart)
1433     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1434 
1435   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1436                                              Depth),
1437                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1438 }
1439 
1440 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1441 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1442 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1443 //
1444 // Formally:
1445 //
1446 //     {S,+,X} == {S-T,+,X} + T
1447 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1448 //
1449 // If ({S-T,+,X} + T) does not overflow  ... (1)
1450 //
1451 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1452 //
1453 // If {S-T,+,X} does not overflow  ... (2)
1454 //
1455 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1456 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1457 //
1458 // If (S-T)+T does not overflow  ... (3)
1459 //
1460 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1461 //      == {Ext(S),+,Ext(X)} == LHS
1462 //
1463 // Thus, if (1), (2) and (3) are true for some T, then
1464 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1465 //
1466 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1467 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1468 // to check for (1) and (2).
1469 //
1470 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1471 // is `Delta` (defined below).
1472 template <typename ExtendOpTy>
1473 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1474                                                 const SCEV *Step,
1475                                                 const Loop *L) {
1476   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1477 
1478   // We restrict `Start` to a constant to prevent SCEV from spending too much
1479   // time here.  It is correct (but more expensive) to continue with a
1480   // non-constant `Start` and do a general SCEV subtraction to compute
1481   // `PreStart` below.
1482   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1483   if (!StartC)
1484     return false;
1485 
1486   APInt StartAI = StartC->getAPInt();
1487 
1488   for (unsigned Delta : {-2, -1, 1, 2}) {
1489     const SCEV *PreStart = getConstant(StartAI - Delta);
1490 
1491     FoldingSetNodeID ID;
1492     ID.AddInteger(scAddRecExpr);
1493     ID.AddPointer(PreStart);
1494     ID.AddPointer(Step);
1495     ID.AddPointer(L);
1496     void *IP = nullptr;
1497     const auto *PreAR =
1498       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1499 
1500     // Give up if we don't already have the add recurrence we need because
1501     // actually constructing an add recurrence is relatively expensive.
1502     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1503       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1504       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1505       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1506           DeltaS, &Pred, this);
1507       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1508         return true;
1509     }
1510   }
1511 
1512   return false;
1513 }
1514 
1515 // Finds an integer D for an expression (C + x + y + ...) such that the top
1516 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1517 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1518 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1519 // the (C + x + y + ...) expression is \p WholeAddExpr.
1520 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1521                                             const SCEVConstant *ConstantTerm,
1522                                             const SCEVAddExpr *WholeAddExpr) {
1523   const APInt &C = ConstantTerm->getAPInt();
1524   const unsigned BitWidth = C.getBitWidth();
1525   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1526   uint32_t TZ = BitWidth;
1527   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1528     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1529   if (TZ) {
1530     // Set D to be as many least significant bits of C as possible while still
1531     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1532     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1533   }
1534   return APInt(BitWidth, 0);
1535 }
1536 
1537 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1538 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1539 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1540 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1541 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1542                                             const APInt &ConstantStart,
1543                                             const SCEV *Step) {
1544   const unsigned BitWidth = ConstantStart.getBitWidth();
1545   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1546   if (TZ)
1547     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1548                          : ConstantStart;
1549   return APInt(BitWidth, 0);
1550 }
1551 
1552 const SCEV *
1553 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1554   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1555          "This is not an extending conversion!");
1556   assert(isSCEVable(Ty) &&
1557          "This is not a conversion to a SCEVable type!");
1558   Ty = getEffectiveSCEVType(Ty);
1559 
1560   // Fold if the operand is constant.
1561   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1562     return getConstant(
1563       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1564 
1565   // zext(zext(x)) --> zext(x)
1566   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1567     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1568 
1569   // Before doing any expensive analysis, check to see if we've already
1570   // computed a SCEV for this Op and Ty.
1571   FoldingSetNodeID ID;
1572   ID.AddInteger(scZeroExtend);
1573   ID.AddPointer(Op);
1574   ID.AddPointer(Ty);
1575   void *IP = nullptr;
1576   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1577   if (Depth > MaxCastDepth) {
1578     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1579                                                      Op, Ty);
1580     UniqueSCEVs.InsertNode(S, IP);
1581     addToLoopUseLists(S);
1582     return S;
1583   }
1584 
1585   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1586   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1587     // It's possible the bits taken off by the truncate were all zero bits. If
1588     // so, we should be able to simplify this further.
1589     const SCEV *X = ST->getOperand();
1590     ConstantRange CR = getUnsignedRange(X);
1591     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1592     unsigned NewBits = getTypeSizeInBits(Ty);
1593     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1594             CR.zextOrTrunc(NewBits)))
1595       return getTruncateOrZeroExtend(X, Ty, Depth);
1596   }
1597 
1598   // If the input value is a chrec scev, and we can prove that the value
1599   // did not overflow the old, smaller, value, we can zero extend all of the
1600   // operands (often constants).  This allows analysis of something like
1601   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1602   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1603     if (AR->isAffine()) {
1604       const SCEV *Start = AR->getStart();
1605       const SCEV *Step = AR->getStepRecurrence(*this);
1606       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1607       const Loop *L = AR->getLoop();
1608 
1609       if (!AR->hasNoUnsignedWrap()) {
1610         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1611         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1612       }
1613 
1614       // If we have special knowledge that this addrec won't overflow,
1615       // we don't need to do any further analysis.
1616       if (AR->hasNoUnsignedWrap())
1617         return getAddRecExpr(
1618             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1619             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1620 
1621       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1622       // Note that this serves two purposes: It filters out loops that are
1623       // simply not analyzable, and it covers the case where this code is
1624       // being called from within backedge-taken count analysis, such that
1625       // attempting to ask for the backedge-taken count would likely result
1626       // in infinite recursion. In the later case, the analysis code will
1627       // cope with a conservative value, and it will take care to purge
1628       // that value once it has finished.
1629       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1630       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1631         // Manually compute the final value for AR, checking for overflow.
1632 
1633         // Check whether the backedge-taken count can be losslessly casted to
1634         // the addrec's type. The count is always unsigned.
1635         const SCEV *CastedMaxBECount =
1636             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1637         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1638             CastedMaxBECount, MaxBECount->getType(), Depth);
1639         if (MaxBECount == RecastedMaxBECount) {
1640           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1641           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1642           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1643                                         SCEV::FlagAnyWrap, Depth + 1);
1644           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1645                                                           SCEV::FlagAnyWrap,
1646                                                           Depth + 1),
1647                                                WideTy, Depth + 1);
1648           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1649           const SCEV *WideMaxBECount =
1650             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1651           const SCEV *OperandExtendedAdd =
1652             getAddExpr(WideStart,
1653                        getMulExpr(WideMaxBECount,
1654                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1655                                   SCEV::FlagAnyWrap, Depth + 1),
1656                        SCEV::FlagAnyWrap, Depth + 1);
1657           if (ZAdd == OperandExtendedAdd) {
1658             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1659             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1660             // Return the expression with the addrec on the outside.
1661             return getAddRecExpr(
1662                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1663                                                          Depth + 1),
1664                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1665                 AR->getNoWrapFlags());
1666           }
1667           // Similar to above, only this time treat the step value as signed.
1668           // This covers loops that count down.
1669           OperandExtendedAdd =
1670             getAddExpr(WideStart,
1671                        getMulExpr(WideMaxBECount,
1672                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1673                                   SCEV::FlagAnyWrap, Depth + 1),
1674                        SCEV::FlagAnyWrap, Depth + 1);
1675           if (ZAdd == OperandExtendedAdd) {
1676             // Cache knowledge of AR NW, which is propagated to this AddRec.
1677             // Negative step causes unsigned wrap, but it still can't self-wrap.
1678             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1679             // Return the expression with the addrec on the outside.
1680             return getAddRecExpr(
1681                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1682                                                          Depth + 1),
1683                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1684                 AR->getNoWrapFlags());
1685           }
1686         }
1687       }
1688 
1689       // Normally, in the cases we can prove no-overflow via a
1690       // backedge guarding condition, we can also compute a backedge
1691       // taken count for the loop.  The exceptions are assumptions and
1692       // guards present in the loop -- SCEV is not great at exploiting
1693       // these to compute max backedge taken counts, but can still use
1694       // these to prove lack of overflow.  Use this fact to avoid
1695       // doing extra work that may not pay off.
1696       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1697           !AC.assumptions().empty()) {
1698 
1699         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1700         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1701         if (AR->hasNoUnsignedWrap()) {
1702           // Same as nuw case above - duplicated here to avoid a compile time
1703           // issue.  It's not clear that the order of checks does matter, but
1704           // it's one of two issue possible causes for a change which was
1705           // reverted.  Be conservative for the moment.
1706           return getAddRecExpr(
1707                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1708                                                          Depth + 1),
1709                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1710                 AR->getNoWrapFlags());
1711         }
1712 
1713         // For a negative step, we can extend the operands iff doing so only
1714         // traverses values in the range zext([0,UINT_MAX]).
1715         if (isKnownNegative(Step)) {
1716           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1717                                       getSignedRangeMin(Step));
1718           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1719               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1720             // Cache knowledge of AR NW, which is propagated to this
1721             // AddRec.  Negative step causes unsigned wrap, but it
1722             // still can't self-wrap.
1723             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1724             // Return the expression with the addrec on the outside.
1725             return getAddRecExpr(
1726                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1727                                                          Depth + 1),
1728                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1729                 AR->getNoWrapFlags());
1730           }
1731         }
1732       }
1733 
1734       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1735       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1736       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1737       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1738         const APInt &C = SC->getAPInt();
1739         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1740         if (D != 0) {
1741           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1742           const SCEV *SResidual =
1743               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1744           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1745           return getAddExpr(SZExtD, SZExtR,
1746                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1747                             Depth + 1);
1748         }
1749       }
1750 
1751       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1752         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1753         return getAddRecExpr(
1754             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1755             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1756       }
1757     }
1758 
1759   // zext(A % B) --> zext(A) % zext(B)
1760   {
1761     const SCEV *LHS;
1762     const SCEV *RHS;
1763     if (matchURem(Op, LHS, RHS))
1764       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1765                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1766   }
1767 
1768   // zext(A / B) --> zext(A) / zext(B).
1769   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1770     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1771                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1772 
1773   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1774     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1775     if (SA->hasNoUnsignedWrap()) {
1776       // If the addition does not unsign overflow then we can, by definition,
1777       // commute the zero extension with the addition operation.
1778       SmallVector<const SCEV *, 4> Ops;
1779       for (const auto *Op : SA->operands())
1780         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1781       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1782     }
1783 
1784     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1785     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1786     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1787     //
1788     // Often address arithmetics contain expressions like
1789     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1790     // This transformation is useful while proving that such expressions are
1791     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1792     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1793       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1794       if (D != 0) {
1795         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1796         const SCEV *SResidual =
1797             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1798         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1799         return getAddExpr(SZExtD, SZExtR,
1800                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1801                           Depth + 1);
1802       }
1803     }
1804   }
1805 
1806   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1807     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1808     if (SM->hasNoUnsignedWrap()) {
1809       // If the multiply does not unsign overflow then we can, by definition,
1810       // commute the zero extension with the multiply operation.
1811       SmallVector<const SCEV *, 4> Ops;
1812       for (const auto *Op : SM->operands())
1813         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1814       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1815     }
1816 
1817     // zext(2^K * (trunc X to iN)) to iM ->
1818     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1819     //
1820     // Proof:
1821     //
1822     //     zext(2^K * (trunc X to iN)) to iM
1823     //   = zext((trunc X to iN) << K) to iM
1824     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1825     //     (because shl removes the top K bits)
1826     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1827     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1828     //
1829     if (SM->getNumOperands() == 2)
1830       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1831         if (MulLHS->getAPInt().isPowerOf2())
1832           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1833             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1834                                MulLHS->getAPInt().logBase2();
1835             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1836             return getMulExpr(
1837                 getZeroExtendExpr(MulLHS, Ty),
1838                 getZeroExtendExpr(
1839                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1840                 SCEV::FlagNUW, Depth + 1);
1841           }
1842   }
1843 
1844   // The cast wasn't folded; create an explicit cast node.
1845   // Recompute the insert position, as it may have been invalidated.
1846   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1847   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1848                                                    Op, Ty);
1849   UniqueSCEVs.InsertNode(S, IP);
1850   addToLoopUseLists(S);
1851   return S;
1852 }
1853 
1854 const SCEV *
1855 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1856   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1857          "This is not an extending conversion!");
1858   assert(isSCEVable(Ty) &&
1859          "This is not a conversion to a SCEVable type!");
1860   Ty = getEffectiveSCEVType(Ty);
1861 
1862   // Fold if the operand is constant.
1863   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1864     return getConstant(
1865       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1866 
1867   // sext(sext(x)) --> sext(x)
1868   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1869     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1870 
1871   // sext(zext(x)) --> zext(x)
1872   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1873     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1874 
1875   // Before doing any expensive analysis, check to see if we've already
1876   // computed a SCEV for this Op and Ty.
1877   FoldingSetNodeID ID;
1878   ID.AddInteger(scSignExtend);
1879   ID.AddPointer(Op);
1880   ID.AddPointer(Ty);
1881   void *IP = nullptr;
1882   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1883   // Limit recursion depth.
1884   if (Depth > MaxCastDepth) {
1885     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1886                                                      Op, Ty);
1887     UniqueSCEVs.InsertNode(S, IP);
1888     addToLoopUseLists(S);
1889     return S;
1890   }
1891 
1892   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1893   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1894     // It's possible the bits taken off by the truncate were all sign bits. If
1895     // so, we should be able to simplify this further.
1896     const SCEV *X = ST->getOperand();
1897     ConstantRange CR = getSignedRange(X);
1898     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1899     unsigned NewBits = getTypeSizeInBits(Ty);
1900     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1901             CR.sextOrTrunc(NewBits)))
1902       return getTruncateOrSignExtend(X, Ty, Depth);
1903   }
1904 
1905   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1906     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1907     if (SA->hasNoSignedWrap()) {
1908       // If the addition does not sign overflow then we can, by definition,
1909       // commute the sign extension with the addition operation.
1910       SmallVector<const SCEV *, 4> Ops;
1911       for (const auto *Op : SA->operands())
1912         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1913       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1914     }
1915 
1916     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1917     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1918     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1919     //
1920     // For instance, this will bring two seemingly different expressions:
1921     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1922     //         sext(6 + 20 * %x + 24 * %y)
1923     // to the same form:
1924     //     2 + sext(4 + 20 * %x + 24 * %y)
1925     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1926       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1927       if (D != 0) {
1928         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1929         const SCEV *SResidual =
1930             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1931         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1932         return getAddExpr(SSExtD, SSExtR,
1933                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1934                           Depth + 1);
1935       }
1936     }
1937   }
1938   // If the input value is a chrec scev, and we can prove that the value
1939   // did not overflow the old, smaller, value, we can sign extend all of the
1940   // operands (often constants).  This allows analysis of something like
1941   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1942   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1943     if (AR->isAffine()) {
1944       const SCEV *Start = AR->getStart();
1945       const SCEV *Step = AR->getStepRecurrence(*this);
1946       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1947       const Loop *L = AR->getLoop();
1948 
1949       if (!AR->hasNoSignedWrap()) {
1950         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1951         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1952       }
1953 
1954       // If we have special knowledge that this addrec won't overflow,
1955       // we don't need to do any further analysis.
1956       if (AR->hasNoSignedWrap())
1957         return getAddRecExpr(
1958             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1959             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1960 
1961       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1962       // Note that this serves two purposes: It filters out loops that are
1963       // simply not analyzable, and it covers the case where this code is
1964       // being called from within backedge-taken count analysis, such that
1965       // attempting to ask for the backedge-taken count would likely result
1966       // in infinite recursion. In the later case, the analysis code will
1967       // cope with a conservative value, and it will take care to purge
1968       // that value once it has finished.
1969       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1970       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1971         // Manually compute the final value for AR, checking for
1972         // overflow.
1973 
1974         // Check whether the backedge-taken count can be losslessly casted to
1975         // the addrec's type. The count is always unsigned.
1976         const SCEV *CastedMaxBECount =
1977             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1978         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1979             CastedMaxBECount, MaxBECount->getType(), Depth);
1980         if (MaxBECount == RecastedMaxBECount) {
1981           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1982           // Check whether Start+Step*MaxBECount has no signed overflow.
1983           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1984                                         SCEV::FlagAnyWrap, Depth + 1);
1985           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1986                                                           SCEV::FlagAnyWrap,
1987                                                           Depth + 1),
1988                                                WideTy, Depth + 1);
1989           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1990           const SCEV *WideMaxBECount =
1991             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1992           const SCEV *OperandExtendedAdd =
1993             getAddExpr(WideStart,
1994                        getMulExpr(WideMaxBECount,
1995                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1996                                   SCEV::FlagAnyWrap, Depth + 1),
1997                        SCEV::FlagAnyWrap, Depth + 1);
1998           if (SAdd == OperandExtendedAdd) {
1999             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2000             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2001             // Return the expression with the addrec on the outside.
2002             return getAddRecExpr(
2003                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2004                                                          Depth + 1),
2005                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2006                 AR->getNoWrapFlags());
2007           }
2008           // Similar to above, only this time treat the step value as unsigned.
2009           // This covers loops that count up with an unsigned step.
2010           OperandExtendedAdd =
2011             getAddExpr(WideStart,
2012                        getMulExpr(WideMaxBECount,
2013                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2014                                   SCEV::FlagAnyWrap, Depth + 1),
2015                        SCEV::FlagAnyWrap, Depth + 1);
2016           if (SAdd == OperandExtendedAdd) {
2017             // If AR wraps around then
2018             //
2019             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2020             // => SAdd != OperandExtendedAdd
2021             //
2022             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2023             // (SAdd == OperandExtendedAdd => AR is NW)
2024 
2025             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2026 
2027             // Return the expression with the addrec on the outside.
2028             return getAddRecExpr(
2029                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2030                                                          Depth + 1),
2031                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2032                 AR->getNoWrapFlags());
2033           }
2034         }
2035       }
2036 
2037       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2038       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2039       if (AR->hasNoSignedWrap()) {
2040         // Same as nsw case above - duplicated here to avoid a compile time
2041         // issue.  It's not clear that the order of checks does matter, but
2042         // it's one of two issue possible causes for a change which was
2043         // reverted.  Be conservative for the moment.
2044         return getAddRecExpr(
2045             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2046             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2047       }
2048 
2049       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2050       // if D + (C - D + Step * n) could be proven to not signed wrap
2051       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2052       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2053         const APInt &C = SC->getAPInt();
2054         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2055         if (D != 0) {
2056           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2057           const SCEV *SResidual =
2058               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2059           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2060           return getAddExpr(SSExtD, SSExtR,
2061                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2062                             Depth + 1);
2063         }
2064       }
2065 
2066       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2067         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2068         return getAddRecExpr(
2069             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2070             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2071       }
2072     }
2073 
2074   // If the input value is provably positive and we could not simplify
2075   // away the sext build a zext instead.
2076   if (isKnownNonNegative(Op))
2077     return getZeroExtendExpr(Op, Ty, Depth + 1);
2078 
2079   // The cast wasn't folded; create an explicit cast node.
2080   // Recompute the insert position, as it may have been invalidated.
2081   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2082   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2083                                                    Op, Ty);
2084   UniqueSCEVs.InsertNode(S, IP);
2085   addToLoopUseLists(S);
2086   return S;
2087 }
2088 
2089 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2090 /// unspecified bits out to the given type.
2091 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2092                                               Type *Ty) {
2093   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2094          "This is not an extending conversion!");
2095   assert(isSCEVable(Ty) &&
2096          "This is not a conversion to a SCEVable type!");
2097   Ty = getEffectiveSCEVType(Ty);
2098 
2099   // Sign-extend negative constants.
2100   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2101     if (SC->getAPInt().isNegative())
2102       return getSignExtendExpr(Op, Ty);
2103 
2104   // Peel off a truncate cast.
2105   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2106     const SCEV *NewOp = T->getOperand();
2107     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2108       return getAnyExtendExpr(NewOp, Ty);
2109     return getTruncateOrNoop(NewOp, Ty);
2110   }
2111 
2112   // Next try a zext cast. If the cast is folded, use it.
2113   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2114   if (!isa<SCEVZeroExtendExpr>(ZExt))
2115     return ZExt;
2116 
2117   // Next try a sext cast. If the cast is folded, use it.
2118   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2119   if (!isa<SCEVSignExtendExpr>(SExt))
2120     return SExt;
2121 
2122   // Force the cast to be folded into the operands of an addrec.
2123   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2124     SmallVector<const SCEV *, 4> Ops;
2125     for (const SCEV *Op : AR->operands())
2126       Ops.push_back(getAnyExtendExpr(Op, Ty));
2127     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2128   }
2129 
2130   // If the expression is obviously signed, use the sext cast value.
2131   if (isa<SCEVSMaxExpr>(Op))
2132     return SExt;
2133 
2134   // Absent any other information, use the zext cast value.
2135   return ZExt;
2136 }
2137 
2138 /// Process the given Ops list, which is a list of operands to be added under
2139 /// the given scale, update the given map. This is a helper function for
2140 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2141 /// that would form an add expression like this:
2142 ///
2143 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2144 ///
2145 /// where A and B are constants, update the map with these values:
2146 ///
2147 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2148 ///
2149 /// and add 13 + A*B*29 to AccumulatedConstant.
2150 /// This will allow getAddRecExpr to produce this:
2151 ///
2152 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2153 ///
2154 /// This form often exposes folding opportunities that are hidden in
2155 /// the original operand list.
2156 ///
2157 /// Return true iff it appears that any interesting folding opportunities
2158 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2159 /// the common case where no interesting opportunities are present, and
2160 /// is also used as a check to avoid infinite recursion.
2161 static bool
2162 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2163                              SmallVectorImpl<const SCEV *> &NewOps,
2164                              APInt &AccumulatedConstant,
2165                              const SCEV *const *Ops, size_t NumOperands,
2166                              const APInt &Scale,
2167                              ScalarEvolution &SE) {
2168   bool Interesting = false;
2169 
2170   // Iterate over the add operands. They are sorted, with constants first.
2171   unsigned i = 0;
2172   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2173     ++i;
2174     // Pull a buried constant out to the outside.
2175     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2176       Interesting = true;
2177     AccumulatedConstant += Scale * C->getAPInt();
2178   }
2179 
2180   // Next comes everything else. We're especially interested in multiplies
2181   // here, but they're in the middle, so just visit the rest with one loop.
2182   for (; i != NumOperands; ++i) {
2183     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2184     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2185       APInt NewScale =
2186           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2187       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2188         // A multiplication of a constant with another add; recurse.
2189         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2190         Interesting |=
2191           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2192                                        Add->op_begin(), Add->getNumOperands(),
2193                                        NewScale, SE);
2194       } else {
2195         // A multiplication of a constant with some other value. Update
2196         // the map.
2197         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2198         const SCEV *Key = SE.getMulExpr(MulOps);
2199         auto Pair = M.insert({Key, NewScale});
2200         if (Pair.second) {
2201           NewOps.push_back(Pair.first->first);
2202         } else {
2203           Pair.first->second += NewScale;
2204           // The map already had an entry for this value, which may indicate
2205           // a folding opportunity.
2206           Interesting = true;
2207         }
2208       }
2209     } else {
2210       // An ordinary operand. Update the map.
2211       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2212           M.insert({Ops[i], Scale});
2213       if (Pair.second) {
2214         NewOps.push_back(Pair.first->first);
2215       } else {
2216         Pair.first->second += Scale;
2217         // The map already had an entry for this value, which may indicate
2218         // a folding opportunity.
2219         Interesting = true;
2220       }
2221     }
2222   }
2223 
2224   return Interesting;
2225 }
2226 
2227 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2228 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2229 // can't-overflow flags for the operation if possible.
2230 static SCEV::NoWrapFlags
2231 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2232                       const ArrayRef<const SCEV *> Ops,
2233                       SCEV::NoWrapFlags Flags) {
2234   using namespace std::placeholders;
2235 
2236   using OBO = OverflowingBinaryOperator;
2237 
2238   bool CanAnalyze =
2239       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2240   (void)CanAnalyze;
2241   assert(CanAnalyze && "don't call from other places!");
2242 
2243   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2244   SCEV::NoWrapFlags SignOrUnsignWrap =
2245       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2246 
2247   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2248   auto IsKnownNonNegative = [&](const SCEV *S) {
2249     return SE->isKnownNonNegative(S);
2250   };
2251 
2252   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2253     Flags =
2254         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2255 
2256   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2257 
2258   if (SignOrUnsignWrap != SignOrUnsignMask &&
2259       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2260       isa<SCEVConstant>(Ops[0])) {
2261 
2262     auto Opcode = [&] {
2263       switch (Type) {
2264       case scAddExpr:
2265         return Instruction::Add;
2266       case scMulExpr:
2267         return Instruction::Mul;
2268       default:
2269         llvm_unreachable("Unexpected SCEV op.");
2270       }
2271     }();
2272 
2273     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2274 
2275     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2276     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2277       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2278           Opcode, C, OBO::NoSignedWrap);
2279       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2280         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2281     }
2282 
2283     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2284     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2285       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2286           Opcode, C, OBO::NoUnsignedWrap);
2287       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2288         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2289     }
2290   }
2291 
2292   return Flags;
2293 }
2294 
2295 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2296   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2297 }
2298 
2299 /// Get a canonical add expression, or something simpler if possible.
2300 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2301                                         SCEV::NoWrapFlags OrigFlags,
2302                                         unsigned Depth) {
2303   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2304          "only nuw or nsw allowed");
2305   assert(!Ops.empty() && "Cannot get empty add!");
2306   if (Ops.size() == 1) return Ops[0];
2307 #ifndef NDEBUG
2308   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2309   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2310     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2311            "SCEVAddExpr operand types don't match!");
2312 #endif
2313 
2314   // Sort by complexity, this groups all similar expression types together.
2315   GroupByComplexity(Ops, &LI, DT);
2316 
2317   // If there are any constants, fold them together.
2318   unsigned Idx = 0;
2319   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2320     ++Idx;
2321     assert(Idx < Ops.size());
2322     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2323       // We found two constants, fold them together!
2324       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2325       if (Ops.size() == 2) return Ops[0];
2326       Ops.erase(Ops.begin()+1);  // Erase the folded element
2327       LHSC = cast<SCEVConstant>(Ops[0]);
2328     }
2329 
2330     // If we are left with a constant zero being added, strip it off.
2331     if (LHSC->getValue()->isZero()) {
2332       Ops.erase(Ops.begin());
2333       --Idx;
2334     }
2335 
2336     if (Ops.size() == 1) return Ops[0];
2337   }
2338 
2339   // Delay expensive flag strengthening until necessary.
2340   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2341     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2342   };
2343 
2344   // Limit recursion calls depth.
2345   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2346     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2347 
2348   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2349     // Don't strengthen flags if we have no new information.
2350     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2351     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2352       Add->setNoWrapFlags(ComputeFlags(Ops));
2353     return S;
2354   }
2355 
2356   // Okay, check to see if the same value occurs in the operand list more than
2357   // once.  If so, merge them together into an multiply expression.  Since we
2358   // sorted the list, these values are required to be adjacent.
2359   Type *Ty = Ops[0]->getType();
2360   bool FoundMatch = false;
2361   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2362     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2363       // Scan ahead to count how many equal operands there are.
2364       unsigned Count = 2;
2365       while (i+Count != e && Ops[i+Count] == Ops[i])
2366         ++Count;
2367       // Merge the values into a multiply.
2368       const SCEV *Scale = getConstant(Ty, Count);
2369       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2370       if (Ops.size() == Count)
2371         return Mul;
2372       Ops[i] = Mul;
2373       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2374       --i; e -= Count - 1;
2375       FoundMatch = true;
2376     }
2377   if (FoundMatch)
2378     return getAddExpr(Ops, OrigFlags, Depth + 1);
2379 
2380   // Check for truncates. If all the operands are truncated from the same
2381   // type, see if factoring out the truncate would permit the result to be
2382   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2383   // if the contents of the resulting outer trunc fold to something simple.
2384   auto FindTruncSrcType = [&]() -> Type * {
2385     // We're ultimately looking to fold an addrec of truncs and muls of only
2386     // constants and truncs, so if we find any other types of SCEV
2387     // as operands of the addrec then we bail and return nullptr here.
2388     // Otherwise, we return the type of the operand of a trunc that we find.
2389     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2390       return T->getOperand()->getType();
2391     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2392       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2393       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2394         return T->getOperand()->getType();
2395     }
2396     return nullptr;
2397   };
2398   if (auto *SrcType = FindTruncSrcType()) {
2399     SmallVector<const SCEV *, 8> LargeOps;
2400     bool Ok = true;
2401     // Check all the operands to see if they can be represented in the
2402     // source type of the truncate.
2403     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2404       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2405         if (T->getOperand()->getType() != SrcType) {
2406           Ok = false;
2407           break;
2408         }
2409         LargeOps.push_back(T->getOperand());
2410       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2411         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2412       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2413         SmallVector<const SCEV *, 8> LargeMulOps;
2414         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2415           if (const SCEVTruncateExpr *T =
2416                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2417             if (T->getOperand()->getType() != SrcType) {
2418               Ok = false;
2419               break;
2420             }
2421             LargeMulOps.push_back(T->getOperand());
2422           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2423             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2424           } else {
2425             Ok = false;
2426             break;
2427           }
2428         }
2429         if (Ok)
2430           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2431       } else {
2432         Ok = false;
2433         break;
2434       }
2435     }
2436     if (Ok) {
2437       // Evaluate the expression in the larger type.
2438       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2439       // If it folds to something simple, use it. Otherwise, don't.
2440       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2441         return getTruncateExpr(Fold, Ty);
2442     }
2443   }
2444 
2445   // Skip past any other cast SCEVs.
2446   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2447     ++Idx;
2448 
2449   // If there are add operands they would be next.
2450   if (Idx < Ops.size()) {
2451     bool DeletedAdd = false;
2452     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2453       if (Ops.size() > AddOpsInlineThreshold ||
2454           Add->getNumOperands() > AddOpsInlineThreshold)
2455         break;
2456       // If we have an add, expand the add operands onto the end of the operands
2457       // list.
2458       Ops.erase(Ops.begin()+Idx);
2459       Ops.append(Add->op_begin(), Add->op_end());
2460       DeletedAdd = true;
2461     }
2462 
2463     // If we deleted at least one add, we added operands to the end of the list,
2464     // and they are not necessarily sorted.  Recurse to resort and resimplify
2465     // any operands we just acquired.
2466     if (DeletedAdd)
2467       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2468   }
2469 
2470   // Skip over the add expression until we get to a multiply.
2471   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2472     ++Idx;
2473 
2474   // Check to see if there are any folding opportunities present with
2475   // operands multiplied by constant values.
2476   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2477     uint64_t BitWidth = getTypeSizeInBits(Ty);
2478     DenseMap<const SCEV *, APInt> M;
2479     SmallVector<const SCEV *, 8> NewOps;
2480     APInt AccumulatedConstant(BitWidth, 0);
2481     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2482                                      Ops.data(), Ops.size(),
2483                                      APInt(BitWidth, 1), *this)) {
2484       struct APIntCompare {
2485         bool operator()(const APInt &LHS, const APInt &RHS) const {
2486           return LHS.ult(RHS);
2487         }
2488       };
2489 
2490       // Some interesting folding opportunity is present, so its worthwhile to
2491       // re-generate the operands list. Group the operands by constant scale,
2492       // to avoid multiplying by the same constant scale multiple times.
2493       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2494       for (const SCEV *NewOp : NewOps)
2495         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2496       // Re-generate the operands list.
2497       Ops.clear();
2498       if (AccumulatedConstant != 0)
2499         Ops.push_back(getConstant(AccumulatedConstant));
2500       for (auto &MulOp : MulOpLists)
2501         if (MulOp.first != 0)
2502           Ops.push_back(getMulExpr(
2503               getConstant(MulOp.first),
2504               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2505               SCEV::FlagAnyWrap, Depth + 1));
2506       if (Ops.empty())
2507         return getZero(Ty);
2508       if (Ops.size() == 1)
2509         return Ops[0];
2510       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2511     }
2512   }
2513 
2514   // If we are adding something to a multiply expression, make sure the
2515   // something is not already an operand of the multiply.  If so, merge it into
2516   // the multiply.
2517   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2518     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2519     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2520       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2521       if (isa<SCEVConstant>(MulOpSCEV))
2522         continue;
2523       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2524         if (MulOpSCEV == Ops[AddOp]) {
2525           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2526           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2527           if (Mul->getNumOperands() != 2) {
2528             // If the multiply has more than two operands, we must get the
2529             // Y*Z term.
2530             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2531                                                 Mul->op_begin()+MulOp);
2532             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2533             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2534           }
2535           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2536           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2537           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2538                                             SCEV::FlagAnyWrap, Depth + 1);
2539           if (Ops.size() == 2) return OuterMul;
2540           if (AddOp < Idx) {
2541             Ops.erase(Ops.begin()+AddOp);
2542             Ops.erase(Ops.begin()+Idx-1);
2543           } else {
2544             Ops.erase(Ops.begin()+Idx);
2545             Ops.erase(Ops.begin()+AddOp-1);
2546           }
2547           Ops.push_back(OuterMul);
2548           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2549         }
2550 
2551       // Check this multiply against other multiplies being added together.
2552       for (unsigned OtherMulIdx = Idx+1;
2553            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2554            ++OtherMulIdx) {
2555         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2556         // If MulOp occurs in OtherMul, we can fold the two multiplies
2557         // together.
2558         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2559              OMulOp != e; ++OMulOp)
2560           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2561             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2562             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2563             if (Mul->getNumOperands() != 2) {
2564               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2565                                                   Mul->op_begin()+MulOp);
2566               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2567               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2568             }
2569             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2570             if (OtherMul->getNumOperands() != 2) {
2571               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2572                                                   OtherMul->op_begin()+OMulOp);
2573               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2574               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2575             }
2576             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2577             const SCEV *InnerMulSum =
2578                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2579             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2580                                               SCEV::FlagAnyWrap, Depth + 1);
2581             if (Ops.size() == 2) return OuterMul;
2582             Ops.erase(Ops.begin()+Idx);
2583             Ops.erase(Ops.begin()+OtherMulIdx-1);
2584             Ops.push_back(OuterMul);
2585             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2586           }
2587       }
2588     }
2589   }
2590 
2591   // If there are any add recurrences in the operands list, see if any other
2592   // added values are loop invariant.  If so, we can fold them into the
2593   // recurrence.
2594   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2595     ++Idx;
2596 
2597   // Scan over all recurrences, trying to fold loop invariants into them.
2598   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2599     // Scan all of the other operands to this add and add them to the vector if
2600     // they are loop invariant w.r.t. the recurrence.
2601     SmallVector<const SCEV *, 8> LIOps;
2602     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2603     const Loop *AddRecLoop = AddRec->getLoop();
2604     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2605       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2606         LIOps.push_back(Ops[i]);
2607         Ops.erase(Ops.begin()+i);
2608         --i; --e;
2609       }
2610 
2611     // If we found some loop invariants, fold them into the recurrence.
2612     if (!LIOps.empty()) {
2613       // Compute nowrap flags for the addition of the loop-invariant ops and
2614       // the addrec. Temporarily push it as an operand for that purpose.
2615       LIOps.push_back(AddRec);
2616       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2617       LIOps.pop_back();
2618 
2619       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2620       LIOps.push_back(AddRec->getStart());
2621 
2622       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2623       // This follows from the fact that the no-wrap flags on the outer add
2624       // expression are applicable on the 0th iteration, when the add recurrence
2625       // will be equal to its start value.
2626       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2627 
2628       // Build the new addrec. Propagate the NUW and NSW flags if both the
2629       // outer add and the inner addrec are guaranteed to have no overflow.
2630       // Always propagate NW.
2631       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2632       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2633 
2634       // If all of the other operands were loop invariant, we are done.
2635       if (Ops.size() == 1) return NewRec;
2636 
2637       // Otherwise, add the folded AddRec by the non-invariant parts.
2638       for (unsigned i = 0;; ++i)
2639         if (Ops[i] == AddRec) {
2640           Ops[i] = NewRec;
2641           break;
2642         }
2643       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2644     }
2645 
2646     // Okay, if there weren't any loop invariants to be folded, check to see if
2647     // there are multiple AddRec's with the same loop induction variable being
2648     // added together.  If so, we can fold them.
2649     for (unsigned OtherIdx = Idx+1;
2650          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2651          ++OtherIdx) {
2652       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2653       // so that the 1st found AddRecExpr is dominated by all others.
2654       assert(DT.dominates(
2655            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2656            AddRec->getLoop()->getHeader()) &&
2657         "AddRecExprs are not sorted in reverse dominance order?");
2658       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2659         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2660         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2661         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2662              ++OtherIdx) {
2663           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2664           if (OtherAddRec->getLoop() == AddRecLoop) {
2665             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2666                  i != e; ++i) {
2667               if (i >= AddRecOps.size()) {
2668                 AddRecOps.append(OtherAddRec->op_begin()+i,
2669                                  OtherAddRec->op_end());
2670                 break;
2671               }
2672               SmallVector<const SCEV *, 2> TwoOps = {
2673                   AddRecOps[i], OtherAddRec->getOperand(i)};
2674               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2675             }
2676             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2677           }
2678         }
2679         // Step size has changed, so we cannot guarantee no self-wraparound.
2680         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2681         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2682       }
2683     }
2684 
2685     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2686     // next one.
2687   }
2688 
2689   // Okay, it looks like we really DO need an add expr.  Check to see if we
2690   // already have one, otherwise create a new one.
2691   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2692 }
2693 
2694 const SCEV *
2695 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2696                                     SCEV::NoWrapFlags Flags) {
2697   FoldingSetNodeID ID;
2698   ID.AddInteger(scAddExpr);
2699   for (const SCEV *Op : Ops)
2700     ID.AddPointer(Op);
2701   void *IP = nullptr;
2702   SCEVAddExpr *S =
2703       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2704   if (!S) {
2705     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2706     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2707     S = new (SCEVAllocator)
2708         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2709     UniqueSCEVs.InsertNode(S, IP);
2710     addToLoopUseLists(S);
2711   }
2712   S->setNoWrapFlags(Flags);
2713   return S;
2714 }
2715 
2716 const SCEV *
2717 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2718                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2719   FoldingSetNodeID ID;
2720   ID.AddInteger(scAddRecExpr);
2721   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2722     ID.AddPointer(Ops[i]);
2723   ID.AddPointer(L);
2724   void *IP = nullptr;
2725   SCEVAddRecExpr *S =
2726       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2727   if (!S) {
2728     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2729     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2730     S = new (SCEVAllocator)
2731         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2732     UniqueSCEVs.InsertNode(S, IP);
2733     addToLoopUseLists(S);
2734   }
2735   setNoWrapFlags(S, Flags);
2736   return S;
2737 }
2738 
2739 const SCEV *
2740 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2741                                     SCEV::NoWrapFlags Flags) {
2742   FoldingSetNodeID ID;
2743   ID.AddInteger(scMulExpr);
2744   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2745     ID.AddPointer(Ops[i]);
2746   void *IP = nullptr;
2747   SCEVMulExpr *S =
2748     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2749   if (!S) {
2750     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2751     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2752     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2753                                         O, Ops.size());
2754     UniqueSCEVs.InsertNode(S, IP);
2755     addToLoopUseLists(S);
2756   }
2757   S->setNoWrapFlags(Flags);
2758   return S;
2759 }
2760 
2761 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2762   uint64_t k = i*j;
2763   if (j > 1 && k / j != i) Overflow = true;
2764   return k;
2765 }
2766 
2767 /// Compute the result of "n choose k", the binomial coefficient.  If an
2768 /// intermediate computation overflows, Overflow will be set and the return will
2769 /// be garbage. Overflow is not cleared on absence of overflow.
2770 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2771   // We use the multiplicative formula:
2772   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2773   // At each iteration, we take the n-th term of the numeral and divide by the
2774   // (k-n)th term of the denominator.  This division will always produce an
2775   // integral result, and helps reduce the chance of overflow in the
2776   // intermediate computations. However, we can still overflow even when the
2777   // final result would fit.
2778 
2779   if (n == 0 || n == k) return 1;
2780   if (k > n) return 0;
2781 
2782   if (k > n/2)
2783     k = n-k;
2784 
2785   uint64_t r = 1;
2786   for (uint64_t i = 1; i <= k; ++i) {
2787     r = umul_ov(r, n-(i-1), Overflow);
2788     r /= i;
2789   }
2790   return r;
2791 }
2792 
2793 /// Determine if any of the operands in this SCEV are a constant or if
2794 /// any of the add or multiply expressions in this SCEV contain a constant.
2795 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2796   struct FindConstantInAddMulChain {
2797     bool FoundConstant = false;
2798 
2799     bool follow(const SCEV *S) {
2800       FoundConstant |= isa<SCEVConstant>(S);
2801       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2802     }
2803 
2804     bool isDone() const {
2805       return FoundConstant;
2806     }
2807   };
2808 
2809   FindConstantInAddMulChain F;
2810   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2811   ST.visitAll(StartExpr);
2812   return F.FoundConstant;
2813 }
2814 
2815 /// Get a canonical multiply expression, or something simpler if possible.
2816 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2817                                         SCEV::NoWrapFlags OrigFlags,
2818                                         unsigned Depth) {
2819   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2820          "only nuw or nsw allowed");
2821   assert(!Ops.empty() && "Cannot get empty mul!");
2822   if (Ops.size() == 1) return Ops[0];
2823 #ifndef NDEBUG
2824   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2825   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2826     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2827            "SCEVMulExpr operand types don't match!");
2828 #endif
2829 
2830   // Sort by complexity, this groups all similar expression types together.
2831   GroupByComplexity(Ops, &LI, DT);
2832 
2833   // If there are any constants, fold them together.
2834   unsigned Idx = 0;
2835   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2836     ++Idx;
2837     assert(Idx < Ops.size());
2838     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2839       // We found two constants, fold them together!
2840       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2841       if (Ops.size() == 2) return Ops[0];
2842       Ops.erase(Ops.begin()+1);  // Erase the folded element
2843       LHSC = cast<SCEVConstant>(Ops[0]);
2844     }
2845 
2846     // If we have a multiply of zero, it will always be zero.
2847     if (LHSC->getValue()->isZero())
2848       return LHSC;
2849 
2850     // If we are left with a constant one being multiplied, strip it off.
2851     if (LHSC->getValue()->isOne()) {
2852       Ops.erase(Ops.begin());
2853       --Idx;
2854     }
2855 
2856     if (Ops.size() == 1)
2857       return Ops[0];
2858   }
2859 
2860   // Delay expensive flag strengthening until necessary.
2861   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2862     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2863   };
2864 
2865   // Limit recursion calls depth.
2866   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2867     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2868 
2869   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2870     // Don't strengthen flags if we have no new information.
2871     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2872     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2873       Mul->setNoWrapFlags(ComputeFlags(Ops));
2874     return S;
2875   }
2876 
2877   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2878     if (Ops.size() == 2) {
2879       // C1*(C2+V) -> C1*C2 + C1*V
2880       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2881         // If any of Add's ops are Adds or Muls with a constant, apply this
2882         // transformation as well.
2883         //
2884         // TODO: There are some cases where this transformation is not
2885         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2886         // this transformation should be narrowed down.
2887         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2888           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2889                                        SCEV::FlagAnyWrap, Depth + 1),
2890                             getMulExpr(LHSC, Add->getOperand(1),
2891                                        SCEV::FlagAnyWrap, Depth + 1),
2892                             SCEV::FlagAnyWrap, Depth + 1);
2893 
2894       if (Ops[0]->isAllOnesValue()) {
2895         // If we have a mul by -1 of an add, try distributing the -1 among the
2896         // add operands.
2897         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2898           SmallVector<const SCEV *, 4> NewOps;
2899           bool AnyFolded = false;
2900           for (const SCEV *AddOp : Add->operands()) {
2901             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2902                                          Depth + 1);
2903             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2904             NewOps.push_back(Mul);
2905           }
2906           if (AnyFolded)
2907             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2908         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2909           // Negation preserves a recurrence's no self-wrap property.
2910           SmallVector<const SCEV *, 4> Operands;
2911           for (const SCEV *AddRecOp : AddRec->operands())
2912             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2913                                           Depth + 1));
2914 
2915           return getAddRecExpr(Operands, AddRec->getLoop(),
2916                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2917         }
2918       }
2919     }
2920   }
2921 
2922   // Skip over the add expression until we get to a multiply.
2923   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2924     ++Idx;
2925 
2926   // If there are mul operands inline them all into this expression.
2927   if (Idx < Ops.size()) {
2928     bool DeletedMul = false;
2929     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2930       if (Ops.size() > MulOpsInlineThreshold)
2931         break;
2932       // If we have an mul, expand the mul operands onto the end of the
2933       // operands list.
2934       Ops.erase(Ops.begin()+Idx);
2935       Ops.append(Mul->op_begin(), Mul->op_end());
2936       DeletedMul = true;
2937     }
2938 
2939     // If we deleted at least one mul, we added operands to the end of the
2940     // list, and they are not necessarily sorted.  Recurse to resort and
2941     // resimplify any operands we just acquired.
2942     if (DeletedMul)
2943       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2944   }
2945 
2946   // If there are any add recurrences in the operands list, see if any other
2947   // added values are loop invariant.  If so, we can fold them into the
2948   // recurrence.
2949   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2950     ++Idx;
2951 
2952   // Scan over all recurrences, trying to fold loop invariants into them.
2953   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2954     // Scan all of the other operands to this mul and add them to the vector
2955     // if they are loop invariant w.r.t. the recurrence.
2956     SmallVector<const SCEV *, 8> LIOps;
2957     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2958     const Loop *AddRecLoop = AddRec->getLoop();
2959     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2960       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2961         LIOps.push_back(Ops[i]);
2962         Ops.erase(Ops.begin()+i);
2963         --i; --e;
2964       }
2965 
2966     // If we found some loop invariants, fold them into the recurrence.
2967     if (!LIOps.empty()) {
2968       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2969       SmallVector<const SCEV *, 4> NewOps;
2970       NewOps.reserve(AddRec->getNumOperands());
2971       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2972       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2973         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2974                                     SCEV::FlagAnyWrap, Depth + 1));
2975 
2976       // Build the new addrec. Propagate the NUW and NSW flags if both the
2977       // outer mul and the inner addrec are guaranteed to have no overflow.
2978       //
2979       // No self-wrap cannot be guaranteed after changing the step size, but
2980       // will be inferred if either NUW or NSW is true.
2981       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2982       const SCEV *NewRec = getAddRecExpr(
2983           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2984 
2985       // If all of the other operands were loop invariant, we are done.
2986       if (Ops.size() == 1) return NewRec;
2987 
2988       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2989       for (unsigned i = 0;; ++i)
2990         if (Ops[i] == AddRec) {
2991           Ops[i] = NewRec;
2992           break;
2993         }
2994       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2995     }
2996 
2997     // Okay, if there weren't any loop invariants to be folded, check to see
2998     // if there are multiple AddRec's with the same loop induction variable
2999     // being multiplied together.  If so, we can fold them.
3000 
3001     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3002     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3003     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3004     //   ]]],+,...up to x=2n}.
3005     // Note that the arguments to choose() are always integers with values
3006     // known at compile time, never SCEV objects.
3007     //
3008     // The implementation avoids pointless extra computations when the two
3009     // addrec's are of different length (mathematically, it's equivalent to
3010     // an infinite stream of zeros on the right).
3011     bool OpsModified = false;
3012     for (unsigned OtherIdx = Idx+1;
3013          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3014          ++OtherIdx) {
3015       const SCEVAddRecExpr *OtherAddRec =
3016         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3017       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3018         continue;
3019 
3020       // Limit max number of arguments to avoid creation of unreasonably big
3021       // SCEVAddRecs with very complex operands.
3022       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3023           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3024         continue;
3025 
3026       bool Overflow = false;
3027       Type *Ty = AddRec->getType();
3028       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3029       SmallVector<const SCEV*, 7> AddRecOps;
3030       for (int x = 0, xe = AddRec->getNumOperands() +
3031              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3032         SmallVector <const SCEV *, 7> SumOps;
3033         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3034           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3035           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3036                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3037                z < ze && !Overflow; ++z) {
3038             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3039             uint64_t Coeff;
3040             if (LargerThan64Bits)
3041               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3042             else
3043               Coeff = Coeff1*Coeff2;
3044             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3045             const SCEV *Term1 = AddRec->getOperand(y-z);
3046             const SCEV *Term2 = OtherAddRec->getOperand(z);
3047             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3048                                         SCEV::FlagAnyWrap, Depth + 1));
3049           }
3050         }
3051         if (SumOps.empty())
3052           SumOps.push_back(getZero(Ty));
3053         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3054       }
3055       if (!Overflow) {
3056         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3057                                               SCEV::FlagAnyWrap);
3058         if (Ops.size() == 2) return NewAddRec;
3059         Ops[Idx] = NewAddRec;
3060         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3061         OpsModified = true;
3062         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3063         if (!AddRec)
3064           break;
3065       }
3066     }
3067     if (OpsModified)
3068       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3069 
3070     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3071     // next one.
3072   }
3073 
3074   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3075   // already have one, otherwise create a new one.
3076   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3077 }
3078 
3079 /// Represents an unsigned remainder expression based on unsigned division.
3080 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3081                                          const SCEV *RHS) {
3082   assert(getEffectiveSCEVType(LHS->getType()) ==
3083          getEffectiveSCEVType(RHS->getType()) &&
3084          "SCEVURemExpr operand types don't match!");
3085 
3086   // Short-circuit easy cases
3087   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3088     // If constant is one, the result is trivial
3089     if (RHSC->getValue()->isOne())
3090       return getZero(LHS->getType()); // X urem 1 --> 0
3091 
3092     // If constant is a power of two, fold into a zext(trunc(LHS)).
3093     if (RHSC->getAPInt().isPowerOf2()) {
3094       Type *FullTy = LHS->getType();
3095       Type *TruncTy =
3096           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3097       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3098     }
3099   }
3100 
3101   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3102   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3103   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3104   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3105 }
3106 
3107 /// Get a canonical unsigned division expression, or something simpler if
3108 /// possible.
3109 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3110                                          const SCEV *RHS) {
3111   assert(getEffectiveSCEVType(LHS->getType()) ==
3112          getEffectiveSCEVType(RHS->getType()) &&
3113          "SCEVUDivExpr operand types don't match!");
3114 
3115   FoldingSetNodeID ID;
3116   ID.AddInteger(scUDivExpr);
3117   ID.AddPointer(LHS);
3118   ID.AddPointer(RHS);
3119   void *IP = nullptr;
3120   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3121     return S;
3122 
3123   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3124     if (RHSC->getValue()->isOne())
3125       return LHS;                               // X udiv 1 --> x
3126     // If the denominator is zero, the result of the udiv is undefined. Don't
3127     // try to analyze it, because the resolution chosen here may differ from
3128     // the resolution chosen in other parts of the compiler.
3129     if (!RHSC->getValue()->isZero()) {
3130       // Determine if the division can be folded into the operands of
3131       // its operands.
3132       // TODO: Generalize this to non-constants by using known-bits information.
3133       Type *Ty = LHS->getType();
3134       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3135       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3136       // For non-power-of-two values, effectively round the value up to the
3137       // nearest power of two.
3138       if (!RHSC->getAPInt().isPowerOf2())
3139         ++MaxShiftAmt;
3140       IntegerType *ExtTy =
3141         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3142       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3143         if (const SCEVConstant *Step =
3144             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3145           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3146           const APInt &StepInt = Step->getAPInt();
3147           const APInt &DivInt = RHSC->getAPInt();
3148           if (!StepInt.urem(DivInt) &&
3149               getZeroExtendExpr(AR, ExtTy) ==
3150               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3151                             getZeroExtendExpr(Step, ExtTy),
3152                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3153             SmallVector<const SCEV *, 4> Operands;
3154             for (const SCEV *Op : AR->operands())
3155               Operands.push_back(getUDivExpr(Op, RHS));
3156             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3157           }
3158           /// Get a canonical UDivExpr for a recurrence.
3159           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3160           // We can currently only fold X%N if X is constant.
3161           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3162           if (StartC && !DivInt.urem(StepInt) &&
3163               getZeroExtendExpr(AR, ExtTy) ==
3164               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3165                             getZeroExtendExpr(Step, ExtTy),
3166                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3167             const APInt &StartInt = StartC->getAPInt();
3168             const APInt &StartRem = StartInt.urem(StepInt);
3169             if (StartRem != 0) {
3170               const SCEV *NewLHS =
3171                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3172                                 AR->getLoop(), SCEV::FlagNW);
3173               if (LHS != NewLHS) {
3174                 LHS = NewLHS;
3175 
3176                 // Reset the ID to include the new LHS, and check if it is
3177                 // already cached.
3178                 ID.clear();
3179                 ID.AddInteger(scUDivExpr);
3180                 ID.AddPointer(LHS);
3181                 ID.AddPointer(RHS);
3182                 IP = nullptr;
3183                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3184                   return S;
3185               }
3186             }
3187           }
3188         }
3189       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3190       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3191         SmallVector<const SCEV *, 4> Operands;
3192         for (const SCEV *Op : M->operands())
3193           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3194         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3195           // Find an operand that's safely divisible.
3196           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3197             const SCEV *Op = M->getOperand(i);
3198             const SCEV *Div = getUDivExpr(Op, RHSC);
3199             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3200               Operands = SmallVector<const SCEV *, 4>(M->operands());
3201               Operands[i] = Div;
3202               return getMulExpr(Operands);
3203             }
3204           }
3205       }
3206 
3207       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3208       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3209         if (auto *DivisorConstant =
3210                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3211           bool Overflow = false;
3212           APInt NewRHS =
3213               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3214           if (Overflow) {
3215             return getConstant(RHSC->getType(), 0, false);
3216           }
3217           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3218         }
3219       }
3220 
3221       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3222       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3223         SmallVector<const SCEV *, 4> Operands;
3224         for (const SCEV *Op : A->operands())
3225           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3226         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3227           Operands.clear();
3228           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3229             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3230             if (isa<SCEVUDivExpr>(Op) ||
3231                 getMulExpr(Op, RHS) != A->getOperand(i))
3232               break;
3233             Operands.push_back(Op);
3234           }
3235           if (Operands.size() == A->getNumOperands())
3236             return getAddExpr(Operands);
3237         }
3238       }
3239 
3240       // Fold if both operands are constant.
3241       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3242         Constant *LHSCV = LHSC->getValue();
3243         Constant *RHSCV = RHSC->getValue();
3244         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3245                                                                    RHSCV)));
3246       }
3247     }
3248   }
3249 
3250   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3251   // changes). Make sure we get a new one.
3252   IP = nullptr;
3253   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3254   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3255                                              LHS, RHS);
3256   UniqueSCEVs.InsertNode(S, IP);
3257   addToLoopUseLists(S);
3258   return S;
3259 }
3260 
3261 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3262   APInt A = C1->getAPInt().abs();
3263   APInt B = C2->getAPInt().abs();
3264   uint32_t ABW = A.getBitWidth();
3265   uint32_t BBW = B.getBitWidth();
3266 
3267   if (ABW > BBW)
3268     B = B.zext(ABW);
3269   else if (ABW < BBW)
3270     A = A.zext(BBW);
3271 
3272   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3273 }
3274 
3275 /// Get a canonical unsigned division expression, or something simpler if
3276 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3277 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3278 /// it's not exact because the udiv may be clearing bits.
3279 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3280                                               const SCEV *RHS) {
3281   // TODO: we could try to find factors in all sorts of things, but for now we
3282   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3283   // end of this file for inspiration.
3284 
3285   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3286   if (!Mul || !Mul->hasNoUnsignedWrap())
3287     return getUDivExpr(LHS, RHS);
3288 
3289   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3290     // If the mulexpr multiplies by a constant, then that constant must be the
3291     // first element of the mulexpr.
3292     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3293       if (LHSCst == RHSCst) {
3294         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3295         return getMulExpr(Operands);
3296       }
3297 
3298       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3299       // that there's a factor provided by one of the other terms. We need to
3300       // check.
3301       APInt Factor = gcd(LHSCst, RHSCst);
3302       if (!Factor.isIntN(1)) {
3303         LHSCst =
3304             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3305         RHSCst =
3306             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3307         SmallVector<const SCEV *, 2> Operands;
3308         Operands.push_back(LHSCst);
3309         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3310         LHS = getMulExpr(Operands);
3311         RHS = RHSCst;
3312         Mul = dyn_cast<SCEVMulExpr>(LHS);
3313         if (!Mul)
3314           return getUDivExactExpr(LHS, RHS);
3315       }
3316     }
3317   }
3318 
3319   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3320     if (Mul->getOperand(i) == RHS) {
3321       SmallVector<const SCEV *, 2> Operands;
3322       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3323       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3324       return getMulExpr(Operands);
3325     }
3326   }
3327 
3328   return getUDivExpr(LHS, RHS);
3329 }
3330 
3331 /// Get an add recurrence expression for the specified loop.  Simplify the
3332 /// expression as much as possible.
3333 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3334                                            const Loop *L,
3335                                            SCEV::NoWrapFlags Flags) {
3336   SmallVector<const SCEV *, 4> Operands;
3337   Operands.push_back(Start);
3338   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3339     if (StepChrec->getLoop() == L) {
3340       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3341       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3342     }
3343 
3344   Operands.push_back(Step);
3345   return getAddRecExpr(Operands, L, Flags);
3346 }
3347 
3348 /// Get an add recurrence expression for the specified loop.  Simplify the
3349 /// expression as much as possible.
3350 const SCEV *
3351 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3352                                const Loop *L, SCEV::NoWrapFlags Flags) {
3353   if (Operands.size() == 1) return Operands[0];
3354 #ifndef NDEBUG
3355   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3356   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3357     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3358            "SCEVAddRecExpr operand types don't match!");
3359   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3360     assert(isLoopInvariant(Operands[i], L) &&
3361            "SCEVAddRecExpr operand is not loop-invariant!");
3362 #endif
3363 
3364   if (Operands.back()->isZero()) {
3365     Operands.pop_back();
3366     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3367   }
3368 
3369   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3370   // use that information to infer NUW and NSW flags. However, computing a
3371   // BE count requires calling getAddRecExpr, so we may not yet have a
3372   // meaningful BE count at this point (and if we don't, we'd be stuck
3373   // with a SCEVCouldNotCompute as the cached BE count).
3374 
3375   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3376 
3377   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3378   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3379     const Loop *NestedLoop = NestedAR->getLoop();
3380     if (L->contains(NestedLoop)
3381             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3382             : (!NestedLoop->contains(L) &&
3383                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3384       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3385       Operands[0] = NestedAR->getStart();
3386       // AddRecs require their operands be loop-invariant with respect to their
3387       // loops. Don't perform this transformation if it would break this
3388       // requirement.
3389       bool AllInvariant = all_of(
3390           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3391 
3392       if (AllInvariant) {
3393         // Create a recurrence for the outer loop with the same step size.
3394         //
3395         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3396         // inner recurrence has the same property.
3397         SCEV::NoWrapFlags OuterFlags =
3398           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3399 
3400         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3401         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3402           return isLoopInvariant(Op, NestedLoop);
3403         });
3404 
3405         if (AllInvariant) {
3406           // Ok, both add recurrences are valid after the transformation.
3407           //
3408           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3409           // the outer recurrence has the same property.
3410           SCEV::NoWrapFlags InnerFlags =
3411             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3412           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3413         }
3414       }
3415       // Reset Operands to its original state.
3416       Operands[0] = NestedAR;
3417     }
3418   }
3419 
3420   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3421   // already have one, otherwise create a new one.
3422   return getOrCreateAddRecExpr(Operands, L, Flags);
3423 }
3424 
3425 const SCEV *
3426 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3427                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3428   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3429   // getSCEV(Base)->getType() has the same address space as Base->getType()
3430   // because SCEV::getType() preserves the address space.
3431   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3432   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3433   // instruction to its SCEV, because the Instruction may be guarded by control
3434   // flow and the no-overflow bits may not be valid for the expression in any
3435   // context. This can be fixed similarly to how these flags are handled for
3436   // adds.
3437   SCEV::NoWrapFlags OffsetWrap =
3438       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3439 
3440   Type *CurTy = GEP->getType();
3441   bool FirstIter = true;
3442   SmallVector<const SCEV *, 4> Offsets;
3443   for (const SCEV *IndexExpr : IndexExprs) {
3444     // Compute the (potentially symbolic) offset in bytes for this index.
3445     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3446       // For a struct, add the member offset.
3447       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3448       unsigned FieldNo = Index->getZExtValue();
3449       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3450       Offsets.push_back(FieldOffset);
3451 
3452       // Update CurTy to the type of the field at Index.
3453       CurTy = STy->getTypeAtIndex(Index);
3454     } else {
3455       // Update CurTy to its element type.
3456       if (FirstIter) {
3457         assert(isa<PointerType>(CurTy) &&
3458                "The first index of a GEP indexes a pointer");
3459         CurTy = GEP->getSourceElementType();
3460         FirstIter = false;
3461       } else {
3462         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3463       }
3464       // For an array, add the element offset, explicitly scaled.
3465       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3466       // Getelementptr indices are signed.
3467       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3468 
3469       // Multiply the index by the element size to compute the element offset.
3470       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3471       Offsets.push_back(LocalOffset);
3472     }
3473   }
3474 
3475   // Handle degenerate case of GEP without offsets.
3476   if (Offsets.empty())
3477     return BaseExpr;
3478 
3479   // Add the offsets together, assuming nsw if inbounds.
3480   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3481   // Add the base address and the offset. We cannot use the nsw flag, as the
3482   // base address is unsigned. However, if we know that the offset is
3483   // non-negative, we can use nuw.
3484   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3485                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3486   return getAddExpr(BaseExpr, Offset, BaseWrap);
3487 }
3488 
3489 std::tuple<SCEV *, FoldingSetNodeID, void *>
3490 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3491                                          ArrayRef<const SCEV *> Ops) {
3492   FoldingSetNodeID ID;
3493   void *IP = nullptr;
3494   ID.AddInteger(SCEVType);
3495   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3496     ID.AddPointer(Ops[i]);
3497   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3498       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3499 }
3500 
3501 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3502   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3503   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3504 }
3505 
3506 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) {
3507   Type *Ty = Op->getType();
3508   return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty));
3509 }
3510 
3511 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3512                                            SmallVectorImpl<const SCEV *> &Ops) {
3513   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3514   if (Ops.size() == 1) return Ops[0];
3515 #ifndef NDEBUG
3516   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3517   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3518     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3519            "Operand types don't match!");
3520 #endif
3521 
3522   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3523   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3524 
3525   // Sort by complexity, this groups all similar expression types together.
3526   GroupByComplexity(Ops, &LI, DT);
3527 
3528   // Check if we have created the same expression before.
3529   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3530     return S;
3531   }
3532 
3533   // If there are any constants, fold them together.
3534   unsigned Idx = 0;
3535   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3536     ++Idx;
3537     assert(Idx < Ops.size());
3538     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3539       if (Kind == scSMaxExpr)
3540         return APIntOps::smax(LHS, RHS);
3541       else if (Kind == scSMinExpr)
3542         return APIntOps::smin(LHS, RHS);
3543       else if (Kind == scUMaxExpr)
3544         return APIntOps::umax(LHS, RHS);
3545       else if (Kind == scUMinExpr)
3546         return APIntOps::umin(LHS, RHS);
3547       llvm_unreachable("Unknown SCEV min/max opcode");
3548     };
3549 
3550     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3551       // We found two constants, fold them together!
3552       ConstantInt *Fold = ConstantInt::get(
3553           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3554       Ops[0] = getConstant(Fold);
3555       Ops.erase(Ops.begin()+1);  // Erase the folded element
3556       if (Ops.size() == 1) return Ops[0];
3557       LHSC = cast<SCEVConstant>(Ops[0]);
3558     }
3559 
3560     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3561     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3562 
3563     if (IsMax ? IsMinV : IsMaxV) {
3564       // If we are left with a constant minimum(/maximum)-int, strip it off.
3565       Ops.erase(Ops.begin());
3566       --Idx;
3567     } else if (IsMax ? IsMaxV : IsMinV) {
3568       // If we have a max(/min) with a constant maximum(/minimum)-int,
3569       // it will always be the extremum.
3570       return LHSC;
3571     }
3572 
3573     if (Ops.size() == 1) return Ops[0];
3574   }
3575 
3576   // Find the first operation of the same kind
3577   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3578     ++Idx;
3579 
3580   // Check to see if one of the operands is of the same kind. If so, expand its
3581   // operands onto our operand list, and recurse to simplify.
3582   if (Idx < Ops.size()) {
3583     bool DeletedAny = false;
3584     while (Ops[Idx]->getSCEVType() == Kind) {
3585       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3586       Ops.erase(Ops.begin()+Idx);
3587       Ops.append(SMME->op_begin(), SMME->op_end());
3588       DeletedAny = true;
3589     }
3590 
3591     if (DeletedAny)
3592       return getMinMaxExpr(Kind, Ops);
3593   }
3594 
3595   // Okay, check to see if the same value occurs in the operand list twice.  If
3596   // so, delete one.  Since we sorted the list, these values are required to
3597   // be adjacent.
3598   llvm::CmpInst::Predicate GEPred =
3599       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3600   llvm::CmpInst::Predicate LEPred =
3601       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3602   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3603   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3604   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3605     if (Ops[i] == Ops[i + 1] ||
3606         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3607       //  X op Y op Y  -->  X op Y
3608       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3609       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3610       --i;
3611       --e;
3612     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3613                                                Ops[i + 1])) {
3614       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3615       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3616       --i;
3617       --e;
3618     }
3619   }
3620 
3621   if (Ops.size() == 1) return Ops[0];
3622 
3623   assert(!Ops.empty() && "Reduced smax down to nothing!");
3624 
3625   // Okay, it looks like we really DO need an expr.  Check to see if we
3626   // already have one, otherwise create a new one.
3627   const SCEV *ExistingSCEV;
3628   FoldingSetNodeID ID;
3629   void *IP;
3630   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3631   if (ExistingSCEV)
3632     return ExistingSCEV;
3633   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3634   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3635   SCEV *S = new (SCEVAllocator)
3636       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3637 
3638   UniqueSCEVs.InsertNode(S, IP);
3639   addToLoopUseLists(S);
3640   return S;
3641 }
3642 
3643 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3644   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3645   return getSMaxExpr(Ops);
3646 }
3647 
3648 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3649   return getMinMaxExpr(scSMaxExpr, Ops);
3650 }
3651 
3652 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3653   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3654   return getUMaxExpr(Ops);
3655 }
3656 
3657 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3658   return getMinMaxExpr(scUMaxExpr, Ops);
3659 }
3660 
3661 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3662                                          const SCEV *RHS) {
3663   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3664   return getSMinExpr(Ops);
3665 }
3666 
3667 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3668   return getMinMaxExpr(scSMinExpr, Ops);
3669 }
3670 
3671 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3672                                          const SCEV *RHS) {
3673   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3674   return getUMinExpr(Ops);
3675 }
3676 
3677 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3678   return getMinMaxExpr(scUMinExpr, Ops);
3679 }
3680 
3681 const SCEV *
3682 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3683                                              ScalableVectorType *ScalableTy) {
3684   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3685   Constant *One = ConstantInt::get(IntTy, 1);
3686   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3687   // Note that the expression we created is the final expression, we don't
3688   // want to simplify it any further Also, if we call a normal getSCEV(),
3689   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3690   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3691 }
3692 
3693 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3694   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3695     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3696   // We can bypass creating a target-independent constant expression and then
3697   // folding it back into a ConstantInt. This is just a compile-time
3698   // optimization.
3699   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3700 }
3701 
3702 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3703   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3704     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3705   // We can bypass creating a target-independent constant expression and then
3706   // folding it back into a ConstantInt. This is just a compile-time
3707   // optimization.
3708   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3709 }
3710 
3711 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3712                                              StructType *STy,
3713                                              unsigned FieldNo) {
3714   // We can bypass creating a target-independent constant expression and then
3715   // folding it back into a ConstantInt. This is just a compile-time
3716   // optimization.
3717   return getConstant(
3718       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3719 }
3720 
3721 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3722   // Don't attempt to do anything other than create a SCEVUnknown object
3723   // here.  createSCEV only calls getUnknown after checking for all other
3724   // interesting possibilities, and any other code that calls getUnknown
3725   // is doing so in order to hide a value from SCEV canonicalization.
3726 
3727   FoldingSetNodeID ID;
3728   ID.AddInteger(scUnknown);
3729   ID.AddPointer(V);
3730   void *IP = nullptr;
3731   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3732     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3733            "Stale SCEVUnknown in uniquing map!");
3734     return S;
3735   }
3736   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3737                                             FirstUnknown);
3738   FirstUnknown = cast<SCEVUnknown>(S);
3739   UniqueSCEVs.InsertNode(S, IP);
3740   return S;
3741 }
3742 
3743 //===----------------------------------------------------------------------===//
3744 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3745 //
3746 
3747 /// Test if values of the given type are analyzable within the SCEV
3748 /// framework. This primarily includes integer types, and it can optionally
3749 /// include pointer types if the ScalarEvolution class has access to
3750 /// target-specific information.
3751 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3752   // Integers and pointers are always SCEVable.
3753   return Ty->isIntOrPtrTy();
3754 }
3755 
3756 /// Return the size in bits of the specified type, for which isSCEVable must
3757 /// return true.
3758 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3759   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3760   if (Ty->isPointerTy())
3761     return getDataLayout().getIndexTypeSizeInBits(Ty);
3762   return getDataLayout().getTypeSizeInBits(Ty);
3763 }
3764 
3765 /// Return a type with the same bitwidth as the given type and which represents
3766 /// how SCEV will treat the given type, for which isSCEVable must return
3767 /// true. For pointer types, this is the pointer index sized integer type.
3768 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3769   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3770 
3771   if (Ty->isIntegerTy())
3772     return Ty;
3773 
3774   // The only other support type is pointer.
3775   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3776   return getDataLayout().getIndexType(Ty);
3777 }
3778 
3779 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3780   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3781 }
3782 
3783 const SCEV *ScalarEvolution::getCouldNotCompute() {
3784   return CouldNotCompute.get();
3785 }
3786 
3787 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3788   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3789     auto *SU = dyn_cast<SCEVUnknown>(S);
3790     return SU && SU->getValue() == nullptr;
3791   });
3792 
3793   return !ContainsNulls;
3794 }
3795 
3796 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3797   HasRecMapType::iterator I = HasRecMap.find(S);
3798   if (I != HasRecMap.end())
3799     return I->second;
3800 
3801   bool FoundAddRec =
3802       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3803   HasRecMap.insert({S, FoundAddRec});
3804   return FoundAddRec;
3805 }
3806 
3807 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3808 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3809 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3810 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3811   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3812   if (!Add)
3813     return {S, nullptr};
3814 
3815   if (Add->getNumOperands() != 2)
3816     return {S, nullptr};
3817 
3818   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3819   if (!ConstOp)
3820     return {S, nullptr};
3821 
3822   return {Add->getOperand(1), ConstOp->getValue()};
3823 }
3824 
3825 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3826 /// by the value and offset from any ValueOffsetPair in the set.
3827 SetVector<ScalarEvolution::ValueOffsetPair> *
3828 ScalarEvolution::getSCEVValues(const SCEV *S) {
3829   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3830   if (SI == ExprValueMap.end())
3831     return nullptr;
3832 #ifndef NDEBUG
3833   if (VerifySCEVMap) {
3834     // Check there is no dangling Value in the set returned.
3835     for (const auto &VE : SI->second)
3836       assert(ValueExprMap.count(VE.first));
3837   }
3838 #endif
3839   return &SI->second;
3840 }
3841 
3842 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3843 /// cannot be used separately. eraseValueFromMap should be used to remove
3844 /// V from ValueExprMap and ExprValueMap at the same time.
3845 void ScalarEvolution::eraseValueFromMap(Value *V) {
3846   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3847   if (I != ValueExprMap.end()) {
3848     const SCEV *S = I->second;
3849     // Remove {V, 0} from the set of ExprValueMap[S]
3850     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3851       SV->remove({V, nullptr});
3852 
3853     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3854     const SCEV *Stripped;
3855     ConstantInt *Offset;
3856     std::tie(Stripped, Offset) = splitAddExpr(S);
3857     if (Offset != nullptr) {
3858       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3859         SV->remove({V, Offset});
3860     }
3861     ValueExprMap.erase(V);
3862   }
3863 }
3864 
3865 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3866 /// TODO: In reality it is better to check the poison recursively
3867 /// but this is better than nothing.
3868 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3869   if (auto *I = dyn_cast<Instruction>(V)) {
3870     if (isa<OverflowingBinaryOperator>(I)) {
3871       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3872         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3873           return true;
3874         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3875           return true;
3876       }
3877     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3878       return true;
3879   }
3880   return false;
3881 }
3882 
3883 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3884 /// create a new one.
3885 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3886   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3887 
3888   const SCEV *S = getExistingSCEV(V);
3889   if (S == nullptr) {
3890     S = createSCEV(V);
3891     // During PHI resolution, it is possible to create two SCEVs for the same
3892     // V, so it is needed to double check whether V->S is inserted into
3893     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3894     std::pair<ValueExprMapType::iterator, bool> Pair =
3895         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3896     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3897       ExprValueMap[S].insert({V, nullptr});
3898 
3899       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3900       // ExprValueMap.
3901       const SCEV *Stripped = S;
3902       ConstantInt *Offset = nullptr;
3903       std::tie(Stripped, Offset) = splitAddExpr(S);
3904       // If stripped is SCEVUnknown, don't bother to save
3905       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3906       // increase the complexity of the expansion code.
3907       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3908       // because it may generate add/sub instead of GEP in SCEV expansion.
3909       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3910           !isa<GetElementPtrInst>(V))
3911         ExprValueMap[Stripped].insert({V, Offset});
3912     }
3913   }
3914   return S;
3915 }
3916 
3917 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3918   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3919 
3920   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3921   if (I != ValueExprMap.end()) {
3922     const SCEV *S = I->second;
3923     if (checkValidity(S))
3924       return S;
3925     eraseValueFromMap(V);
3926     forgetMemoizedResults(S);
3927   }
3928   return nullptr;
3929 }
3930 
3931 /// Return a SCEV corresponding to -V = -1*V
3932 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3933                                              SCEV::NoWrapFlags Flags) {
3934   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3935     return getConstant(
3936                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3937 
3938   Type *Ty = V->getType();
3939   Ty = getEffectiveSCEVType(Ty);
3940   return getMulExpr(V, getMinusOne(Ty), Flags);
3941 }
3942 
3943 /// If Expr computes ~A, return A else return nullptr
3944 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3945   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3946   if (!Add || Add->getNumOperands() != 2 ||
3947       !Add->getOperand(0)->isAllOnesValue())
3948     return nullptr;
3949 
3950   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3951   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3952       !AddRHS->getOperand(0)->isAllOnesValue())
3953     return nullptr;
3954 
3955   return AddRHS->getOperand(1);
3956 }
3957 
3958 /// Return a SCEV corresponding to ~V = -1-V
3959 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3960   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3961     return getConstant(
3962                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3963 
3964   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3965   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3966     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3967       SmallVector<const SCEV *, 2> MatchedOperands;
3968       for (const SCEV *Operand : MME->operands()) {
3969         const SCEV *Matched = MatchNotExpr(Operand);
3970         if (!Matched)
3971           return (const SCEV *)nullptr;
3972         MatchedOperands.push_back(Matched);
3973       }
3974       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3975                            MatchedOperands);
3976     };
3977     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3978       return Replaced;
3979   }
3980 
3981   Type *Ty = V->getType();
3982   Ty = getEffectiveSCEVType(Ty);
3983   return getMinusSCEV(getMinusOne(Ty), V);
3984 }
3985 
3986 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3987                                           SCEV::NoWrapFlags Flags,
3988                                           unsigned Depth) {
3989   // Fast path: X - X --> 0.
3990   if (LHS == RHS)
3991     return getZero(LHS->getType());
3992 
3993   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3994   // makes it so that we cannot make much use of NUW.
3995   auto AddFlags = SCEV::FlagAnyWrap;
3996   const bool RHSIsNotMinSigned =
3997       !getSignedRangeMin(RHS).isMinSignedValue();
3998   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3999     // Let M be the minimum representable signed value. Then (-1)*RHS
4000     // signed-wraps if and only if RHS is M. That can happen even for
4001     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4002     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4003     // (-1)*RHS, we need to prove that RHS != M.
4004     //
4005     // If LHS is non-negative and we know that LHS - RHS does not
4006     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4007     // either by proving that RHS > M or that LHS >= 0.
4008     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4009       AddFlags = SCEV::FlagNSW;
4010     }
4011   }
4012 
4013   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4014   // RHS is NSW and LHS >= 0.
4015   //
4016   // The difficulty here is that the NSW flag may have been proven
4017   // relative to a loop that is to be found in a recurrence in LHS and
4018   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4019   // larger scope than intended.
4020   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4021 
4022   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4023 }
4024 
4025 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4026                                                      unsigned Depth) {
4027   Type *SrcTy = V->getType();
4028   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4029          "Cannot truncate or zero extend with non-integer arguments!");
4030   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4031     return V;  // No conversion
4032   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4033     return getTruncateExpr(V, Ty, Depth);
4034   return getZeroExtendExpr(V, Ty, Depth);
4035 }
4036 
4037 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4038                                                      unsigned Depth) {
4039   Type *SrcTy = V->getType();
4040   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4041          "Cannot truncate or zero extend with non-integer arguments!");
4042   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4043     return V;  // No conversion
4044   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4045     return getTruncateExpr(V, Ty, Depth);
4046   return getSignExtendExpr(V, Ty, Depth);
4047 }
4048 
4049 const SCEV *
4050 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4051   Type *SrcTy = V->getType();
4052   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4053          "Cannot noop or zero extend with non-integer arguments!");
4054   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4055          "getNoopOrZeroExtend cannot truncate!");
4056   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4057     return V;  // No conversion
4058   return getZeroExtendExpr(V, Ty);
4059 }
4060 
4061 const SCEV *
4062 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4063   Type *SrcTy = V->getType();
4064   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4065          "Cannot noop or sign extend with non-integer arguments!");
4066   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4067          "getNoopOrSignExtend cannot truncate!");
4068   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4069     return V;  // No conversion
4070   return getSignExtendExpr(V, Ty);
4071 }
4072 
4073 const SCEV *
4074 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4075   Type *SrcTy = V->getType();
4076   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4077          "Cannot noop or any extend with non-integer arguments!");
4078   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4079          "getNoopOrAnyExtend cannot truncate!");
4080   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4081     return V;  // No conversion
4082   return getAnyExtendExpr(V, Ty);
4083 }
4084 
4085 const SCEV *
4086 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4087   Type *SrcTy = V->getType();
4088   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4089          "Cannot truncate or noop with non-integer arguments!");
4090   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4091          "getTruncateOrNoop cannot extend!");
4092   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4093     return V;  // No conversion
4094   return getTruncateExpr(V, Ty);
4095 }
4096 
4097 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4098                                                         const SCEV *RHS) {
4099   const SCEV *PromotedLHS = LHS;
4100   const SCEV *PromotedRHS = RHS;
4101 
4102   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4103     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4104   else
4105     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4106 
4107   return getUMaxExpr(PromotedLHS, PromotedRHS);
4108 }
4109 
4110 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4111                                                         const SCEV *RHS) {
4112   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4113   return getUMinFromMismatchedTypes(Ops);
4114 }
4115 
4116 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4117     SmallVectorImpl<const SCEV *> &Ops) {
4118   assert(!Ops.empty() && "At least one operand must be!");
4119   // Trivial case.
4120   if (Ops.size() == 1)
4121     return Ops[0];
4122 
4123   // Find the max type first.
4124   Type *MaxType = nullptr;
4125   for (auto *S : Ops)
4126     if (MaxType)
4127       MaxType = getWiderType(MaxType, S->getType());
4128     else
4129       MaxType = S->getType();
4130   assert(MaxType && "Failed to find maximum type!");
4131 
4132   // Extend all ops to max type.
4133   SmallVector<const SCEV *, 2> PromotedOps;
4134   for (auto *S : Ops)
4135     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4136 
4137   // Generate umin.
4138   return getUMinExpr(PromotedOps);
4139 }
4140 
4141 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4142   // A pointer operand may evaluate to a nonpointer expression, such as null.
4143   if (!V->getType()->isPointerTy())
4144     return V;
4145 
4146   while (true) {
4147     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4148       V = Cast->getOperand();
4149     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4150       const SCEV *PtrOp = nullptr;
4151       for (const SCEV *NAryOp : NAry->operands()) {
4152         if (NAryOp->getType()->isPointerTy()) {
4153           // Cannot find the base of an expression with multiple pointer ops.
4154           if (PtrOp)
4155             return V;
4156           PtrOp = NAryOp;
4157         }
4158       }
4159       if (!PtrOp) // All operands were non-pointer.
4160         return V;
4161       V = PtrOp;
4162     } else // Not something we can look further into.
4163       return V;
4164   }
4165 }
4166 
4167 /// Push users of the given Instruction onto the given Worklist.
4168 static void
4169 PushDefUseChildren(Instruction *I,
4170                    SmallVectorImpl<Instruction *> &Worklist) {
4171   // Push the def-use children onto the Worklist stack.
4172   for (User *U : I->users())
4173     Worklist.push_back(cast<Instruction>(U));
4174 }
4175 
4176 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4177   SmallVector<Instruction *, 16> Worklist;
4178   PushDefUseChildren(PN, Worklist);
4179 
4180   SmallPtrSet<Instruction *, 8> Visited;
4181   Visited.insert(PN);
4182   while (!Worklist.empty()) {
4183     Instruction *I = Worklist.pop_back_val();
4184     if (!Visited.insert(I).second)
4185       continue;
4186 
4187     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4188     if (It != ValueExprMap.end()) {
4189       const SCEV *Old = It->second;
4190 
4191       // Short-circuit the def-use traversal if the symbolic name
4192       // ceases to appear in expressions.
4193       if (Old != SymName && !hasOperand(Old, SymName))
4194         continue;
4195 
4196       // SCEVUnknown for a PHI either means that it has an unrecognized
4197       // structure, it's a PHI that's in the progress of being computed
4198       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4199       // additional loop trip count information isn't going to change anything.
4200       // In the second case, createNodeForPHI will perform the necessary
4201       // updates on its own when it gets to that point. In the third, we do
4202       // want to forget the SCEVUnknown.
4203       if (!isa<PHINode>(I) ||
4204           !isa<SCEVUnknown>(Old) ||
4205           (I != PN && Old == SymName)) {
4206         eraseValueFromMap(It->first);
4207         forgetMemoizedResults(Old);
4208       }
4209     }
4210 
4211     PushDefUseChildren(I, Worklist);
4212   }
4213 }
4214 
4215 namespace {
4216 
4217 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4218 /// expression in case its Loop is L. If it is not L then
4219 /// if IgnoreOtherLoops is true then use AddRec itself
4220 /// otherwise rewrite cannot be done.
4221 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4222 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4223 public:
4224   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4225                              bool IgnoreOtherLoops = true) {
4226     SCEVInitRewriter Rewriter(L, SE);
4227     const SCEV *Result = Rewriter.visit(S);
4228     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4229       return SE.getCouldNotCompute();
4230     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4231                ? SE.getCouldNotCompute()
4232                : Result;
4233   }
4234 
4235   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4236     if (!SE.isLoopInvariant(Expr, L))
4237       SeenLoopVariantSCEVUnknown = true;
4238     return Expr;
4239   }
4240 
4241   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4242     // Only re-write AddRecExprs for this loop.
4243     if (Expr->getLoop() == L)
4244       return Expr->getStart();
4245     SeenOtherLoops = true;
4246     return Expr;
4247   }
4248 
4249   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4250 
4251   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4252 
4253 private:
4254   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4255       : SCEVRewriteVisitor(SE), L(L) {}
4256 
4257   const Loop *L;
4258   bool SeenLoopVariantSCEVUnknown = false;
4259   bool SeenOtherLoops = false;
4260 };
4261 
4262 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4263 /// increment expression in case its Loop is L. If it is not L then
4264 /// use AddRec itself.
4265 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4266 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4267 public:
4268   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4269     SCEVPostIncRewriter Rewriter(L, SE);
4270     const SCEV *Result = Rewriter.visit(S);
4271     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4272         ? SE.getCouldNotCompute()
4273         : Result;
4274   }
4275 
4276   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4277     if (!SE.isLoopInvariant(Expr, L))
4278       SeenLoopVariantSCEVUnknown = true;
4279     return Expr;
4280   }
4281 
4282   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4283     // Only re-write AddRecExprs for this loop.
4284     if (Expr->getLoop() == L)
4285       return Expr->getPostIncExpr(SE);
4286     SeenOtherLoops = true;
4287     return Expr;
4288   }
4289 
4290   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4291 
4292   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4293 
4294 private:
4295   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4296       : SCEVRewriteVisitor(SE), L(L) {}
4297 
4298   const Loop *L;
4299   bool SeenLoopVariantSCEVUnknown = false;
4300   bool SeenOtherLoops = false;
4301 };
4302 
4303 /// This class evaluates the compare condition by matching it against the
4304 /// condition of loop latch. If there is a match we assume a true value
4305 /// for the condition while building SCEV nodes.
4306 class SCEVBackedgeConditionFolder
4307     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4308 public:
4309   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4310                              ScalarEvolution &SE) {
4311     bool IsPosBECond = false;
4312     Value *BECond = nullptr;
4313     if (BasicBlock *Latch = L->getLoopLatch()) {
4314       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4315       if (BI && BI->isConditional()) {
4316         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4317                "Both outgoing branches should not target same header!");
4318         BECond = BI->getCondition();
4319         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4320       } else {
4321         return S;
4322       }
4323     }
4324     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4325     return Rewriter.visit(S);
4326   }
4327 
4328   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4329     const SCEV *Result = Expr;
4330     bool InvariantF = SE.isLoopInvariant(Expr, L);
4331 
4332     if (!InvariantF) {
4333       Instruction *I = cast<Instruction>(Expr->getValue());
4334       switch (I->getOpcode()) {
4335       case Instruction::Select: {
4336         SelectInst *SI = cast<SelectInst>(I);
4337         Optional<const SCEV *> Res =
4338             compareWithBackedgeCondition(SI->getCondition());
4339         if (Res.hasValue()) {
4340           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4341           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4342         }
4343         break;
4344       }
4345       default: {
4346         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4347         if (Res.hasValue())
4348           Result = Res.getValue();
4349         break;
4350       }
4351       }
4352     }
4353     return Result;
4354   }
4355 
4356 private:
4357   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4358                                        bool IsPosBECond, ScalarEvolution &SE)
4359       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4360         IsPositiveBECond(IsPosBECond) {}
4361 
4362   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4363 
4364   const Loop *L;
4365   /// Loop back condition.
4366   Value *BackedgeCond = nullptr;
4367   /// Set to true if loop back is on positive branch condition.
4368   bool IsPositiveBECond;
4369 };
4370 
4371 Optional<const SCEV *>
4372 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4373 
4374   // If value matches the backedge condition for loop latch,
4375   // then return a constant evolution node based on loopback
4376   // branch taken.
4377   if (BackedgeCond == IC)
4378     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4379                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4380   return None;
4381 }
4382 
4383 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4384 public:
4385   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4386                              ScalarEvolution &SE) {
4387     SCEVShiftRewriter Rewriter(L, SE);
4388     const SCEV *Result = Rewriter.visit(S);
4389     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4390   }
4391 
4392   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4393     // Only allow AddRecExprs for this loop.
4394     if (!SE.isLoopInvariant(Expr, L))
4395       Valid = false;
4396     return Expr;
4397   }
4398 
4399   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4400     if (Expr->getLoop() == L && Expr->isAffine())
4401       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4402     Valid = false;
4403     return Expr;
4404   }
4405 
4406   bool isValid() { return Valid; }
4407 
4408 private:
4409   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4410       : SCEVRewriteVisitor(SE), L(L) {}
4411 
4412   const Loop *L;
4413   bool Valid = true;
4414 };
4415 
4416 } // end anonymous namespace
4417 
4418 SCEV::NoWrapFlags
4419 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4420   if (!AR->isAffine())
4421     return SCEV::FlagAnyWrap;
4422 
4423   using OBO = OverflowingBinaryOperator;
4424 
4425   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4426 
4427   if (!AR->hasNoSignedWrap()) {
4428     ConstantRange AddRecRange = getSignedRange(AR);
4429     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4430 
4431     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4432         Instruction::Add, IncRange, OBO::NoSignedWrap);
4433     if (NSWRegion.contains(AddRecRange))
4434       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4435   }
4436 
4437   if (!AR->hasNoUnsignedWrap()) {
4438     ConstantRange AddRecRange = getUnsignedRange(AR);
4439     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4440 
4441     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4442         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4443     if (NUWRegion.contains(AddRecRange))
4444       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4445   }
4446 
4447   return Result;
4448 }
4449 
4450 SCEV::NoWrapFlags
4451 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4452   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4453 
4454   if (AR->hasNoSignedWrap())
4455     return Result;
4456 
4457   if (!AR->isAffine())
4458     return Result;
4459 
4460   const SCEV *Step = AR->getStepRecurrence(*this);
4461   const Loop *L = AR->getLoop();
4462 
4463   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4464   // Note that this serves two purposes: It filters out loops that are
4465   // simply not analyzable, and it covers the case where this code is
4466   // being called from within backedge-taken count analysis, such that
4467   // attempting to ask for the backedge-taken count would likely result
4468   // in infinite recursion. In the later case, the analysis code will
4469   // cope with a conservative value, and it will take care to purge
4470   // that value once it has finished.
4471   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4472 
4473   // Normally, in the cases we can prove no-overflow via a
4474   // backedge guarding condition, we can also compute a backedge
4475   // taken count for the loop.  The exceptions are assumptions and
4476   // guards present in the loop -- SCEV is not great at exploiting
4477   // these to compute max backedge taken counts, but can still use
4478   // these to prove lack of overflow.  Use this fact to avoid
4479   // doing extra work that may not pay off.
4480 
4481   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4482       AC.assumptions().empty())
4483     return Result;
4484 
4485   // If the backedge is guarded by a comparison with the pre-inc  value the
4486   // addrec is safe. Also, if the entry is guarded by a comparison with the
4487   // start value and the backedge is guarded by a comparison with the post-inc
4488   // value, the addrec is safe.
4489   ICmpInst::Predicate Pred;
4490   const SCEV *OverflowLimit =
4491     getSignedOverflowLimitForStep(Step, &Pred, this);
4492   if (OverflowLimit &&
4493       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4494        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4495     Result = setFlags(Result, SCEV::FlagNSW);
4496   }
4497   return Result;
4498 }
4499 SCEV::NoWrapFlags
4500 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4501   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4502 
4503   if (AR->hasNoUnsignedWrap())
4504     return Result;
4505 
4506   if (!AR->isAffine())
4507     return Result;
4508 
4509   const SCEV *Step = AR->getStepRecurrence(*this);
4510   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4511   const Loop *L = AR->getLoop();
4512 
4513   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4514   // Note that this serves two purposes: It filters out loops that are
4515   // simply not analyzable, and it covers the case where this code is
4516   // being called from within backedge-taken count analysis, such that
4517   // attempting to ask for the backedge-taken count would likely result
4518   // in infinite recursion. In the later case, the analysis code will
4519   // cope with a conservative value, and it will take care to purge
4520   // that value once it has finished.
4521   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4522 
4523   // Normally, in the cases we can prove no-overflow via a
4524   // backedge guarding condition, we can also compute a backedge
4525   // taken count for the loop.  The exceptions are assumptions and
4526   // guards present in the loop -- SCEV is not great at exploiting
4527   // these to compute max backedge taken counts, but can still use
4528   // these to prove lack of overflow.  Use this fact to avoid
4529   // doing extra work that may not pay off.
4530 
4531   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4532       AC.assumptions().empty())
4533     return Result;
4534 
4535   // If the backedge is guarded by a comparison with the pre-inc  value the
4536   // addrec is safe. Also, if the entry is guarded by a comparison with the
4537   // start value and the backedge is guarded by a comparison with the post-inc
4538   // value, the addrec is safe.
4539   if (isKnownPositive(Step)) {
4540     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4541                                 getUnsignedRangeMax(Step));
4542     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4543         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4544       Result = setFlags(Result, SCEV::FlagNUW);
4545     }
4546   }
4547 
4548   return Result;
4549 }
4550 
4551 namespace {
4552 
4553 /// Represents an abstract binary operation.  This may exist as a
4554 /// normal instruction or constant expression, or may have been
4555 /// derived from an expression tree.
4556 struct BinaryOp {
4557   unsigned Opcode;
4558   Value *LHS;
4559   Value *RHS;
4560   bool IsNSW = false;
4561   bool IsNUW = false;
4562   bool IsExact = false;
4563 
4564   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4565   /// constant expression.
4566   Operator *Op = nullptr;
4567 
4568   explicit BinaryOp(Operator *Op)
4569       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4570         Op(Op) {
4571     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4572       IsNSW = OBO->hasNoSignedWrap();
4573       IsNUW = OBO->hasNoUnsignedWrap();
4574     }
4575     if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op))
4576       IsExact = PEO->isExact();
4577   }
4578 
4579   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4580                     bool IsNUW = false, bool IsExact = false)
4581       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4582         IsExact(IsExact) {}
4583 };
4584 
4585 } // end anonymous namespace
4586 
4587 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4588 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4589   auto *Op = dyn_cast<Operator>(V);
4590   if (!Op)
4591     return None;
4592 
4593   // Implementation detail: all the cleverness here should happen without
4594   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4595   // SCEV expressions when possible, and we should not break that.
4596 
4597   switch (Op->getOpcode()) {
4598   case Instruction::Add:
4599   case Instruction::Sub:
4600   case Instruction::Mul:
4601   case Instruction::UDiv:
4602   case Instruction::URem:
4603   case Instruction::And:
4604   case Instruction::Or:
4605   case Instruction::AShr:
4606   case Instruction::Shl:
4607     return BinaryOp(Op);
4608 
4609   case Instruction::Xor:
4610     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4611       // If the RHS of the xor is a signmask, then this is just an add.
4612       // Instcombine turns add of signmask into xor as a strength reduction step.
4613       if (RHSC->getValue().isSignMask())
4614         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4615     return BinaryOp(Op);
4616 
4617   case Instruction::LShr:
4618     // Turn logical shift right of a constant into a unsigned divide.
4619     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4620       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4621 
4622       // If the shift count is not less than the bitwidth, the result of
4623       // the shift is undefined. Don't try to analyze it, because the
4624       // resolution chosen here may differ from the resolution chosen in
4625       // other parts of the compiler.
4626       if (SA->getValue().ult(BitWidth)) {
4627         Constant *X =
4628             ConstantInt::get(SA->getContext(),
4629                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4630         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4631       }
4632     }
4633     return BinaryOp(Op);
4634 
4635   case Instruction::ExtractValue: {
4636     auto *EVI = cast<ExtractValueInst>(Op);
4637     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4638       break;
4639 
4640     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4641     if (!WO)
4642       break;
4643 
4644     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4645     bool Signed = WO->isSigned();
4646     // TODO: Should add nuw/nsw flags for mul as well.
4647     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4648       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4649 
4650     // Now that we know that all uses of the arithmetic-result component of
4651     // CI are guarded by the overflow check, we can go ahead and pretend
4652     // that the arithmetic is non-overflowing.
4653     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4654                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4655   }
4656 
4657   default:
4658     break;
4659   }
4660 
4661   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4662   // semantics as a Sub, return a binary sub expression.
4663   if (auto *II = dyn_cast<IntrinsicInst>(V))
4664     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4665       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4666 
4667   return None;
4668 }
4669 
4670 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4671 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4672 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4673 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4674 /// follows one of the following patterns:
4675 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4676 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4677 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4678 /// we return the type of the truncation operation, and indicate whether the
4679 /// truncated type should be treated as signed/unsigned by setting
4680 /// \p Signed to true/false, respectively.
4681 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4682                                bool &Signed, ScalarEvolution &SE) {
4683   // The case where Op == SymbolicPHI (that is, with no type conversions on
4684   // the way) is handled by the regular add recurrence creating logic and
4685   // would have already been triggered in createAddRecForPHI. Reaching it here
4686   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4687   // because one of the other operands of the SCEVAddExpr updating this PHI is
4688   // not invariant).
4689   //
4690   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4691   // this case predicates that allow us to prove that Op == SymbolicPHI will
4692   // be added.
4693   if (Op == SymbolicPHI)
4694     return nullptr;
4695 
4696   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4697   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4698   if (SourceBits != NewBits)
4699     return nullptr;
4700 
4701   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4702   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4703   if (!SExt && !ZExt)
4704     return nullptr;
4705   const SCEVTruncateExpr *Trunc =
4706       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4707            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4708   if (!Trunc)
4709     return nullptr;
4710   const SCEV *X = Trunc->getOperand();
4711   if (X != SymbolicPHI)
4712     return nullptr;
4713   Signed = SExt != nullptr;
4714   return Trunc->getType();
4715 }
4716 
4717 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4718   if (!PN->getType()->isIntegerTy())
4719     return nullptr;
4720   const Loop *L = LI.getLoopFor(PN->getParent());
4721   if (!L || L->getHeader() != PN->getParent())
4722     return nullptr;
4723   return L;
4724 }
4725 
4726 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4727 // computation that updates the phi follows the following pattern:
4728 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4729 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4730 // If so, try to see if it can be rewritten as an AddRecExpr under some
4731 // Predicates. If successful, return them as a pair. Also cache the results
4732 // of the analysis.
4733 //
4734 // Example usage scenario:
4735 //    Say the Rewriter is called for the following SCEV:
4736 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4737 //    where:
4738 //         %X = phi i64 (%Start, %BEValue)
4739 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4740 //    and call this function with %SymbolicPHI = %X.
4741 //
4742 //    The analysis will find that the value coming around the backedge has
4743 //    the following SCEV:
4744 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4745 //    Upon concluding that this matches the desired pattern, the function
4746 //    will return the pair {NewAddRec, SmallPredsVec} where:
4747 //         NewAddRec = {%Start,+,%Step}
4748 //         SmallPredsVec = {P1, P2, P3} as follows:
4749 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4750 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4751 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4752 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4753 //    under the predicates {P1,P2,P3}.
4754 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4755 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4756 //
4757 // TODO's:
4758 //
4759 // 1) Extend the Induction descriptor to also support inductions that involve
4760 //    casts: When needed (namely, when we are called in the context of the
4761 //    vectorizer induction analysis), a Set of cast instructions will be
4762 //    populated by this method, and provided back to isInductionPHI. This is
4763 //    needed to allow the vectorizer to properly record them to be ignored by
4764 //    the cost model and to avoid vectorizing them (otherwise these casts,
4765 //    which are redundant under the runtime overflow checks, will be
4766 //    vectorized, which can be costly).
4767 //
4768 // 2) Support additional induction/PHISCEV patterns: We also want to support
4769 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4770 //    after the induction update operation (the induction increment):
4771 //
4772 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4773 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4774 //
4775 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4776 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4777 //
4778 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4779 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4780 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4781   SmallVector<const SCEVPredicate *, 3> Predicates;
4782 
4783   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4784   // return an AddRec expression under some predicate.
4785 
4786   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4787   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4788   assert(L && "Expecting an integer loop header phi");
4789 
4790   // The loop may have multiple entrances or multiple exits; we can analyze
4791   // this phi as an addrec if it has a unique entry value and a unique
4792   // backedge value.
4793   Value *BEValueV = nullptr, *StartValueV = nullptr;
4794   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4795     Value *V = PN->getIncomingValue(i);
4796     if (L->contains(PN->getIncomingBlock(i))) {
4797       if (!BEValueV) {
4798         BEValueV = V;
4799       } else if (BEValueV != V) {
4800         BEValueV = nullptr;
4801         break;
4802       }
4803     } else if (!StartValueV) {
4804       StartValueV = V;
4805     } else if (StartValueV != V) {
4806       StartValueV = nullptr;
4807       break;
4808     }
4809   }
4810   if (!BEValueV || !StartValueV)
4811     return None;
4812 
4813   const SCEV *BEValue = getSCEV(BEValueV);
4814 
4815   // If the value coming around the backedge is an add with the symbolic
4816   // value we just inserted, possibly with casts that we can ignore under
4817   // an appropriate runtime guard, then we found a simple induction variable!
4818   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4819   if (!Add)
4820     return None;
4821 
4822   // If there is a single occurrence of the symbolic value, possibly
4823   // casted, replace it with a recurrence.
4824   unsigned FoundIndex = Add->getNumOperands();
4825   Type *TruncTy = nullptr;
4826   bool Signed;
4827   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4828     if ((TruncTy =
4829              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4830       if (FoundIndex == e) {
4831         FoundIndex = i;
4832         break;
4833       }
4834 
4835   if (FoundIndex == Add->getNumOperands())
4836     return None;
4837 
4838   // Create an add with everything but the specified operand.
4839   SmallVector<const SCEV *, 8> Ops;
4840   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4841     if (i != FoundIndex)
4842       Ops.push_back(Add->getOperand(i));
4843   const SCEV *Accum = getAddExpr(Ops);
4844 
4845   // The runtime checks will not be valid if the step amount is
4846   // varying inside the loop.
4847   if (!isLoopInvariant(Accum, L))
4848     return None;
4849 
4850   // *** Part2: Create the predicates
4851 
4852   // Analysis was successful: we have a phi-with-cast pattern for which we
4853   // can return an AddRec expression under the following predicates:
4854   //
4855   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4856   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4857   // P2: An Equal predicate that guarantees that
4858   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4859   // P3: An Equal predicate that guarantees that
4860   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4861   //
4862   // As we next prove, the above predicates guarantee that:
4863   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4864   //
4865   //
4866   // More formally, we want to prove that:
4867   //     Expr(i+1) = Start + (i+1) * Accum
4868   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4869   //
4870   // Given that:
4871   // 1) Expr(0) = Start
4872   // 2) Expr(1) = Start + Accum
4873   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4874   // 3) Induction hypothesis (step i):
4875   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4876   //
4877   // Proof:
4878   //  Expr(i+1) =
4879   //   = Start + (i+1)*Accum
4880   //   = (Start + i*Accum) + Accum
4881   //   = Expr(i) + Accum
4882   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4883   //                                                             :: from step i
4884   //
4885   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4886   //
4887   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4888   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4889   //     + Accum                                                     :: from P3
4890   //
4891   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4892   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4893   //
4894   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4895   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4896   //
4897   // By induction, the same applies to all iterations 1<=i<n:
4898   //
4899 
4900   // Create a truncated addrec for which we will add a no overflow check (P1).
4901   const SCEV *StartVal = getSCEV(StartValueV);
4902   const SCEV *PHISCEV =
4903       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4904                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4905 
4906   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4907   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4908   // will be constant.
4909   //
4910   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4911   // add P1.
4912   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4913     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4914         Signed ? SCEVWrapPredicate::IncrementNSSW
4915                : SCEVWrapPredicate::IncrementNUSW;
4916     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4917     Predicates.push_back(AddRecPred);
4918   }
4919 
4920   // Create the Equal Predicates P2,P3:
4921 
4922   // It is possible that the predicates P2 and/or P3 are computable at
4923   // compile time due to StartVal and/or Accum being constants.
4924   // If either one is, then we can check that now and escape if either P2
4925   // or P3 is false.
4926 
4927   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4928   // for each of StartVal and Accum
4929   auto getExtendedExpr = [&](const SCEV *Expr,
4930                              bool CreateSignExtend) -> const SCEV * {
4931     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4932     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4933     const SCEV *ExtendedExpr =
4934         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4935                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4936     return ExtendedExpr;
4937   };
4938 
4939   // Given:
4940   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4941   //               = getExtendedExpr(Expr)
4942   // Determine whether the predicate P: Expr == ExtendedExpr
4943   // is known to be false at compile time
4944   auto PredIsKnownFalse = [&](const SCEV *Expr,
4945                               const SCEV *ExtendedExpr) -> bool {
4946     return Expr != ExtendedExpr &&
4947            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4948   };
4949 
4950   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4951   if (PredIsKnownFalse(StartVal, StartExtended)) {
4952     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4953     return None;
4954   }
4955 
4956   // The Step is always Signed (because the overflow checks are either
4957   // NSSW or NUSW)
4958   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4959   if (PredIsKnownFalse(Accum, AccumExtended)) {
4960     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4961     return None;
4962   }
4963 
4964   auto AppendPredicate = [&](const SCEV *Expr,
4965                              const SCEV *ExtendedExpr) -> void {
4966     if (Expr != ExtendedExpr &&
4967         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4968       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4969       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4970       Predicates.push_back(Pred);
4971     }
4972   };
4973 
4974   AppendPredicate(StartVal, StartExtended);
4975   AppendPredicate(Accum, AccumExtended);
4976 
4977   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4978   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4979   // into NewAR if it will also add the runtime overflow checks specified in
4980   // Predicates.
4981   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4982 
4983   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4984       std::make_pair(NewAR, Predicates);
4985   // Remember the result of the analysis for this SCEV at this locayyytion.
4986   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4987   return PredRewrite;
4988 }
4989 
4990 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4991 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4992   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4993   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4994   if (!L)
4995     return None;
4996 
4997   // Check to see if we already analyzed this PHI.
4998   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4999   if (I != PredicatedSCEVRewrites.end()) {
5000     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5001         I->second;
5002     // Analysis was done before and failed to create an AddRec:
5003     if (Rewrite.first == SymbolicPHI)
5004       return None;
5005     // Analysis was done before and succeeded to create an AddRec under
5006     // a predicate:
5007     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5008     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5009     return Rewrite;
5010   }
5011 
5012   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5013     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5014 
5015   // Record in the cache that the analysis failed
5016   if (!Rewrite) {
5017     SmallVector<const SCEVPredicate *, 3> Predicates;
5018     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5019     return None;
5020   }
5021 
5022   return Rewrite;
5023 }
5024 
5025 // FIXME: This utility is currently required because the Rewriter currently
5026 // does not rewrite this expression:
5027 // {0, +, (sext ix (trunc iy to ix) to iy)}
5028 // into {0, +, %step},
5029 // even when the following Equal predicate exists:
5030 // "%step == (sext ix (trunc iy to ix) to iy)".
5031 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5032     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5033   if (AR1 == AR2)
5034     return true;
5035 
5036   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5037     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5038         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5039       return false;
5040     return true;
5041   };
5042 
5043   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5044       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5045     return false;
5046   return true;
5047 }
5048 
5049 /// A helper function for createAddRecFromPHI to handle simple cases.
5050 ///
5051 /// This function tries to find an AddRec expression for the simplest (yet most
5052 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5053 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5054 /// technique for finding the AddRec expression.
5055 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5056                                                       Value *BEValueV,
5057                                                       Value *StartValueV) {
5058   const Loop *L = LI.getLoopFor(PN->getParent());
5059   assert(L && L->getHeader() == PN->getParent());
5060   assert(BEValueV && StartValueV);
5061 
5062   auto BO = MatchBinaryOp(BEValueV, DT);
5063   if (!BO)
5064     return nullptr;
5065 
5066   if (BO->Opcode != Instruction::Add)
5067     return nullptr;
5068 
5069   const SCEV *Accum = nullptr;
5070   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5071     Accum = getSCEV(BO->RHS);
5072   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5073     Accum = getSCEV(BO->LHS);
5074 
5075   if (!Accum)
5076     return nullptr;
5077 
5078   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5079   if (BO->IsNUW)
5080     Flags = setFlags(Flags, SCEV::FlagNUW);
5081   if (BO->IsNSW)
5082     Flags = setFlags(Flags, SCEV::FlagNSW);
5083 
5084   const SCEV *StartVal = getSCEV(StartValueV);
5085   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5086 
5087   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5088 
5089   // We can add Flags to the post-inc expression only if we
5090   // know that it is *undefined behavior* for BEValueV to
5091   // overflow.
5092   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5093     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5094       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5095 
5096   return PHISCEV;
5097 }
5098 
5099 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5100   const Loop *L = LI.getLoopFor(PN->getParent());
5101   if (!L || L->getHeader() != PN->getParent())
5102     return nullptr;
5103 
5104   // The loop may have multiple entrances or multiple exits; we can analyze
5105   // this phi as an addrec if it has a unique entry value and a unique
5106   // backedge value.
5107   Value *BEValueV = nullptr, *StartValueV = nullptr;
5108   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5109     Value *V = PN->getIncomingValue(i);
5110     if (L->contains(PN->getIncomingBlock(i))) {
5111       if (!BEValueV) {
5112         BEValueV = V;
5113       } else if (BEValueV != V) {
5114         BEValueV = nullptr;
5115         break;
5116       }
5117     } else if (!StartValueV) {
5118       StartValueV = V;
5119     } else if (StartValueV != V) {
5120       StartValueV = nullptr;
5121       break;
5122     }
5123   }
5124   if (!BEValueV || !StartValueV)
5125     return nullptr;
5126 
5127   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5128          "PHI node already processed?");
5129 
5130   // First, try to find AddRec expression without creating a fictituos symbolic
5131   // value for PN.
5132   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5133     return S;
5134 
5135   // Handle PHI node value symbolically.
5136   const SCEV *SymbolicName = getUnknown(PN);
5137   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5138 
5139   // Using this symbolic name for the PHI, analyze the value coming around
5140   // the back-edge.
5141   const SCEV *BEValue = getSCEV(BEValueV);
5142 
5143   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5144   // has a special value for the first iteration of the loop.
5145 
5146   // If the value coming around the backedge is an add with the symbolic
5147   // value we just inserted, then we found a simple induction variable!
5148   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5149     // If there is a single occurrence of the symbolic value, replace it
5150     // with a recurrence.
5151     unsigned FoundIndex = Add->getNumOperands();
5152     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5153       if (Add->getOperand(i) == SymbolicName)
5154         if (FoundIndex == e) {
5155           FoundIndex = i;
5156           break;
5157         }
5158 
5159     if (FoundIndex != Add->getNumOperands()) {
5160       // Create an add with everything but the specified operand.
5161       SmallVector<const SCEV *, 8> Ops;
5162       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5163         if (i != FoundIndex)
5164           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5165                                                              L, *this));
5166       const SCEV *Accum = getAddExpr(Ops);
5167 
5168       // This is not a valid addrec if the step amount is varying each
5169       // loop iteration, but is not itself an addrec in this loop.
5170       if (isLoopInvariant(Accum, L) ||
5171           (isa<SCEVAddRecExpr>(Accum) &&
5172            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5173         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5174 
5175         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5176           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5177             if (BO->IsNUW)
5178               Flags = setFlags(Flags, SCEV::FlagNUW);
5179             if (BO->IsNSW)
5180               Flags = setFlags(Flags, SCEV::FlagNSW);
5181           }
5182         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5183           // If the increment is an inbounds GEP, then we know the address
5184           // space cannot be wrapped around. We cannot make any guarantee
5185           // about signed or unsigned overflow because pointers are
5186           // unsigned but we may have a negative index from the base
5187           // pointer. We can guarantee that no unsigned wrap occurs if the
5188           // indices form a positive value.
5189           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5190             Flags = setFlags(Flags, SCEV::FlagNW);
5191 
5192             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5193             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5194               Flags = setFlags(Flags, SCEV::FlagNUW);
5195           }
5196 
5197           // We cannot transfer nuw and nsw flags from subtraction
5198           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5199           // for instance.
5200         }
5201 
5202         const SCEV *StartVal = getSCEV(StartValueV);
5203         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5204 
5205         // Okay, for the entire analysis of this edge we assumed the PHI
5206         // to be symbolic.  We now need to go back and purge all of the
5207         // entries for the scalars that use the symbolic expression.
5208         forgetSymbolicName(PN, SymbolicName);
5209         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5210 
5211         // We can add Flags to the post-inc expression only if we
5212         // know that it is *undefined behavior* for BEValueV to
5213         // overflow.
5214         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5215           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5216             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5217 
5218         return PHISCEV;
5219       }
5220     }
5221   } else {
5222     // Otherwise, this could be a loop like this:
5223     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5224     // In this case, j = {1,+,1}  and BEValue is j.
5225     // Because the other in-value of i (0) fits the evolution of BEValue
5226     // i really is an addrec evolution.
5227     //
5228     // We can generalize this saying that i is the shifted value of BEValue
5229     // by one iteration:
5230     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5231     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5232     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5233     if (Shifted != getCouldNotCompute() &&
5234         Start != getCouldNotCompute()) {
5235       const SCEV *StartVal = getSCEV(StartValueV);
5236       if (Start == StartVal) {
5237         // Okay, for the entire analysis of this edge we assumed the PHI
5238         // to be symbolic.  We now need to go back and purge all of the
5239         // entries for the scalars that use the symbolic expression.
5240         forgetSymbolicName(PN, SymbolicName);
5241         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5242         return Shifted;
5243       }
5244     }
5245   }
5246 
5247   // Remove the temporary PHI node SCEV that has been inserted while intending
5248   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5249   // as it will prevent later (possibly simpler) SCEV expressions to be added
5250   // to the ValueExprMap.
5251   eraseValueFromMap(PN);
5252 
5253   return nullptr;
5254 }
5255 
5256 // Checks if the SCEV S is available at BB.  S is considered available at BB
5257 // if S can be materialized at BB without introducing a fault.
5258 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5259                                BasicBlock *BB) {
5260   struct CheckAvailable {
5261     bool TraversalDone = false;
5262     bool Available = true;
5263 
5264     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5265     BasicBlock *BB = nullptr;
5266     DominatorTree &DT;
5267 
5268     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5269       : L(L), BB(BB), DT(DT) {}
5270 
5271     bool setUnavailable() {
5272       TraversalDone = true;
5273       Available = false;
5274       return false;
5275     }
5276 
5277     bool follow(const SCEV *S) {
5278       switch (S->getSCEVType()) {
5279       case scConstant:
5280       case scPtrToInt:
5281       case scTruncate:
5282       case scZeroExtend:
5283       case scSignExtend:
5284       case scAddExpr:
5285       case scMulExpr:
5286       case scUMaxExpr:
5287       case scSMaxExpr:
5288       case scUMinExpr:
5289       case scSMinExpr:
5290         // These expressions are available if their operand(s) is/are.
5291         return true;
5292 
5293       case scAddRecExpr: {
5294         // We allow add recurrences that are on the loop BB is in, or some
5295         // outer loop.  This guarantees availability because the value of the
5296         // add recurrence at BB is simply the "current" value of the induction
5297         // variable.  We can relax this in the future; for instance an add
5298         // recurrence on a sibling dominating loop is also available at BB.
5299         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5300         if (L && (ARLoop == L || ARLoop->contains(L)))
5301           return true;
5302 
5303         return setUnavailable();
5304       }
5305 
5306       case scUnknown: {
5307         // For SCEVUnknown, we check for simple dominance.
5308         const auto *SU = cast<SCEVUnknown>(S);
5309         Value *V = SU->getValue();
5310 
5311         if (isa<Argument>(V))
5312           return false;
5313 
5314         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5315           return false;
5316 
5317         return setUnavailable();
5318       }
5319 
5320       case scUDivExpr:
5321       case scCouldNotCompute:
5322         // We do not try to smart about these at all.
5323         return setUnavailable();
5324       }
5325       llvm_unreachable("Unknown SCEV kind!");
5326     }
5327 
5328     bool isDone() { return TraversalDone; }
5329   };
5330 
5331   CheckAvailable CA(L, BB, DT);
5332   SCEVTraversal<CheckAvailable> ST(CA);
5333 
5334   ST.visitAll(S);
5335   return CA.Available;
5336 }
5337 
5338 // Try to match a control flow sequence that branches out at BI and merges back
5339 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5340 // match.
5341 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5342                           Value *&C, Value *&LHS, Value *&RHS) {
5343   C = BI->getCondition();
5344 
5345   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5346   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5347 
5348   if (!LeftEdge.isSingleEdge())
5349     return false;
5350 
5351   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5352 
5353   Use &LeftUse = Merge->getOperandUse(0);
5354   Use &RightUse = Merge->getOperandUse(1);
5355 
5356   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5357     LHS = LeftUse;
5358     RHS = RightUse;
5359     return true;
5360   }
5361 
5362   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5363     LHS = RightUse;
5364     RHS = LeftUse;
5365     return true;
5366   }
5367 
5368   return false;
5369 }
5370 
5371 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5372   auto IsReachable =
5373       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5374   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5375     const Loop *L = LI.getLoopFor(PN->getParent());
5376 
5377     // We don't want to break LCSSA, even in a SCEV expression tree.
5378     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5379       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5380         return nullptr;
5381 
5382     // Try to match
5383     //
5384     //  br %cond, label %left, label %right
5385     // left:
5386     //  br label %merge
5387     // right:
5388     //  br label %merge
5389     // merge:
5390     //  V = phi [ %x, %left ], [ %y, %right ]
5391     //
5392     // as "select %cond, %x, %y"
5393 
5394     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5395     assert(IDom && "At least the entry block should dominate PN");
5396 
5397     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5398     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5399 
5400     if (BI && BI->isConditional() &&
5401         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5402         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5403         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5404       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5405   }
5406 
5407   return nullptr;
5408 }
5409 
5410 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5411   if (const SCEV *S = createAddRecFromPHI(PN))
5412     return S;
5413 
5414   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5415     return S;
5416 
5417   // If the PHI has a single incoming value, follow that value, unless the
5418   // PHI's incoming blocks are in a different loop, in which case doing so
5419   // risks breaking LCSSA form. Instcombine would normally zap these, but
5420   // it doesn't have DominatorTree information, so it may miss cases.
5421   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5422     if (LI.replacementPreservesLCSSAForm(PN, V))
5423       return getSCEV(V);
5424 
5425   // If it's not a loop phi, we can't handle it yet.
5426   return getUnknown(PN);
5427 }
5428 
5429 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5430                                                       Value *Cond,
5431                                                       Value *TrueVal,
5432                                                       Value *FalseVal) {
5433   // Handle "constant" branch or select. This can occur for instance when a
5434   // loop pass transforms an inner loop and moves on to process the outer loop.
5435   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5436     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5437 
5438   // Try to match some simple smax or umax patterns.
5439   auto *ICI = dyn_cast<ICmpInst>(Cond);
5440   if (!ICI)
5441     return getUnknown(I);
5442 
5443   Value *LHS = ICI->getOperand(0);
5444   Value *RHS = ICI->getOperand(1);
5445 
5446   switch (ICI->getPredicate()) {
5447   case ICmpInst::ICMP_SLT:
5448   case ICmpInst::ICMP_SLE:
5449     std::swap(LHS, RHS);
5450     LLVM_FALLTHROUGH;
5451   case ICmpInst::ICMP_SGT:
5452   case ICmpInst::ICMP_SGE:
5453     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5454     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5455     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5456       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5457       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5458       const SCEV *LA = getSCEV(TrueVal);
5459       const SCEV *RA = getSCEV(FalseVal);
5460       const SCEV *LDiff = getMinusSCEV(LA, LS);
5461       const SCEV *RDiff = getMinusSCEV(RA, RS);
5462       if (LDiff == RDiff)
5463         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5464       LDiff = getMinusSCEV(LA, RS);
5465       RDiff = getMinusSCEV(RA, LS);
5466       if (LDiff == RDiff)
5467         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5468     }
5469     break;
5470   case ICmpInst::ICMP_ULT:
5471   case ICmpInst::ICMP_ULE:
5472     std::swap(LHS, RHS);
5473     LLVM_FALLTHROUGH;
5474   case ICmpInst::ICMP_UGT:
5475   case ICmpInst::ICMP_UGE:
5476     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5477     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5478     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5479       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5480       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5481       const SCEV *LA = getSCEV(TrueVal);
5482       const SCEV *RA = getSCEV(FalseVal);
5483       const SCEV *LDiff = getMinusSCEV(LA, LS);
5484       const SCEV *RDiff = getMinusSCEV(RA, RS);
5485       if (LDiff == RDiff)
5486         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5487       LDiff = getMinusSCEV(LA, RS);
5488       RDiff = getMinusSCEV(RA, LS);
5489       if (LDiff == RDiff)
5490         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5491     }
5492     break;
5493   case ICmpInst::ICMP_NE:
5494     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5495     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5496         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5497       const SCEV *One = getOne(I->getType());
5498       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5499       const SCEV *LA = getSCEV(TrueVal);
5500       const SCEV *RA = getSCEV(FalseVal);
5501       const SCEV *LDiff = getMinusSCEV(LA, LS);
5502       const SCEV *RDiff = getMinusSCEV(RA, One);
5503       if (LDiff == RDiff)
5504         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5505     }
5506     break;
5507   case ICmpInst::ICMP_EQ:
5508     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5509     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5510         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5511       const SCEV *One = getOne(I->getType());
5512       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5513       const SCEV *LA = getSCEV(TrueVal);
5514       const SCEV *RA = getSCEV(FalseVal);
5515       const SCEV *LDiff = getMinusSCEV(LA, One);
5516       const SCEV *RDiff = getMinusSCEV(RA, LS);
5517       if (LDiff == RDiff)
5518         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5519     }
5520     break;
5521   default:
5522     break;
5523   }
5524 
5525   return getUnknown(I);
5526 }
5527 
5528 /// Expand GEP instructions into add and multiply operations. This allows them
5529 /// to be analyzed by regular SCEV code.
5530 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5531   // Don't attempt to analyze GEPs over unsized objects.
5532   if (!GEP->getSourceElementType()->isSized())
5533     return getUnknown(GEP);
5534 
5535   SmallVector<const SCEV *, 4> IndexExprs;
5536   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5537     IndexExprs.push_back(getSCEV(*Index));
5538   return getGEPExpr(GEP, IndexExprs);
5539 }
5540 
5541 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5542   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5543     return C->getAPInt().countTrailingZeros();
5544 
5545   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5546     return GetMinTrailingZeros(I->getOperand());
5547 
5548   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5549     return std::min(GetMinTrailingZeros(T->getOperand()),
5550                     (uint32_t)getTypeSizeInBits(T->getType()));
5551 
5552   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5553     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5554     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5555                ? getTypeSizeInBits(E->getType())
5556                : OpRes;
5557   }
5558 
5559   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5560     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5561     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5562                ? getTypeSizeInBits(E->getType())
5563                : OpRes;
5564   }
5565 
5566   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5567     // The result is the min of all operands results.
5568     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5569     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5570       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5571     return MinOpRes;
5572   }
5573 
5574   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5575     // The result is the sum of all operands results.
5576     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5577     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5578     for (unsigned i = 1, e = M->getNumOperands();
5579          SumOpRes != BitWidth && i != e; ++i)
5580       SumOpRes =
5581           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5582     return SumOpRes;
5583   }
5584 
5585   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5586     // The result is the min of all operands results.
5587     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5588     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5589       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5590     return MinOpRes;
5591   }
5592 
5593   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5594     // The result is the min of all operands results.
5595     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5596     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5597       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5598     return MinOpRes;
5599   }
5600 
5601   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5602     // The result is the min of all operands results.
5603     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5604     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5605       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5606     return MinOpRes;
5607   }
5608 
5609   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5610     // For a SCEVUnknown, ask ValueTracking.
5611     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5612     return Known.countMinTrailingZeros();
5613   }
5614 
5615   // SCEVUDivExpr
5616   return 0;
5617 }
5618 
5619 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5620   auto I = MinTrailingZerosCache.find(S);
5621   if (I != MinTrailingZerosCache.end())
5622     return I->second;
5623 
5624   uint32_t Result = GetMinTrailingZerosImpl(S);
5625   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5626   assert(InsertPair.second && "Should insert a new key");
5627   return InsertPair.first->second;
5628 }
5629 
5630 /// Helper method to assign a range to V from metadata present in the IR.
5631 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5632   if (Instruction *I = dyn_cast<Instruction>(V))
5633     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5634       return getConstantRangeFromMetadata(*MD);
5635 
5636   return None;
5637 }
5638 
5639 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5640                                      SCEV::NoWrapFlags Flags) {
5641   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5642     AddRec->setNoWrapFlags(Flags);
5643     UnsignedRanges.erase(AddRec);
5644     SignedRanges.erase(AddRec);
5645   }
5646 }
5647 
5648 ConstantRange ScalarEvolution::
5649 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5650   const DataLayout &DL = getDataLayout();
5651 
5652   unsigned BitWidth = getTypeSizeInBits(U->getType());
5653   ConstantRange CR(BitWidth, /*isFullSet=*/true);
5654 
5655   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5656   // use information about the trip count to improve our available range.  Note
5657   // that the trip count independent cases are already handled by known bits.
5658   // WARNING: The definition of recurrence used here is subtly different than
5659   // the one used by AddRec (and thus most of this file).  Step is allowed to
5660   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5661   // and other addrecs in the same loop (for non-affine addrecs).  The code
5662   // below intentionally handles the case where step is not loop invariant.
5663   auto *P = dyn_cast<PHINode>(U->getValue());
5664   if (!P)
5665     return CR;
5666 
5667   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5668   // even the values that are not available in these blocks may come from them,
5669   // and this leads to false-positive recurrence test.
5670   for (auto *Pred : predecessors(P->getParent()))
5671     if (!DT.isReachableFromEntry(Pred))
5672       return CR;
5673 
5674   BinaryOperator *BO;
5675   Value *Start, *Step;
5676   if (!matchSimpleRecurrence(P, BO, Start, Step))
5677     return CR;
5678 
5679   // If we found a recurrence in reachable code, we must be in a loop. Note
5680   // that BO might be in some subloop of L, and that's completely okay.
5681   auto *L = LI.getLoopFor(P->getParent());
5682   assert(L && L->getHeader() == P->getParent());
5683   if (!L->contains(BO->getParent()))
5684     // NOTE: This bailout should be an assert instead.  However, asserting
5685     // the condition here exposes a case where LoopFusion is querying SCEV
5686     // with malformed loop information during the midst of the transform.
5687     // There doesn't appear to be an obvious fix, so for the moment bailout
5688     // until the caller issue can be fixed.  PR49566 tracks the bug.
5689     return CR;
5690 
5691   // TODO: Handle ashr and lshr cases to increase minimum value reported
5692   if (BO->getOpcode() != Instruction::Shl || BO->getOperand(0) != P)
5693     return CR;
5694 
5695   unsigned TC = getSmallConstantMaxTripCount(L);
5696   if (!TC || TC >= BitWidth)
5697     return CR;
5698 
5699   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5700   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5701   assert(KnownStart.getBitWidth() == BitWidth &&
5702          KnownStep.getBitWidth() == BitWidth);
5703 
5704   // Compute total shift amount, being careful of overflow and bitwidths.
5705   auto MaxShiftAmt = KnownStep.getMaxValue();
5706   APInt TCAP(BitWidth, TC-1);
5707   bool Overflow = false;
5708   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5709   if (Overflow)
5710     return CR;
5711 
5712   // Iff no bits are shifted out, value increases on every shift.
5713   auto KnownEnd = KnownBits::shl(KnownStart,
5714                                  KnownBits::makeConstant(TotalShift));
5715   if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5716     CR = CR.intersectWith(ConstantRange(KnownStart.getMinValue(),
5717                                         KnownEnd.getMaxValue() + 1));
5718   return CR;
5719 }
5720 
5721 
5722 
5723 /// Determine the range for a particular SCEV.  If SignHint is
5724 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5725 /// with a "cleaner" unsigned (resp. signed) representation.
5726 const ConstantRange &
5727 ScalarEvolution::getRangeRef(const SCEV *S,
5728                              ScalarEvolution::RangeSignHint SignHint) {
5729   DenseMap<const SCEV *, ConstantRange> &Cache =
5730       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5731                                                        : SignedRanges;
5732   ConstantRange::PreferredRangeType RangeType =
5733       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5734           ? ConstantRange::Unsigned : ConstantRange::Signed;
5735 
5736   // See if we've computed this range already.
5737   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5738   if (I != Cache.end())
5739     return I->second;
5740 
5741   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5742     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5743 
5744   unsigned BitWidth = getTypeSizeInBits(S->getType());
5745   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5746   using OBO = OverflowingBinaryOperator;
5747 
5748   // If the value has known zeros, the maximum value will have those known zeros
5749   // as well.
5750   uint32_t TZ = GetMinTrailingZeros(S);
5751   if (TZ != 0) {
5752     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5753       ConservativeResult =
5754           ConstantRange(APInt::getMinValue(BitWidth),
5755                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5756     else
5757       ConservativeResult = ConstantRange(
5758           APInt::getSignedMinValue(BitWidth),
5759           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5760   }
5761 
5762   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5763     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5764     unsigned WrapType = OBO::AnyWrap;
5765     if (Add->hasNoSignedWrap())
5766       WrapType |= OBO::NoSignedWrap;
5767     if (Add->hasNoUnsignedWrap())
5768       WrapType |= OBO::NoUnsignedWrap;
5769     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5770       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5771                           WrapType, RangeType);
5772     return setRange(Add, SignHint,
5773                     ConservativeResult.intersectWith(X, RangeType));
5774   }
5775 
5776   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5777     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5778     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5779       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5780     return setRange(Mul, SignHint,
5781                     ConservativeResult.intersectWith(X, RangeType));
5782   }
5783 
5784   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5785     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5786     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5787       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5788     return setRange(SMax, SignHint,
5789                     ConservativeResult.intersectWith(X, RangeType));
5790   }
5791 
5792   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5793     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5794     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5795       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5796     return setRange(UMax, SignHint,
5797                     ConservativeResult.intersectWith(X, RangeType));
5798   }
5799 
5800   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5801     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5802     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5803       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5804     return setRange(SMin, SignHint,
5805                     ConservativeResult.intersectWith(X, RangeType));
5806   }
5807 
5808   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5809     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5810     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5811       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5812     return setRange(UMin, SignHint,
5813                     ConservativeResult.intersectWith(X, RangeType));
5814   }
5815 
5816   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5817     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5818     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5819     return setRange(UDiv, SignHint,
5820                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5821   }
5822 
5823   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5824     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5825     return setRange(ZExt, SignHint,
5826                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5827                                                      RangeType));
5828   }
5829 
5830   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5831     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5832     return setRange(SExt, SignHint,
5833                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5834                                                      RangeType));
5835   }
5836 
5837   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5838     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5839     return setRange(PtrToInt, SignHint, X);
5840   }
5841 
5842   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5843     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5844     return setRange(Trunc, SignHint,
5845                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5846                                                      RangeType));
5847   }
5848 
5849   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5850     // If there's no unsigned wrap, the value will never be less than its
5851     // initial value.
5852     if (AddRec->hasNoUnsignedWrap()) {
5853       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5854       if (!UnsignedMinValue.isNullValue())
5855         ConservativeResult = ConservativeResult.intersectWith(
5856             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5857     }
5858 
5859     // If there's no signed wrap, and all the operands except initial value have
5860     // the same sign or zero, the value won't ever be:
5861     // 1: smaller than initial value if operands are non negative,
5862     // 2: bigger than initial value if operands are non positive.
5863     // For both cases, value can not cross signed min/max boundary.
5864     if (AddRec->hasNoSignedWrap()) {
5865       bool AllNonNeg = true;
5866       bool AllNonPos = true;
5867       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5868         if (!isKnownNonNegative(AddRec->getOperand(i)))
5869           AllNonNeg = false;
5870         if (!isKnownNonPositive(AddRec->getOperand(i)))
5871           AllNonPos = false;
5872       }
5873       if (AllNonNeg)
5874         ConservativeResult = ConservativeResult.intersectWith(
5875             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5876                                        APInt::getSignedMinValue(BitWidth)),
5877             RangeType);
5878       else if (AllNonPos)
5879         ConservativeResult = ConservativeResult.intersectWith(
5880             ConstantRange::getNonEmpty(
5881                 APInt::getSignedMinValue(BitWidth),
5882                 getSignedRangeMax(AddRec->getStart()) + 1),
5883             RangeType);
5884     }
5885 
5886     // TODO: non-affine addrec
5887     if (AddRec->isAffine()) {
5888       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5889       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5890           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5891         auto RangeFromAffine = getRangeForAffineAR(
5892             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5893             BitWidth);
5894         ConservativeResult =
5895             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5896 
5897         auto RangeFromFactoring = getRangeViaFactoring(
5898             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5899             BitWidth);
5900         ConservativeResult =
5901             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5902       }
5903 
5904       // Now try symbolic BE count and more powerful methods.
5905       if (UseExpensiveRangeSharpening) {
5906         const SCEV *SymbolicMaxBECount =
5907             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5908         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5909             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5910             AddRec->hasNoSelfWrap()) {
5911           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5912               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5913           ConservativeResult =
5914               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5915         }
5916       }
5917     }
5918 
5919     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5920   }
5921 
5922   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5923 
5924     // Check if the IR explicitly contains !range metadata.
5925     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5926     if (MDRange.hasValue())
5927       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5928                                                             RangeType);
5929 
5930     // Use facts about recurrences in the underlying IR.  Note that add
5931     // recurrences are AddRecExprs and thus don't hit this path.  This
5932     // primarily handles shift recurrences.
5933     auto CR = getRangeForUnknownRecurrence(U);
5934     ConservativeResult = ConservativeResult.intersectWith(CR);
5935 
5936     // See if ValueTracking can give us a useful range.
5937     const DataLayout &DL = getDataLayout();
5938     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5939     if (Known.getBitWidth() != BitWidth)
5940       Known = Known.zextOrTrunc(BitWidth);
5941 
5942     // ValueTracking may be able to compute a tighter result for the number of
5943     // sign bits than for the value of those sign bits.
5944     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5945     if (U->getType()->isPointerTy()) {
5946       // If the pointer size is larger than the index size type, this can cause
5947       // NS to be larger than BitWidth. So compensate for this.
5948       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5949       int ptrIdxDiff = ptrSize - BitWidth;
5950       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5951         NS -= ptrIdxDiff;
5952     }
5953 
5954     if (NS > 1) {
5955       // If we know any of the sign bits, we know all of the sign bits.
5956       if (!Known.Zero.getHiBits(NS).isNullValue())
5957         Known.Zero.setHighBits(NS);
5958       if (!Known.One.getHiBits(NS).isNullValue())
5959         Known.One.setHighBits(NS);
5960     }
5961 
5962     if (Known.getMinValue() != Known.getMaxValue() + 1)
5963       ConservativeResult = ConservativeResult.intersectWith(
5964           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5965           RangeType);
5966     if (NS > 1)
5967       ConservativeResult = ConservativeResult.intersectWith(
5968           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5969                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5970           RangeType);
5971 
5972     // A range of Phi is a subset of union of all ranges of its input.
5973     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5974       // Make sure that we do not run over cycled Phis.
5975       if (PendingPhiRanges.insert(Phi).second) {
5976         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5977         for (auto &Op : Phi->operands()) {
5978           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5979           RangeFromOps = RangeFromOps.unionWith(OpRange);
5980           // No point to continue if we already have a full set.
5981           if (RangeFromOps.isFullSet())
5982             break;
5983         }
5984         ConservativeResult =
5985             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5986         bool Erased = PendingPhiRanges.erase(Phi);
5987         assert(Erased && "Failed to erase Phi properly?");
5988         (void) Erased;
5989       }
5990     }
5991 
5992     return setRange(U, SignHint, std::move(ConservativeResult));
5993   }
5994 
5995   return setRange(S, SignHint, std::move(ConservativeResult));
5996 }
5997 
5998 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5999 // values that the expression can take. Initially, the expression has a value
6000 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6001 // argument defines if we treat Step as signed or unsigned.
6002 static ConstantRange getRangeForAffineARHelper(APInt Step,
6003                                                const ConstantRange &StartRange,
6004                                                const APInt &MaxBECount,
6005                                                unsigned BitWidth, bool Signed) {
6006   // If either Step or MaxBECount is 0, then the expression won't change, and we
6007   // just need to return the initial range.
6008   if (Step == 0 || MaxBECount == 0)
6009     return StartRange;
6010 
6011   // If we don't know anything about the initial value (i.e. StartRange is
6012   // FullRange), then we don't know anything about the final range either.
6013   // Return FullRange.
6014   if (StartRange.isFullSet())
6015     return ConstantRange::getFull(BitWidth);
6016 
6017   // If Step is signed and negative, then we use its absolute value, but we also
6018   // note that we're moving in the opposite direction.
6019   bool Descending = Signed && Step.isNegative();
6020 
6021   if (Signed)
6022     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6023     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6024     // This equations hold true due to the well-defined wrap-around behavior of
6025     // APInt.
6026     Step = Step.abs();
6027 
6028   // Check if Offset is more than full span of BitWidth. If it is, the
6029   // expression is guaranteed to overflow.
6030   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6031     return ConstantRange::getFull(BitWidth);
6032 
6033   // Offset is by how much the expression can change. Checks above guarantee no
6034   // overflow here.
6035   APInt Offset = Step * MaxBECount;
6036 
6037   // Minimum value of the final range will match the minimal value of StartRange
6038   // if the expression is increasing and will be decreased by Offset otherwise.
6039   // Maximum value of the final range will match the maximal value of StartRange
6040   // if the expression is decreasing and will be increased by Offset otherwise.
6041   APInt StartLower = StartRange.getLower();
6042   APInt StartUpper = StartRange.getUpper() - 1;
6043   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6044                                    : (StartUpper + std::move(Offset));
6045 
6046   // It's possible that the new minimum/maximum value will fall into the initial
6047   // range (due to wrap around). This means that the expression can take any
6048   // value in this bitwidth, and we have to return full range.
6049   if (StartRange.contains(MovedBoundary))
6050     return ConstantRange::getFull(BitWidth);
6051 
6052   APInt NewLower =
6053       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6054   APInt NewUpper =
6055       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6056   NewUpper += 1;
6057 
6058   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6059   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6060 }
6061 
6062 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6063                                                    const SCEV *Step,
6064                                                    const SCEV *MaxBECount,
6065                                                    unsigned BitWidth) {
6066   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6067          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6068          "Precondition!");
6069 
6070   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6071   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6072 
6073   // First, consider step signed.
6074   ConstantRange StartSRange = getSignedRange(Start);
6075   ConstantRange StepSRange = getSignedRange(Step);
6076 
6077   // If Step can be both positive and negative, we need to find ranges for the
6078   // maximum absolute step values in both directions and union them.
6079   ConstantRange SR =
6080       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6081                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6082   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6083                                               StartSRange, MaxBECountValue,
6084                                               BitWidth, /* Signed = */ true));
6085 
6086   // Next, consider step unsigned.
6087   ConstantRange UR = getRangeForAffineARHelper(
6088       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6089       MaxBECountValue, BitWidth, /* Signed = */ false);
6090 
6091   // Finally, intersect signed and unsigned ranges.
6092   return SR.intersectWith(UR, ConstantRange::Smallest);
6093 }
6094 
6095 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6096     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6097     ScalarEvolution::RangeSignHint SignHint) {
6098   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6099   assert(AddRec->hasNoSelfWrap() &&
6100          "This only works for non-self-wrapping AddRecs!");
6101   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6102   const SCEV *Step = AddRec->getStepRecurrence(*this);
6103   // Only deal with constant step to save compile time.
6104   if (!isa<SCEVConstant>(Step))
6105     return ConstantRange::getFull(BitWidth);
6106   // Let's make sure that we can prove that we do not self-wrap during
6107   // MaxBECount iterations. We need this because MaxBECount is a maximum
6108   // iteration count estimate, and we might infer nw from some exit for which we
6109   // do not know max exit count (or any other side reasoning).
6110   // TODO: Turn into assert at some point.
6111   if (getTypeSizeInBits(MaxBECount->getType()) >
6112       getTypeSizeInBits(AddRec->getType()))
6113     return ConstantRange::getFull(BitWidth);
6114   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6115   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6116   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6117   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6118   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6119                                          MaxItersWithoutWrap))
6120     return ConstantRange::getFull(BitWidth);
6121 
6122   ICmpInst::Predicate LEPred =
6123       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6124   ICmpInst::Predicate GEPred =
6125       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6126   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6127 
6128   // We know that there is no self-wrap. Let's take Start and End values and
6129   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6130   // the iteration. They either lie inside the range [Min(Start, End),
6131   // Max(Start, End)] or outside it:
6132   //
6133   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6134   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6135   //
6136   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6137   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6138   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6139   // Start <= End and step is positive, or Start >= End and step is negative.
6140   const SCEV *Start = AddRec->getStart();
6141   ConstantRange StartRange = getRangeRef(Start, SignHint);
6142   ConstantRange EndRange = getRangeRef(End, SignHint);
6143   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6144   // If they already cover full iteration space, we will know nothing useful
6145   // even if we prove what we want to prove.
6146   if (RangeBetween.isFullSet())
6147     return RangeBetween;
6148   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6149   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6150                                : RangeBetween.isWrappedSet();
6151   if (IsWrappedSet)
6152     return ConstantRange::getFull(BitWidth);
6153 
6154   if (isKnownPositive(Step) &&
6155       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6156     return RangeBetween;
6157   else if (isKnownNegative(Step) &&
6158            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6159     return RangeBetween;
6160   return ConstantRange::getFull(BitWidth);
6161 }
6162 
6163 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6164                                                     const SCEV *Step,
6165                                                     const SCEV *MaxBECount,
6166                                                     unsigned BitWidth) {
6167   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6168   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6169 
6170   struct SelectPattern {
6171     Value *Condition = nullptr;
6172     APInt TrueValue;
6173     APInt FalseValue;
6174 
6175     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6176                            const SCEV *S) {
6177       Optional<unsigned> CastOp;
6178       APInt Offset(BitWidth, 0);
6179 
6180       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6181              "Should be!");
6182 
6183       // Peel off a constant offset:
6184       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6185         // In the future we could consider being smarter here and handle
6186         // {Start+Step,+,Step} too.
6187         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6188           return;
6189 
6190         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6191         S = SA->getOperand(1);
6192       }
6193 
6194       // Peel off a cast operation
6195       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6196         CastOp = SCast->getSCEVType();
6197         S = SCast->getOperand();
6198       }
6199 
6200       using namespace llvm::PatternMatch;
6201 
6202       auto *SU = dyn_cast<SCEVUnknown>(S);
6203       const APInt *TrueVal, *FalseVal;
6204       if (!SU ||
6205           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6206                                           m_APInt(FalseVal)))) {
6207         Condition = nullptr;
6208         return;
6209       }
6210 
6211       TrueValue = *TrueVal;
6212       FalseValue = *FalseVal;
6213 
6214       // Re-apply the cast we peeled off earlier
6215       if (CastOp.hasValue())
6216         switch (*CastOp) {
6217         default:
6218           llvm_unreachable("Unknown SCEV cast type!");
6219 
6220         case scTruncate:
6221           TrueValue = TrueValue.trunc(BitWidth);
6222           FalseValue = FalseValue.trunc(BitWidth);
6223           break;
6224         case scZeroExtend:
6225           TrueValue = TrueValue.zext(BitWidth);
6226           FalseValue = FalseValue.zext(BitWidth);
6227           break;
6228         case scSignExtend:
6229           TrueValue = TrueValue.sext(BitWidth);
6230           FalseValue = FalseValue.sext(BitWidth);
6231           break;
6232         }
6233 
6234       // Re-apply the constant offset we peeled off earlier
6235       TrueValue += Offset;
6236       FalseValue += Offset;
6237     }
6238 
6239     bool isRecognized() { return Condition != nullptr; }
6240   };
6241 
6242   SelectPattern StartPattern(*this, BitWidth, Start);
6243   if (!StartPattern.isRecognized())
6244     return ConstantRange::getFull(BitWidth);
6245 
6246   SelectPattern StepPattern(*this, BitWidth, Step);
6247   if (!StepPattern.isRecognized())
6248     return ConstantRange::getFull(BitWidth);
6249 
6250   if (StartPattern.Condition != StepPattern.Condition) {
6251     // We don't handle this case today; but we could, by considering four
6252     // possibilities below instead of two. I'm not sure if there are cases where
6253     // that will help over what getRange already does, though.
6254     return ConstantRange::getFull(BitWidth);
6255   }
6256 
6257   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6258   // construct arbitrary general SCEV expressions here.  This function is called
6259   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6260   // say) can end up caching a suboptimal value.
6261 
6262   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6263   // C2352 and C2512 (otherwise it isn't needed).
6264 
6265   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6266   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6267   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6268   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6269 
6270   ConstantRange TrueRange =
6271       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6272   ConstantRange FalseRange =
6273       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6274 
6275   return TrueRange.unionWith(FalseRange);
6276 }
6277 
6278 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6279   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6280   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6281 
6282   // Return early if there are no flags to propagate to the SCEV.
6283   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6284   if (BinOp->hasNoUnsignedWrap())
6285     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6286   if (BinOp->hasNoSignedWrap())
6287     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6288   if (Flags == SCEV::FlagAnyWrap)
6289     return SCEV::FlagAnyWrap;
6290 
6291   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6292 }
6293 
6294 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6295   // Here we check that I is in the header of the innermost loop containing I,
6296   // since we only deal with instructions in the loop header. The actual loop we
6297   // need to check later will come from an add recurrence, but getting that
6298   // requires computing the SCEV of the operands, which can be expensive. This
6299   // check we can do cheaply to rule out some cases early.
6300   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6301   if (InnermostContainingLoop == nullptr ||
6302       InnermostContainingLoop->getHeader() != I->getParent())
6303     return false;
6304 
6305   // Only proceed if we can prove that I does not yield poison.
6306   if (!programUndefinedIfPoison(I))
6307     return false;
6308 
6309   // At this point we know that if I is executed, then it does not wrap
6310   // according to at least one of NSW or NUW. If I is not executed, then we do
6311   // not know if the calculation that I represents would wrap. Multiple
6312   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6313   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6314   // derived from other instructions that map to the same SCEV. We cannot make
6315   // that guarantee for cases where I is not executed. So we need to find the
6316   // loop that I is considered in relation to and prove that I is executed for
6317   // every iteration of that loop. That implies that the value that I
6318   // calculates does not wrap anywhere in the loop, so then we can apply the
6319   // flags to the SCEV.
6320   //
6321   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6322   // from different loops, so that we know which loop to prove that I is
6323   // executed in.
6324   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6325     // I could be an extractvalue from a call to an overflow intrinsic.
6326     // TODO: We can do better here in some cases.
6327     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6328       return false;
6329     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6330     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6331       bool AllOtherOpsLoopInvariant = true;
6332       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6333            ++OtherOpIndex) {
6334         if (OtherOpIndex != OpIndex) {
6335           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6336           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6337             AllOtherOpsLoopInvariant = false;
6338             break;
6339           }
6340         }
6341       }
6342       if (AllOtherOpsLoopInvariant &&
6343           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6344         return true;
6345     }
6346   }
6347   return false;
6348 }
6349 
6350 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6351   // If we know that \c I can never be poison period, then that's enough.
6352   if (isSCEVExprNeverPoison(I))
6353     return true;
6354 
6355   // For an add recurrence specifically, we assume that infinite loops without
6356   // side effects are undefined behavior, and then reason as follows:
6357   //
6358   // If the add recurrence is poison in any iteration, it is poison on all
6359   // future iterations (since incrementing poison yields poison). If the result
6360   // of the add recurrence is fed into the loop latch condition and the loop
6361   // does not contain any throws or exiting blocks other than the latch, we now
6362   // have the ability to "choose" whether the backedge is taken or not (by
6363   // choosing a sufficiently evil value for the poison feeding into the branch)
6364   // for every iteration including and after the one in which \p I first became
6365   // poison.  There are two possibilities (let's call the iteration in which \p
6366   // I first became poison as K):
6367   //
6368   //  1. In the set of iterations including and after K, the loop body executes
6369   //     no side effects.  In this case executing the backege an infinte number
6370   //     of times will yield undefined behavior.
6371   //
6372   //  2. In the set of iterations including and after K, the loop body executes
6373   //     at least one side effect.  In this case, that specific instance of side
6374   //     effect is control dependent on poison, which also yields undefined
6375   //     behavior.
6376 
6377   auto *ExitingBB = L->getExitingBlock();
6378   auto *LatchBB = L->getLoopLatch();
6379   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6380     return false;
6381 
6382   SmallPtrSet<const Instruction *, 16> Pushed;
6383   SmallVector<const Instruction *, 8> PoisonStack;
6384 
6385   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6386   // things that are known to be poison under that assumption go on the
6387   // PoisonStack.
6388   Pushed.insert(I);
6389   PoisonStack.push_back(I);
6390 
6391   bool LatchControlDependentOnPoison = false;
6392   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6393     const Instruction *Poison = PoisonStack.pop_back_val();
6394 
6395     for (auto *PoisonUser : Poison->users()) {
6396       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6397         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6398           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6399       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6400         assert(BI->isConditional() && "Only possibility!");
6401         if (BI->getParent() == LatchBB) {
6402           LatchControlDependentOnPoison = true;
6403           break;
6404         }
6405       }
6406     }
6407   }
6408 
6409   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6410 }
6411 
6412 ScalarEvolution::LoopProperties
6413 ScalarEvolution::getLoopProperties(const Loop *L) {
6414   using LoopProperties = ScalarEvolution::LoopProperties;
6415 
6416   auto Itr = LoopPropertiesCache.find(L);
6417   if (Itr == LoopPropertiesCache.end()) {
6418     auto HasSideEffects = [](Instruction *I) {
6419       if (auto *SI = dyn_cast<StoreInst>(I))
6420         return !SI->isSimple();
6421 
6422       return I->mayHaveSideEffects();
6423     };
6424 
6425     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6426                          /*HasNoSideEffects*/ true};
6427 
6428     for (auto *BB : L->getBlocks())
6429       for (auto &I : *BB) {
6430         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6431           LP.HasNoAbnormalExits = false;
6432         if (HasSideEffects(&I))
6433           LP.HasNoSideEffects = false;
6434         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6435           break; // We're already as pessimistic as we can get.
6436       }
6437 
6438     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6439     assert(InsertPair.second && "We just checked!");
6440     Itr = InsertPair.first;
6441   }
6442 
6443   return Itr->second;
6444 }
6445 
6446 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6447   if (!isSCEVable(V->getType()))
6448     return getUnknown(V);
6449 
6450   if (Instruction *I = dyn_cast<Instruction>(V)) {
6451     // Don't attempt to analyze instructions in blocks that aren't
6452     // reachable. Such instructions don't matter, and they aren't required
6453     // to obey basic rules for definitions dominating uses which this
6454     // analysis depends on.
6455     if (!DT.isReachableFromEntry(I->getParent()))
6456       return getUnknown(UndefValue::get(V->getType()));
6457   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6458     return getConstant(CI);
6459   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6460     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6461   else if (!isa<ConstantExpr>(V))
6462     return getUnknown(V);
6463 
6464   Operator *U = cast<Operator>(V);
6465   if (auto BO = MatchBinaryOp(U, DT)) {
6466     switch (BO->Opcode) {
6467     case Instruction::Add: {
6468       // The simple thing to do would be to just call getSCEV on both operands
6469       // and call getAddExpr with the result. However if we're looking at a
6470       // bunch of things all added together, this can be quite inefficient,
6471       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6472       // Instead, gather up all the operands and make a single getAddExpr call.
6473       // LLVM IR canonical form means we need only traverse the left operands.
6474       SmallVector<const SCEV *, 4> AddOps;
6475       do {
6476         if (BO->Op) {
6477           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6478             AddOps.push_back(OpSCEV);
6479             break;
6480           }
6481 
6482           // If a NUW or NSW flag can be applied to the SCEV for this
6483           // addition, then compute the SCEV for this addition by itself
6484           // with a separate call to getAddExpr. We need to do that
6485           // instead of pushing the operands of the addition onto AddOps,
6486           // since the flags are only known to apply to this particular
6487           // addition - they may not apply to other additions that can be
6488           // formed with operands from AddOps.
6489           const SCEV *RHS = getSCEV(BO->RHS);
6490           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6491           if (Flags != SCEV::FlagAnyWrap) {
6492             const SCEV *LHS = getSCEV(BO->LHS);
6493             if (BO->Opcode == Instruction::Sub)
6494               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6495             else
6496               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6497             break;
6498           }
6499         }
6500 
6501         if (BO->Opcode == Instruction::Sub)
6502           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6503         else
6504           AddOps.push_back(getSCEV(BO->RHS));
6505 
6506         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6507         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6508                        NewBO->Opcode != Instruction::Sub)) {
6509           AddOps.push_back(getSCEV(BO->LHS));
6510           break;
6511         }
6512         BO = NewBO;
6513       } while (true);
6514 
6515       return getAddExpr(AddOps);
6516     }
6517 
6518     case Instruction::Mul: {
6519       SmallVector<const SCEV *, 4> MulOps;
6520       do {
6521         if (BO->Op) {
6522           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6523             MulOps.push_back(OpSCEV);
6524             break;
6525           }
6526 
6527           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6528           if (Flags != SCEV::FlagAnyWrap) {
6529             MulOps.push_back(
6530                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6531             break;
6532           }
6533         }
6534 
6535         MulOps.push_back(getSCEV(BO->RHS));
6536         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6537         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6538           MulOps.push_back(getSCEV(BO->LHS));
6539           break;
6540         }
6541         BO = NewBO;
6542       } while (true);
6543 
6544       return getMulExpr(MulOps);
6545     }
6546     case Instruction::UDiv:
6547       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6548     case Instruction::URem:
6549       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6550     case Instruction::Sub: {
6551       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6552       if (BO->Op)
6553         Flags = getNoWrapFlagsFromUB(BO->Op);
6554       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6555     }
6556     case Instruction::And:
6557       // For an expression like x&255 that merely masks off the high bits,
6558       // use zext(trunc(x)) as the SCEV expression.
6559       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6560         if (CI->isZero())
6561           return getSCEV(BO->RHS);
6562         if (CI->isMinusOne())
6563           return getSCEV(BO->LHS);
6564         const APInt &A = CI->getValue();
6565 
6566         // Instcombine's ShrinkDemandedConstant may strip bits out of
6567         // constants, obscuring what would otherwise be a low-bits mask.
6568         // Use computeKnownBits to compute what ShrinkDemandedConstant
6569         // knew about to reconstruct a low-bits mask value.
6570         unsigned LZ = A.countLeadingZeros();
6571         unsigned TZ = A.countTrailingZeros();
6572         unsigned BitWidth = A.getBitWidth();
6573         KnownBits Known(BitWidth);
6574         computeKnownBits(BO->LHS, Known, getDataLayout(),
6575                          0, &AC, nullptr, &DT);
6576 
6577         APInt EffectiveMask =
6578             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6579         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6580           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6581           const SCEV *LHS = getSCEV(BO->LHS);
6582           const SCEV *ShiftedLHS = nullptr;
6583           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6584             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6585               // For an expression like (x * 8) & 8, simplify the multiply.
6586               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6587               unsigned GCD = std::min(MulZeros, TZ);
6588               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6589               SmallVector<const SCEV*, 4> MulOps;
6590               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6591               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6592               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6593               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6594             }
6595           }
6596           if (!ShiftedLHS)
6597             ShiftedLHS = getUDivExpr(LHS, MulCount);
6598           return getMulExpr(
6599               getZeroExtendExpr(
6600                   getTruncateExpr(ShiftedLHS,
6601                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6602                   BO->LHS->getType()),
6603               MulCount);
6604         }
6605       }
6606       break;
6607 
6608     case Instruction::Or:
6609       // If the RHS of the Or is a constant, we may have something like:
6610       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6611       // optimizations will transparently handle this case.
6612       //
6613       // In order for this transformation to be safe, the LHS must be of the
6614       // form X*(2^n) and the Or constant must be less than 2^n.
6615       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6616         const SCEV *LHS = getSCEV(BO->LHS);
6617         const APInt &CIVal = CI->getValue();
6618         if (GetMinTrailingZeros(LHS) >=
6619             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6620           // Build a plain add SCEV.
6621           return getAddExpr(LHS, getSCEV(CI),
6622                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6623         }
6624       }
6625       break;
6626 
6627     case Instruction::Xor:
6628       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6629         // If the RHS of xor is -1, then this is a not operation.
6630         if (CI->isMinusOne())
6631           return getNotSCEV(getSCEV(BO->LHS));
6632 
6633         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6634         // This is a variant of the check for xor with -1, and it handles
6635         // the case where instcombine has trimmed non-demanded bits out
6636         // of an xor with -1.
6637         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6638           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6639             if (LBO->getOpcode() == Instruction::And &&
6640                 LCI->getValue() == CI->getValue())
6641               if (const SCEVZeroExtendExpr *Z =
6642                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6643                 Type *UTy = BO->LHS->getType();
6644                 const SCEV *Z0 = Z->getOperand();
6645                 Type *Z0Ty = Z0->getType();
6646                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6647 
6648                 // If C is a low-bits mask, the zero extend is serving to
6649                 // mask off the high bits. Complement the operand and
6650                 // re-apply the zext.
6651                 if (CI->getValue().isMask(Z0TySize))
6652                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6653 
6654                 // If C is a single bit, it may be in the sign-bit position
6655                 // before the zero-extend. In this case, represent the xor
6656                 // using an add, which is equivalent, and re-apply the zext.
6657                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6658                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6659                     Trunc.isSignMask())
6660                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6661                                            UTy);
6662               }
6663       }
6664       break;
6665 
6666     case Instruction::Shl:
6667       // Turn shift left of a constant amount into a multiply.
6668       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6669         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6670 
6671         // If the shift count is not less than the bitwidth, the result of
6672         // the shift is undefined. Don't try to analyze it, because the
6673         // resolution chosen here may differ from the resolution chosen in
6674         // other parts of the compiler.
6675         if (SA->getValue().uge(BitWidth))
6676           break;
6677 
6678         // We can safely preserve the nuw flag in all cases. It's also safe to
6679         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6680         // requires special handling. It can be preserved as long as we're not
6681         // left shifting by bitwidth - 1.
6682         auto Flags = SCEV::FlagAnyWrap;
6683         if (BO->Op) {
6684           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6685           if ((MulFlags & SCEV::FlagNSW) &&
6686               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6687             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6688           if (MulFlags & SCEV::FlagNUW)
6689             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6690         }
6691 
6692         Constant *X = ConstantInt::get(
6693             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6694         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6695       }
6696       break;
6697 
6698     case Instruction::AShr: {
6699       // AShr X, C, where C is a constant.
6700       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6701       if (!CI)
6702         break;
6703 
6704       Type *OuterTy = BO->LHS->getType();
6705       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6706       // If the shift count is not less than the bitwidth, the result of
6707       // the shift is undefined. Don't try to analyze it, because the
6708       // resolution chosen here may differ from the resolution chosen in
6709       // other parts of the compiler.
6710       if (CI->getValue().uge(BitWidth))
6711         break;
6712 
6713       if (CI->isZero())
6714         return getSCEV(BO->LHS); // shift by zero --> noop
6715 
6716       uint64_t AShrAmt = CI->getZExtValue();
6717       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6718 
6719       Operator *L = dyn_cast<Operator>(BO->LHS);
6720       if (L && L->getOpcode() == Instruction::Shl) {
6721         // X = Shl A, n
6722         // Y = AShr X, m
6723         // Both n and m are constant.
6724 
6725         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6726         if (L->getOperand(1) == BO->RHS)
6727           // For a two-shift sext-inreg, i.e. n = m,
6728           // use sext(trunc(x)) as the SCEV expression.
6729           return getSignExtendExpr(
6730               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6731 
6732         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6733         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6734           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6735           if (ShlAmt > AShrAmt) {
6736             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6737             // expression. We already checked that ShlAmt < BitWidth, so
6738             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6739             // ShlAmt - AShrAmt < Amt.
6740             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6741                                             ShlAmt - AShrAmt);
6742             return getSignExtendExpr(
6743                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6744                 getConstant(Mul)), OuterTy);
6745           }
6746         }
6747       }
6748       if (BO->IsExact) {
6749         // Given exact arithmetic in-bounds right-shift by a constant,
6750         // we can lower it into:  (abs(x) EXACT/u (1<<C)) * signum(x)
6751         const SCEV *X = getSCEV(BO->LHS);
6752         const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false);
6753         APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt);
6754         const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult));
6755         return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW);
6756       }
6757       break;
6758     }
6759     }
6760   }
6761 
6762   switch (U->getOpcode()) {
6763   case Instruction::Trunc:
6764     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6765 
6766   case Instruction::ZExt:
6767     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6768 
6769   case Instruction::SExt:
6770     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6771       // The NSW flag of a subtract does not always survive the conversion to
6772       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6773       // more likely to preserve NSW and allow later AddRec optimisations.
6774       //
6775       // NOTE: This is effectively duplicating this logic from getSignExtend:
6776       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6777       // but by that point the NSW information has potentially been lost.
6778       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6779         Type *Ty = U->getType();
6780         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6781         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6782         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6783       }
6784     }
6785     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6786 
6787   case Instruction::BitCast:
6788     // BitCasts are no-op casts so we just eliminate the cast.
6789     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6790       return getSCEV(U->getOperand(0));
6791     break;
6792 
6793   case Instruction::PtrToInt: {
6794     // Pointer to integer cast is straight-forward, so do model it.
6795     Value *Ptr = U->getOperand(0);
6796     const SCEV *Op = getSCEV(Ptr);
6797     Type *DstIntTy = U->getType();
6798     Type *PtrTy = Ptr->getType();
6799     Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy);
6800     // But only if effective SCEV (integer) type is wide enough to represent
6801     // all possible pointer values.
6802     if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) !=
6803         getDataLayout().getTypeSizeInBits(IntPtrTy))
6804       return getUnknown(V);
6805     return getPtrToIntExpr(Op, DstIntTy);
6806   }
6807   case Instruction::IntToPtr:
6808     // Just don't deal with inttoptr casts.
6809     return getUnknown(V);
6810 
6811   case Instruction::SDiv:
6812     // If both operands are non-negative, this is just an udiv.
6813     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6814         isKnownNonNegative(getSCEV(U->getOperand(1))))
6815       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6816     break;
6817 
6818   case Instruction::SRem:
6819     // If both operands are non-negative, this is just an urem.
6820     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6821         isKnownNonNegative(getSCEV(U->getOperand(1))))
6822       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6823     break;
6824 
6825   case Instruction::GetElementPtr:
6826     return createNodeForGEP(cast<GEPOperator>(U));
6827 
6828   case Instruction::PHI:
6829     return createNodeForPHI(cast<PHINode>(U));
6830 
6831   case Instruction::Select:
6832     // U can also be a select constant expr, which let fall through.  Since
6833     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6834     // constant expressions cannot have instructions as operands, we'd have
6835     // returned getUnknown for a select constant expressions anyway.
6836     if (isa<Instruction>(U))
6837       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6838                                       U->getOperand(1), U->getOperand(2));
6839     break;
6840 
6841   case Instruction::Call:
6842   case Instruction::Invoke:
6843     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6844       return getSCEV(RV);
6845 
6846     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6847       switch (II->getIntrinsicID()) {
6848       case Intrinsic::abs:
6849         return getAbsExpr(
6850             getSCEV(II->getArgOperand(0)),
6851             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6852       case Intrinsic::umax:
6853         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6854                            getSCEV(II->getArgOperand(1)));
6855       case Intrinsic::umin:
6856         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6857                            getSCEV(II->getArgOperand(1)));
6858       case Intrinsic::smax:
6859         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6860                            getSCEV(II->getArgOperand(1)));
6861       case Intrinsic::smin:
6862         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6863                            getSCEV(II->getArgOperand(1)));
6864       case Intrinsic::usub_sat: {
6865         const SCEV *X = getSCEV(II->getArgOperand(0));
6866         const SCEV *Y = getSCEV(II->getArgOperand(1));
6867         const SCEV *ClampedY = getUMinExpr(X, Y);
6868         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6869       }
6870       case Intrinsic::uadd_sat: {
6871         const SCEV *X = getSCEV(II->getArgOperand(0));
6872         const SCEV *Y = getSCEV(II->getArgOperand(1));
6873         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6874         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6875       }
6876       case Intrinsic::start_loop_iterations:
6877         // A start_loop_iterations is just equivalent to the first operand for
6878         // SCEV purposes.
6879         return getSCEV(II->getArgOperand(0));
6880       default:
6881         break;
6882       }
6883     }
6884     break;
6885   }
6886 
6887   return getUnknown(V);
6888 }
6889 
6890 //===----------------------------------------------------------------------===//
6891 //                   Iteration Count Computation Code
6892 //
6893 
6894 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6895   if (!ExitCount)
6896     return 0;
6897 
6898   ConstantInt *ExitConst = ExitCount->getValue();
6899 
6900   // Guard against huge trip counts.
6901   if (ExitConst->getValue().getActiveBits() > 32)
6902     return 0;
6903 
6904   // In case of integer overflow, this returns 0, which is correct.
6905   return ((unsigned)ExitConst->getZExtValue()) + 1;
6906 }
6907 
6908 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6909   if (BasicBlock *ExitingBB = L->getExitingBlock())
6910     return getSmallConstantTripCount(L, ExitingBB);
6911 
6912   // No trip count information for multiple exits.
6913   return 0;
6914 }
6915 
6916 unsigned
6917 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6918                                            const BasicBlock *ExitingBlock) {
6919   assert(ExitingBlock && "Must pass a non-null exiting block!");
6920   assert(L->isLoopExiting(ExitingBlock) &&
6921          "Exiting block must actually branch out of the loop!");
6922   const SCEVConstant *ExitCount =
6923       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6924   return getConstantTripCount(ExitCount);
6925 }
6926 
6927 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6928   const auto *MaxExitCount =
6929       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6930   return getConstantTripCount(MaxExitCount);
6931 }
6932 
6933 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6934   if (BasicBlock *ExitingBB = L->getExitingBlock())
6935     return getSmallConstantTripMultiple(L, ExitingBB);
6936 
6937   // No trip multiple information for multiple exits.
6938   return 0;
6939 }
6940 
6941 /// Returns the largest constant divisor of the trip count of this loop as a
6942 /// normal unsigned value, if possible. This means that the actual trip count is
6943 /// always a multiple of the returned value (don't forget the trip count could
6944 /// very well be zero as well!).
6945 ///
6946 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6947 /// multiple of a constant (which is also the case if the trip count is simply
6948 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6949 /// if the trip count is very large (>= 2^32).
6950 ///
6951 /// As explained in the comments for getSmallConstantTripCount, this assumes
6952 /// that control exits the loop via ExitingBlock.
6953 unsigned
6954 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6955                                               const BasicBlock *ExitingBlock) {
6956   assert(ExitingBlock && "Must pass a non-null exiting block!");
6957   assert(L->isLoopExiting(ExitingBlock) &&
6958          "Exiting block must actually branch out of the loop!");
6959   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6960   if (ExitCount == getCouldNotCompute())
6961     return 1;
6962 
6963   // Get the trip count from the BE count by adding 1.
6964   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6965 
6966   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6967   if (!TC)
6968     // Attempt to factor more general cases. Returns the greatest power of
6969     // two divisor. If overflow happens, the trip count expression is still
6970     // divisible by the greatest power of 2 divisor returned.
6971     return 1U << std::min((uint32_t)31,
6972                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
6973 
6974   ConstantInt *Result = TC->getValue();
6975 
6976   // Guard against huge trip counts (this requires checking
6977   // for zero to handle the case where the trip count == -1 and the
6978   // addition wraps).
6979   if (!Result || Result->getValue().getActiveBits() > 32 ||
6980       Result->getValue().getActiveBits() == 0)
6981     return 1;
6982 
6983   return (unsigned)Result->getZExtValue();
6984 }
6985 
6986 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6987                                           const BasicBlock *ExitingBlock,
6988                                           ExitCountKind Kind) {
6989   switch (Kind) {
6990   case Exact:
6991   case SymbolicMaximum:
6992     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6993   case ConstantMaximum:
6994     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
6995   };
6996   llvm_unreachable("Invalid ExitCountKind!");
6997 }
6998 
6999 const SCEV *
7000 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7001                                                  SCEVUnionPredicate &Preds) {
7002   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7003 }
7004 
7005 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7006                                                    ExitCountKind Kind) {
7007   switch (Kind) {
7008   case Exact:
7009     return getBackedgeTakenInfo(L).getExact(L, this);
7010   case ConstantMaximum:
7011     return getBackedgeTakenInfo(L).getConstantMax(this);
7012   case SymbolicMaximum:
7013     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7014   };
7015   llvm_unreachable("Invalid ExitCountKind!");
7016 }
7017 
7018 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7019   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7020 }
7021 
7022 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7023 static void
7024 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
7025   BasicBlock *Header = L->getHeader();
7026 
7027   // Push all Loop-header PHIs onto the Worklist stack.
7028   for (PHINode &PN : Header->phis())
7029     Worklist.push_back(&PN);
7030 }
7031 
7032 const ScalarEvolution::BackedgeTakenInfo &
7033 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7034   auto &BTI = getBackedgeTakenInfo(L);
7035   if (BTI.hasFullInfo())
7036     return BTI;
7037 
7038   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7039 
7040   if (!Pair.second)
7041     return Pair.first->second;
7042 
7043   BackedgeTakenInfo Result =
7044       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7045 
7046   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7047 }
7048 
7049 ScalarEvolution::BackedgeTakenInfo &
7050 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7051   // Initially insert an invalid entry for this loop. If the insertion
7052   // succeeds, proceed to actually compute a backedge-taken count and
7053   // update the value. The temporary CouldNotCompute value tells SCEV
7054   // code elsewhere that it shouldn't attempt to request a new
7055   // backedge-taken count, which could result in infinite recursion.
7056   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7057       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7058   if (!Pair.second)
7059     return Pair.first->second;
7060 
7061   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7062   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7063   // must be cleared in this scope.
7064   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7065 
7066   // In product build, there are no usage of statistic.
7067   (void)NumTripCountsComputed;
7068   (void)NumTripCountsNotComputed;
7069 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7070   const SCEV *BEExact = Result.getExact(L, this);
7071   if (BEExact != getCouldNotCompute()) {
7072     assert(isLoopInvariant(BEExact, L) &&
7073            isLoopInvariant(Result.getConstantMax(this), L) &&
7074            "Computed backedge-taken count isn't loop invariant for loop!");
7075     ++NumTripCountsComputed;
7076   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7077              isa<PHINode>(L->getHeader()->begin())) {
7078     // Only count loops that have phi nodes as not being computable.
7079     ++NumTripCountsNotComputed;
7080   }
7081 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7082 
7083   // Now that we know more about the trip count for this loop, forget any
7084   // existing SCEV values for PHI nodes in this loop since they are only
7085   // conservative estimates made without the benefit of trip count
7086   // information. This is similar to the code in forgetLoop, except that
7087   // it handles SCEVUnknown PHI nodes specially.
7088   if (Result.hasAnyInfo()) {
7089     SmallVector<Instruction *, 16> Worklist;
7090     PushLoopPHIs(L, Worklist);
7091 
7092     SmallPtrSet<Instruction *, 8> Discovered;
7093     while (!Worklist.empty()) {
7094       Instruction *I = Worklist.pop_back_val();
7095 
7096       ValueExprMapType::iterator It =
7097         ValueExprMap.find_as(static_cast<Value *>(I));
7098       if (It != ValueExprMap.end()) {
7099         const SCEV *Old = It->second;
7100 
7101         // SCEVUnknown for a PHI either means that it has an unrecognized
7102         // structure, or it's a PHI that's in the progress of being computed
7103         // by createNodeForPHI.  In the former case, additional loop trip
7104         // count information isn't going to change anything. In the later
7105         // case, createNodeForPHI will perform the necessary updates on its
7106         // own when it gets to that point.
7107         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7108           eraseValueFromMap(It->first);
7109           forgetMemoizedResults(Old);
7110         }
7111         if (PHINode *PN = dyn_cast<PHINode>(I))
7112           ConstantEvolutionLoopExitValue.erase(PN);
7113       }
7114 
7115       // Since we don't need to invalidate anything for correctness and we're
7116       // only invalidating to make SCEV's results more precise, we get to stop
7117       // early to avoid invalidating too much.  This is especially important in
7118       // cases like:
7119       //
7120       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7121       // loop0:
7122       //   %pn0 = phi
7123       //   ...
7124       // loop1:
7125       //   %pn1 = phi
7126       //   ...
7127       //
7128       // where both loop0 and loop1's backedge taken count uses the SCEV
7129       // expression for %v.  If we don't have the early stop below then in cases
7130       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7131       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7132       // count for loop1, effectively nullifying SCEV's trip count cache.
7133       for (auto *U : I->users())
7134         if (auto *I = dyn_cast<Instruction>(U)) {
7135           auto *LoopForUser = LI.getLoopFor(I->getParent());
7136           if (LoopForUser && L->contains(LoopForUser) &&
7137               Discovered.insert(I).second)
7138             Worklist.push_back(I);
7139         }
7140     }
7141   }
7142 
7143   // Re-lookup the insert position, since the call to
7144   // computeBackedgeTakenCount above could result in a
7145   // recusive call to getBackedgeTakenInfo (on a different
7146   // loop), which would invalidate the iterator computed
7147   // earlier.
7148   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7149 }
7150 
7151 void ScalarEvolution::forgetAllLoops() {
7152   // This method is intended to forget all info about loops. It should
7153   // invalidate caches as if the following happened:
7154   // - The trip counts of all loops have changed arbitrarily
7155   // - Every llvm::Value has been updated in place to produce a different
7156   // result.
7157   BackedgeTakenCounts.clear();
7158   PredicatedBackedgeTakenCounts.clear();
7159   LoopPropertiesCache.clear();
7160   ConstantEvolutionLoopExitValue.clear();
7161   ValueExprMap.clear();
7162   ValuesAtScopes.clear();
7163   LoopDispositions.clear();
7164   BlockDispositions.clear();
7165   UnsignedRanges.clear();
7166   SignedRanges.clear();
7167   ExprValueMap.clear();
7168   HasRecMap.clear();
7169   MinTrailingZerosCache.clear();
7170   PredicatedSCEVRewrites.clear();
7171 }
7172 
7173 void ScalarEvolution::forgetLoop(const Loop *L) {
7174   // Drop any stored trip count value.
7175   auto RemoveLoopFromBackedgeMap =
7176       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
7177         auto BTCPos = Map.find(L);
7178         if (BTCPos != Map.end()) {
7179           BTCPos->second.clear();
7180           Map.erase(BTCPos);
7181         }
7182       };
7183 
7184   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7185   SmallVector<Instruction *, 32> Worklist;
7186   SmallPtrSet<Instruction *, 16> Visited;
7187 
7188   // Iterate over all the loops and sub-loops to drop SCEV information.
7189   while (!LoopWorklist.empty()) {
7190     auto *CurrL = LoopWorklist.pop_back_val();
7191 
7192     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
7193     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
7194 
7195     // Drop information about predicated SCEV rewrites for this loop.
7196     for (auto I = PredicatedSCEVRewrites.begin();
7197          I != PredicatedSCEVRewrites.end();) {
7198       std::pair<const SCEV *, const Loop *> Entry = I->first;
7199       if (Entry.second == CurrL)
7200         PredicatedSCEVRewrites.erase(I++);
7201       else
7202         ++I;
7203     }
7204 
7205     auto LoopUsersItr = LoopUsers.find(CurrL);
7206     if (LoopUsersItr != LoopUsers.end()) {
7207       for (auto *S : LoopUsersItr->second)
7208         forgetMemoizedResults(S);
7209       LoopUsers.erase(LoopUsersItr);
7210     }
7211 
7212     // Drop information about expressions based on loop-header PHIs.
7213     PushLoopPHIs(CurrL, Worklist);
7214 
7215     while (!Worklist.empty()) {
7216       Instruction *I = Worklist.pop_back_val();
7217       if (!Visited.insert(I).second)
7218         continue;
7219 
7220       ValueExprMapType::iterator It =
7221           ValueExprMap.find_as(static_cast<Value *>(I));
7222       if (It != ValueExprMap.end()) {
7223         eraseValueFromMap(It->first);
7224         forgetMemoizedResults(It->second);
7225         if (PHINode *PN = dyn_cast<PHINode>(I))
7226           ConstantEvolutionLoopExitValue.erase(PN);
7227       }
7228 
7229       PushDefUseChildren(I, Worklist);
7230     }
7231 
7232     LoopPropertiesCache.erase(CurrL);
7233     // Forget all contained loops too, to avoid dangling entries in the
7234     // ValuesAtScopes map.
7235     LoopWorklist.append(CurrL->begin(), CurrL->end());
7236   }
7237 }
7238 
7239 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7240   while (Loop *Parent = L->getParentLoop())
7241     L = Parent;
7242   forgetLoop(L);
7243 }
7244 
7245 void ScalarEvolution::forgetValue(Value *V) {
7246   Instruction *I = dyn_cast<Instruction>(V);
7247   if (!I) return;
7248 
7249   // Drop information about expressions based on loop-header PHIs.
7250   SmallVector<Instruction *, 16> Worklist;
7251   Worklist.push_back(I);
7252 
7253   SmallPtrSet<Instruction *, 8> Visited;
7254   while (!Worklist.empty()) {
7255     I = Worklist.pop_back_val();
7256     if (!Visited.insert(I).second)
7257       continue;
7258 
7259     ValueExprMapType::iterator It =
7260       ValueExprMap.find_as(static_cast<Value *>(I));
7261     if (It != ValueExprMap.end()) {
7262       eraseValueFromMap(It->first);
7263       forgetMemoizedResults(It->second);
7264       if (PHINode *PN = dyn_cast<PHINode>(I))
7265         ConstantEvolutionLoopExitValue.erase(PN);
7266     }
7267 
7268     PushDefUseChildren(I, Worklist);
7269   }
7270 }
7271 
7272 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7273   LoopDispositions.clear();
7274 }
7275 
7276 /// Get the exact loop backedge taken count considering all loop exits. A
7277 /// computable result can only be returned for loops with all exiting blocks
7278 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7279 /// is never skipped. This is a valid assumption as long as the loop exits via
7280 /// that test. For precise results, it is the caller's responsibility to specify
7281 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7282 const SCEV *
7283 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7284                                              SCEVUnionPredicate *Preds) const {
7285   // If any exits were not computable, the loop is not computable.
7286   if (!isComplete() || ExitNotTaken.empty())
7287     return SE->getCouldNotCompute();
7288 
7289   const BasicBlock *Latch = L->getLoopLatch();
7290   // All exiting blocks we have collected must dominate the only backedge.
7291   if (!Latch)
7292     return SE->getCouldNotCompute();
7293 
7294   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7295   // count is simply a minimum out of all these calculated exit counts.
7296   SmallVector<const SCEV *, 2> Ops;
7297   for (auto &ENT : ExitNotTaken) {
7298     const SCEV *BECount = ENT.ExactNotTaken;
7299     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7300     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7301            "We should only have known counts for exiting blocks that dominate "
7302            "latch!");
7303 
7304     Ops.push_back(BECount);
7305 
7306     if (Preds && !ENT.hasAlwaysTruePredicate())
7307       Preds->add(ENT.Predicate.get());
7308 
7309     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7310            "Predicate should be always true!");
7311   }
7312 
7313   return SE->getUMinFromMismatchedTypes(Ops);
7314 }
7315 
7316 /// Get the exact not taken count for this loop exit.
7317 const SCEV *
7318 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7319                                              ScalarEvolution *SE) const {
7320   for (auto &ENT : ExitNotTaken)
7321     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7322       return ENT.ExactNotTaken;
7323 
7324   return SE->getCouldNotCompute();
7325 }
7326 
7327 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7328     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7329   for (auto &ENT : ExitNotTaken)
7330     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7331       return ENT.MaxNotTaken;
7332 
7333   return SE->getCouldNotCompute();
7334 }
7335 
7336 /// getConstantMax - Get the constant max backedge taken count for the loop.
7337 const SCEV *
7338 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7339   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7340     return !ENT.hasAlwaysTruePredicate();
7341   };
7342 
7343   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7344     return SE->getCouldNotCompute();
7345 
7346   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7347           isa<SCEVConstant>(getConstantMax())) &&
7348          "No point in having a non-constant max backedge taken count!");
7349   return getConstantMax();
7350 }
7351 
7352 const SCEV *
7353 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7354                                                    ScalarEvolution *SE) {
7355   if (!SymbolicMax)
7356     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7357   return SymbolicMax;
7358 }
7359 
7360 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7361     ScalarEvolution *SE) const {
7362   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7363     return !ENT.hasAlwaysTruePredicate();
7364   };
7365   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7366 }
7367 
7368 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7369                                                     ScalarEvolution *SE) const {
7370   if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7371       SE->hasOperand(getConstantMax(), S))
7372     return true;
7373 
7374   for (auto &ENT : ExitNotTaken)
7375     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7376         SE->hasOperand(ENT.ExactNotTaken, S))
7377       return true;
7378 
7379   return false;
7380 }
7381 
7382 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7383     : ExactNotTaken(E), MaxNotTaken(E) {
7384   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7385           isa<SCEVConstant>(MaxNotTaken)) &&
7386          "No point in having a non-constant max backedge taken count!");
7387 }
7388 
7389 ScalarEvolution::ExitLimit::ExitLimit(
7390     const SCEV *E, const SCEV *M, bool MaxOrZero,
7391     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7392     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7393   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7394           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7395          "Exact is not allowed to be less precise than Max");
7396   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7397           isa<SCEVConstant>(MaxNotTaken)) &&
7398          "No point in having a non-constant max backedge taken count!");
7399   for (auto *PredSet : PredSetList)
7400     for (auto *P : *PredSet)
7401       addPredicate(P);
7402 }
7403 
7404 ScalarEvolution::ExitLimit::ExitLimit(
7405     const SCEV *E, const SCEV *M, bool MaxOrZero,
7406     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7407     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7408   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7409           isa<SCEVConstant>(MaxNotTaken)) &&
7410          "No point in having a non-constant max backedge taken count!");
7411 }
7412 
7413 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7414                                       bool MaxOrZero)
7415     : ExitLimit(E, M, MaxOrZero, None) {
7416   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7417           isa<SCEVConstant>(MaxNotTaken)) &&
7418          "No point in having a non-constant max backedge taken count!");
7419 }
7420 
7421 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7422 /// computable exit into a persistent ExitNotTakenInfo array.
7423 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7424     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7425     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7426     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7427   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7428 
7429   ExitNotTaken.reserve(ExitCounts.size());
7430   std::transform(
7431       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7432       [&](const EdgeExitInfo &EEI) {
7433         BasicBlock *ExitBB = EEI.first;
7434         const ExitLimit &EL = EEI.second;
7435         if (EL.Predicates.empty())
7436           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7437                                   nullptr);
7438 
7439         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7440         for (auto *Pred : EL.Predicates)
7441           Predicate->add(Pred);
7442 
7443         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7444                                 std::move(Predicate));
7445       });
7446   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7447           isa<SCEVConstant>(ConstantMax)) &&
7448          "No point in having a non-constant max backedge taken count!");
7449 }
7450 
7451 /// Invalidate this result and free the ExitNotTakenInfo array.
7452 void ScalarEvolution::BackedgeTakenInfo::clear() {
7453   ExitNotTaken.clear();
7454 }
7455 
7456 /// Compute the number of times the backedge of the specified loop will execute.
7457 ScalarEvolution::BackedgeTakenInfo
7458 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7459                                            bool AllowPredicates) {
7460   SmallVector<BasicBlock *, 8> ExitingBlocks;
7461   L->getExitingBlocks(ExitingBlocks);
7462 
7463   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7464 
7465   SmallVector<EdgeExitInfo, 4> ExitCounts;
7466   bool CouldComputeBECount = true;
7467   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7468   const SCEV *MustExitMaxBECount = nullptr;
7469   const SCEV *MayExitMaxBECount = nullptr;
7470   bool MustExitMaxOrZero = false;
7471 
7472   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7473   // and compute maxBECount.
7474   // Do a union of all the predicates here.
7475   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7476     BasicBlock *ExitBB = ExitingBlocks[i];
7477 
7478     // We canonicalize untaken exits to br (constant), ignore them so that
7479     // proving an exit untaken doesn't negatively impact our ability to reason
7480     // about the loop as whole.
7481     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7482       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7483         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7484         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7485           continue;
7486       }
7487 
7488     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7489 
7490     assert((AllowPredicates || EL.Predicates.empty()) &&
7491            "Predicated exit limit when predicates are not allowed!");
7492 
7493     // 1. For each exit that can be computed, add an entry to ExitCounts.
7494     // CouldComputeBECount is true only if all exits can be computed.
7495     if (EL.ExactNotTaken == getCouldNotCompute())
7496       // We couldn't compute an exact value for this exit, so
7497       // we won't be able to compute an exact value for the loop.
7498       CouldComputeBECount = false;
7499     else
7500       ExitCounts.emplace_back(ExitBB, EL);
7501 
7502     // 2. Derive the loop's MaxBECount from each exit's max number of
7503     // non-exiting iterations. Partition the loop exits into two kinds:
7504     // LoopMustExits and LoopMayExits.
7505     //
7506     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7507     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7508     // MaxBECount is the minimum EL.MaxNotTaken of computable
7509     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7510     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7511     // computable EL.MaxNotTaken.
7512     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7513         DT.dominates(ExitBB, Latch)) {
7514       if (!MustExitMaxBECount) {
7515         MustExitMaxBECount = EL.MaxNotTaken;
7516         MustExitMaxOrZero = EL.MaxOrZero;
7517       } else {
7518         MustExitMaxBECount =
7519             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7520       }
7521     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7522       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7523         MayExitMaxBECount = EL.MaxNotTaken;
7524       else {
7525         MayExitMaxBECount =
7526             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7527       }
7528     }
7529   }
7530   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7531     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7532   // The loop backedge will be taken the maximum or zero times if there's
7533   // a single exit that must be taken the maximum or zero times.
7534   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7535   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7536                            MaxBECount, MaxOrZero);
7537 }
7538 
7539 ScalarEvolution::ExitLimit
7540 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7541                                       bool AllowPredicates) {
7542   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7543   // If our exiting block does not dominate the latch, then its connection with
7544   // loop's exit limit may be far from trivial.
7545   const BasicBlock *Latch = L->getLoopLatch();
7546   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7547     return getCouldNotCompute();
7548 
7549   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7550   Instruction *Term = ExitingBlock->getTerminator();
7551   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7552     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7553     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7554     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7555            "It should have one successor in loop and one exit block!");
7556     // Proceed to the next level to examine the exit condition expression.
7557     return computeExitLimitFromCond(
7558         L, BI->getCondition(), ExitIfTrue,
7559         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7560   }
7561 
7562   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7563     // For switch, make sure that there is a single exit from the loop.
7564     BasicBlock *Exit = nullptr;
7565     for (auto *SBB : successors(ExitingBlock))
7566       if (!L->contains(SBB)) {
7567         if (Exit) // Multiple exit successors.
7568           return getCouldNotCompute();
7569         Exit = SBB;
7570       }
7571     assert(Exit && "Exiting block must have at least one exit");
7572     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7573                                                 /*ControlsExit=*/IsOnlyExit);
7574   }
7575 
7576   return getCouldNotCompute();
7577 }
7578 
7579 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7580     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7581     bool ControlsExit, bool AllowPredicates) {
7582   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7583   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7584                                         ControlsExit, AllowPredicates);
7585 }
7586 
7587 Optional<ScalarEvolution::ExitLimit>
7588 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7589                                       bool ExitIfTrue, bool ControlsExit,
7590                                       bool AllowPredicates) {
7591   (void)this->L;
7592   (void)this->ExitIfTrue;
7593   (void)this->AllowPredicates;
7594 
7595   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7596          this->AllowPredicates == AllowPredicates &&
7597          "Variance in assumed invariant key components!");
7598   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7599   if (Itr == TripCountMap.end())
7600     return None;
7601   return Itr->second;
7602 }
7603 
7604 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7605                                              bool ExitIfTrue,
7606                                              bool ControlsExit,
7607                                              bool AllowPredicates,
7608                                              const ExitLimit &EL) {
7609   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7610          this->AllowPredicates == AllowPredicates &&
7611          "Variance in assumed invariant key components!");
7612 
7613   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7614   assert(InsertResult.second && "Expected successful insertion!");
7615   (void)InsertResult;
7616   (void)ExitIfTrue;
7617 }
7618 
7619 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7620     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7621     bool ControlsExit, bool AllowPredicates) {
7622 
7623   if (auto MaybeEL =
7624           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7625     return *MaybeEL;
7626 
7627   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7628                                               ControlsExit, AllowPredicates);
7629   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7630   return EL;
7631 }
7632 
7633 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7634     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7635     bool ControlsExit, bool AllowPredicates) {
7636   // Handle BinOp conditions (And, Or).
7637   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7638           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7639     return *LimitFromBinOp;
7640 
7641   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7642   // Proceed to the next level to examine the icmp.
7643   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7644     ExitLimit EL =
7645         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7646     if (EL.hasFullInfo() || !AllowPredicates)
7647       return EL;
7648 
7649     // Try again, but use SCEV predicates this time.
7650     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7651                                     /*AllowPredicates=*/true);
7652   }
7653 
7654   // Check for a constant condition. These are normally stripped out by
7655   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7656   // preserve the CFG and is temporarily leaving constant conditions
7657   // in place.
7658   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7659     if (ExitIfTrue == !CI->getZExtValue())
7660       // The backedge is always taken.
7661       return getCouldNotCompute();
7662     else
7663       // The backedge is never taken.
7664       return getZero(CI->getType());
7665   }
7666 
7667   // If it's not an integer or pointer comparison then compute it the hard way.
7668   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7669 }
7670 
7671 Optional<ScalarEvolution::ExitLimit>
7672 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7673     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7674     bool ControlsExit, bool AllowPredicates) {
7675   // Check if the controlling expression for this loop is an And or Or.
7676   Value *Op0, *Op1;
7677   bool IsAnd = false;
7678   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7679     IsAnd = true;
7680   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7681     IsAnd = false;
7682   else
7683     return None;
7684 
7685   // EitherMayExit is true in these two cases:
7686   //   br (and Op0 Op1), loop, exit
7687   //   br (or  Op0 Op1), exit, loop
7688   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7689   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7690                                                  ControlsExit && !EitherMayExit,
7691                                                  AllowPredicates);
7692   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7693                                                  ControlsExit && !EitherMayExit,
7694                                                  AllowPredicates);
7695 
7696   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7697   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7698   if (isa<ConstantInt>(Op1))
7699     return Op1 == NeutralElement ? EL0 : EL1;
7700   if (isa<ConstantInt>(Op0))
7701     return Op0 == NeutralElement ? EL1 : EL0;
7702 
7703   const SCEV *BECount = getCouldNotCompute();
7704   const SCEV *MaxBECount = getCouldNotCompute();
7705   if (EitherMayExit) {
7706     // Both conditions must be same for the loop to continue executing.
7707     // Choose the less conservative count.
7708     // If ExitCond is a short-circuit form (select), using
7709     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7710     // To see the detailed examples, please see
7711     // test/Analysis/ScalarEvolution/exit-count-select.ll
7712     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7713     if (!PoisonSafe)
7714       // Even if ExitCond is select, we can safely derive BECount using both
7715       // EL0 and EL1 in these cases:
7716       // (1) EL0.ExactNotTaken is non-zero
7717       // (2) EL1.ExactNotTaken is non-poison
7718       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7719       //     it cannot be umin(0, ..))
7720       // The PoisonSafe assignment below is simplified and the assertion after
7721       // BECount calculation fully guarantees the condition (3).
7722       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7723                    isa<SCEVConstant>(EL1.ExactNotTaken);
7724     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7725         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7726       BECount =
7727           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7728 
7729       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7730       // it should have been simplified to zero (see the condition (3) above)
7731       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7732              BECount->isZero());
7733     }
7734     if (EL0.MaxNotTaken == getCouldNotCompute())
7735       MaxBECount = EL1.MaxNotTaken;
7736     else if (EL1.MaxNotTaken == getCouldNotCompute())
7737       MaxBECount = EL0.MaxNotTaken;
7738     else
7739       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7740   } else {
7741     // Both conditions must be same at the same time for the loop to exit.
7742     // For now, be conservative.
7743     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7744       BECount = EL0.ExactNotTaken;
7745   }
7746 
7747   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7748   // to be more aggressive when computing BECount than when computing
7749   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7750   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7751   // to not.
7752   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7753       !isa<SCEVCouldNotCompute>(BECount))
7754     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7755 
7756   return ExitLimit(BECount, MaxBECount, false,
7757                    { &EL0.Predicates, &EL1.Predicates });
7758 }
7759 
7760 ScalarEvolution::ExitLimit
7761 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7762                                           ICmpInst *ExitCond,
7763                                           bool ExitIfTrue,
7764                                           bool ControlsExit,
7765                                           bool AllowPredicates) {
7766   // If the condition was exit on true, convert the condition to exit on false
7767   ICmpInst::Predicate Pred;
7768   if (!ExitIfTrue)
7769     Pred = ExitCond->getPredicate();
7770   else
7771     Pred = ExitCond->getInversePredicate();
7772   const ICmpInst::Predicate OriginalPred = Pred;
7773 
7774   // Handle common loops like: for (X = "string"; *X; ++X)
7775   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7776     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7777       ExitLimit ItCnt =
7778         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7779       if (ItCnt.hasAnyInfo())
7780         return ItCnt;
7781     }
7782 
7783   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7784   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7785 
7786   // Try to evaluate any dependencies out of the loop.
7787   LHS = getSCEVAtScope(LHS, L);
7788   RHS = getSCEVAtScope(RHS, L);
7789 
7790   // At this point, we would like to compute how many iterations of the
7791   // loop the predicate will return true for these inputs.
7792   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7793     // If there is a loop-invariant, force it into the RHS.
7794     std::swap(LHS, RHS);
7795     Pred = ICmpInst::getSwappedPredicate(Pred);
7796   }
7797 
7798   // Simplify the operands before analyzing them.
7799   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7800 
7801   // If we have a comparison of a chrec against a constant, try to use value
7802   // ranges to answer this query.
7803   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7804     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7805       if (AddRec->getLoop() == L) {
7806         // Form the constant range.
7807         ConstantRange CompRange =
7808             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7809 
7810         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7811         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7812       }
7813 
7814   switch (Pred) {
7815   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7816     // Convert to: while (X-Y != 0)
7817     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7818                                 AllowPredicates);
7819     if (EL.hasAnyInfo()) return EL;
7820     break;
7821   }
7822   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7823     // Convert to: while (X-Y == 0)
7824     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7825     if (EL.hasAnyInfo()) return EL;
7826     break;
7827   }
7828   case ICmpInst::ICMP_SLT:
7829   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7830     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7831     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7832                                     AllowPredicates);
7833     if (EL.hasAnyInfo()) return EL;
7834     break;
7835   }
7836   case ICmpInst::ICMP_SGT:
7837   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7838     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7839     ExitLimit EL =
7840         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7841                             AllowPredicates);
7842     if (EL.hasAnyInfo()) return EL;
7843     break;
7844   }
7845   default:
7846     break;
7847   }
7848 
7849   auto *ExhaustiveCount =
7850       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7851 
7852   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7853     return ExhaustiveCount;
7854 
7855   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7856                                       ExitCond->getOperand(1), L, OriginalPred);
7857 }
7858 
7859 ScalarEvolution::ExitLimit
7860 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7861                                                       SwitchInst *Switch,
7862                                                       BasicBlock *ExitingBlock,
7863                                                       bool ControlsExit) {
7864   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7865 
7866   // Give up if the exit is the default dest of a switch.
7867   if (Switch->getDefaultDest() == ExitingBlock)
7868     return getCouldNotCompute();
7869 
7870   assert(L->contains(Switch->getDefaultDest()) &&
7871          "Default case must not exit the loop!");
7872   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7873   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7874 
7875   // while (X != Y) --> while (X-Y != 0)
7876   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7877   if (EL.hasAnyInfo())
7878     return EL;
7879 
7880   return getCouldNotCompute();
7881 }
7882 
7883 static ConstantInt *
7884 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7885                                 ScalarEvolution &SE) {
7886   const SCEV *InVal = SE.getConstant(C);
7887   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7888   assert(isa<SCEVConstant>(Val) &&
7889          "Evaluation of SCEV at constant didn't fold correctly?");
7890   return cast<SCEVConstant>(Val)->getValue();
7891 }
7892 
7893 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7894 /// compute the backedge execution count.
7895 ScalarEvolution::ExitLimit
7896 ScalarEvolution::computeLoadConstantCompareExitLimit(
7897   LoadInst *LI,
7898   Constant *RHS,
7899   const Loop *L,
7900   ICmpInst::Predicate predicate) {
7901   if (LI->isVolatile()) return getCouldNotCompute();
7902 
7903   // Check to see if the loaded pointer is a getelementptr of a global.
7904   // TODO: Use SCEV instead of manually grubbing with GEPs.
7905   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7906   if (!GEP) return getCouldNotCompute();
7907 
7908   // Make sure that it is really a constant global we are gepping, with an
7909   // initializer, and make sure the first IDX is really 0.
7910   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7911   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7912       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7913       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7914     return getCouldNotCompute();
7915 
7916   // Okay, we allow one non-constant index into the GEP instruction.
7917   Value *VarIdx = nullptr;
7918   std::vector<Constant*> Indexes;
7919   unsigned VarIdxNum = 0;
7920   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7921     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7922       Indexes.push_back(CI);
7923     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7924       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7925       VarIdx = GEP->getOperand(i);
7926       VarIdxNum = i-2;
7927       Indexes.push_back(nullptr);
7928     }
7929 
7930   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7931   if (!VarIdx)
7932     return getCouldNotCompute();
7933 
7934   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7935   // Check to see if X is a loop variant variable value now.
7936   const SCEV *Idx = getSCEV(VarIdx);
7937   Idx = getSCEVAtScope(Idx, L);
7938 
7939   // We can only recognize very limited forms of loop index expressions, in
7940   // particular, only affine AddRec's like {C1,+,C2}<L>.
7941   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7942   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
7943       isLoopInvariant(IdxExpr, L) ||
7944       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7945       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7946     return getCouldNotCompute();
7947 
7948   unsigned MaxSteps = MaxBruteForceIterations;
7949   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7950     ConstantInt *ItCst = ConstantInt::get(
7951                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7952     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7953 
7954     // Form the GEP offset.
7955     Indexes[VarIdxNum] = Val;
7956 
7957     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7958                                                          Indexes);
7959     if (!Result) break;  // Cannot compute!
7960 
7961     // Evaluate the condition for this iteration.
7962     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7963     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7964     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7965       ++NumArrayLenItCounts;
7966       return getConstant(ItCst);   // Found terminating iteration!
7967     }
7968   }
7969   return getCouldNotCompute();
7970 }
7971 
7972 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7973     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7974   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7975   if (!RHS)
7976     return getCouldNotCompute();
7977 
7978   const BasicBlock *Latch = L->getLoopLatch();
7979   if (!Latch)
7980     return getCouldNotCompute();
7981 
7982   const BasicBlock *Predecessor = L->getLoopPredecessor();
7983   if (!Predecessor)
7984     return getCouldNotCompute();
7985 
7986   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7987   // Return LHS in OutLHS and shift_opt in OutOpCode.
7988   auto MatchPositiveShift =
7989       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7990 
7991     using namespace PatternMatch;
7992 
7993     ConstantInt *ShiftAmt;
7994     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7995       OutOpCode = Instruction::LShr;
7996     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7997       OutOpCode = Instruction::AShr;
7998     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7999       OutOpCode = Instruction::Shl;
8000     else
8001       return false;
8002 
8003     return ShiftAmt->getValue().isStrictlyPositive();
8004   };
8005 
8006   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8007   //
8008   // loop:
8009   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8010   //   %iv.shifted = lshr i32 %iv, <positive constant>
8011   //
8012   // Return true on a successful match.  Return the corresponding PHI node (%iv
8013   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8014   auto MatchShiftRecurrence =
8015       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8016     Optional<Instruction::BinaryOps> PostShiftOpCode;
8017 
8018     {
8019       Instruction::BinaryOps OpC;
8020       Value *V;
8021 
8022       // If we encounter a shift instruction, "peel off" the shift operation,
8023       // and remember that we did so.  Later when we inspect %iv's backedge
8024       // value, we will make sure that the backedge value uses the same
8025       // operation.
8026       //
8027       // Note: the peeled shift operation does not have to be the same
8028       // instruction as the one feeding into the PHI's backedge value.  We only
8029       // really care about it being the same *kind* of shift instruction --
8030       // that's all that is required for our later inferences to hold.
8031       if (MatchPositiveShift(LHS, V, OpC)) {
8032         PostShiftOpCode = OpC;
8033         LHS = V;
8034       }
8035     }
8036 
8037     PNOut = dyn_cast<PHINode>(LHS);
8038     if (!PNOut || PNOut->getParent() != L->getHeader())
8039       return false;
8040 
8041     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8042     Value *OpLHS;
8043 
8044     return
8045         // The backedge value for the PHI node must be a shift by a positive
8046         // amount
8047         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8048 
8049         // of the PHI node itself
8050         OpLHS == PNOut &&
8051 
8052         // and the kind of shift should be match the kind of shift we peeled
8053         // off, if any.
8054         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8055   };
8056 
8057   PHINode *PN;
8058   Instruction::BinaryOps OpCode;
8059   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8060     return getCouldNotCompute();
8061 
8062   const DataLayout &DL = getDataLayout();
8063 
8064   // The key rationale for this optimization is that for some kinds of shift
8065   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8066   // within a finite number of iterations.  If the condition guarding the
8067   // backedge (in the sense that the backedge is taken if the condition is true)
8068   // is false for the value the shift recurrence stabilizes to, then we know
8069   // that the backedge is taken only a finite number of times.
8070 
8071   ConstantInt *StableValue = nullptr;
8072   switch (OpCode) {
8073   default:
8074     llvm_unreachable("Impossible case!");
8075 
8076   case Instruction::AShr: {
8077     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8078     // bitwidth(K) iterations.
8079     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8080     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8081                                        Predecessor->getTerminator(), &DT);
8082     auto *Ty = cast<IntegerType>(RHS->getType());
8083     if (Known.isNonNegative())
8084       StableValue = ConstantInt::get(Ty, 0);
8085     else if (Known.isNegative())
8086       StableValue = ConstantInt::get(Ty, -1, true);
8087     else
8088       return getCouldNotCompute();
8089 
8090     break;
8091   }
8092   case Instruction::LShr:
8093   case Instruction::Shl:
8094     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8095     // stabilize to 0 in at most bitwidth(K) iterations.
8096     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8097     break;
8098   }
8099 
8100   auto *Result =
8101       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8102   assert(Result->getType()->isIntegerTy(1) &&
8103          "Otherwise cannot be an operand to a branch instruction");
8104 
8105   if (Result->isZeroValue()) {
8106     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8107     const SCEV *UpperBound =
8108         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8109     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8110   }
8111 
8112   return getCouldNotCompute();
8113 }
8114 
8115 /// Return true if we can constant fold an instruction of the specified type,
8116 /// assuming that all operands were constants.
8117 static bool CanConstantFold(const Instruction *I) {
8118   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8119       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8120       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8121     return true;
8122 
8123   if (const CallInst *CI = dyn_cast<CallInst>(I))
8124     if (const Function *F = CI->getCalledFunction())
8125       return canConstantFoldCallTo(CI, F);
8126   return false;
8127 }
8128 
8129 /// Determine whether this instruction can constant evolve within this loop
8130 /// assuming its operands can all constant evolve.
8131 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8132   // An instruction outside of the loop can't be derived from a loop PHI.
8133   if (!L->contains(I)) return false;
8134 
8135   if (isa<PHINode>(I)) {
8136     // We don't currently keep track of the control flow needed to evaluate
8137     // PHIs, so we cannot handle PHIs inside of loops.
8138     return L->getHeader() == I->getParent();
8139   }
8140 
8141   // If we won't be able to constant fold this expression even if the operands
8142   // are constants, bail early.
8143   return CanConstantFold(I);
8144 }
8145 
8146 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8147 /// recursing through each instruction operand until reaching a loop header phi.
8148 static PHINode *
8149 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8150                                DenseMap<Instruction *, PHINode *> &PHIMap,
8151                                unsigned Depth) {
8152   if (Depth > MaxConstantEvolvingDepth)
8153     return nullptr;
8154 
8155   // Otherwise, we can evaluate this instruction if all of its operands are
8156   // constant or derived from a PHI node themselves.
8157   PHINode *PHI = nullptr;
8158   for (Value *Op : UseInst->operands()) {
8159     if (isa<Constant>(Op)) continue;
8160 
8161     Instruction *OpInst = dyn_cast<Instruction>(Op);
8162     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8163 
8164     PHINode *P = dyn_cast<PHINode>(OpInst);
8165     if (!P)
8166       // If this operand is already visited, reuse the prior result.
8167       // We may have P != PHI if this is the deepest point at which the
8168       // inconsistent paths meet.
8169       P = PHIMap.lookup(OpInst);
8170     if (!P) {
8171       // Recurse and memoize the results, whether a phi is found or not.
8172       // This recursive call invalidates pointers into PHIMap.
8173       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8174       PHIMap[OpInst] = P;
8175     }
8176     if (!P)
8177       return nullptr;  // Not evolving from PHI
8178     if (PHI && PHI != P)
8179       return nullptr;  // Evolving from multiple different PHIs.
8180     PHI = P;
8181   }
8182   // This is a expression evolving from a constant PHI!
8183   return PHI;
8184 }
8185 
8186 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8187 /// in the loop that V is derived from.  We allow arbitrary operations along the
8188 /// way, but the operands of an operation must either be constants or a value
8189 /// derived from a constant PHI.  If this expression does not fit with these
8190 /// constraints, return null.
8191 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8192   Instruction *I = dyn_cast<Instruction>(V);
8193   if (!I || !canConstantEvolve(I, L)) return nullptr;
8194 
8195   if (PHINode *PN = dyn_cast<PHINode>(I))
8196     return PN;
8197 
8198   // Record non-constant instructions contained by the loop.
8199   DenseMap<Instruction *, PHINode *> PHIMap;
8200   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8201 }
8202 
8203 /// EvaluateExpression - Given an expression that passes the
8204 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8205 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8206 /// reason, return null.
8207 static Constant *EvaluateExpression(Value *V, const Loop *L,
8208                                     DenseMap<Instruction *, Constant *> &Vals,
8209                                     const DataLayout &DL,
8210                                     const TargetLibraryInfo *TLI) {
8211   // Convenient constant check, but redundant for recursive calls.
8212   if (Constant *C = dyn_cast<Constant>(V)) return C;
8213   Instruction *I = dyn_cast<Instruction>(V);
8214   if (!I) return nullptr;
8215 
8216   if (Constant *C = Vals.lookup(I)) return C;
8217 
8218   // An instruction inside the loop depends on a value outside the loop that we
8219   // weren't given a mapping for, or a value such as a call inside the loop.
8220   if (!canConstantEvolve(I, L)) return nullptr;
8221 
8222   // An unmapped PHI can be due to a branch or another loop inside this loop,
8223   // or due to this not being the initial iteration through a loop where we
8224   // couldn't compute the evolution of this particular PHI last time.
8225   if (isa<PHINode>(I)) return nullptr;
8226 
8227   std::vector<Constant*> Operands(I->getNumOperands());
8228 
8229   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8230     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8231     if (!Operand) {
8232       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8233       if (!Operands[i]) return nullptr;
8234       continue;
8235     }
8236     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8237     Vals[Operand] = C;
8238     if (!C) return nullptr;
8239     Operands[i] = C;
8240   }
8241 
8242   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8243     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8244                                            Operands[1], DL, TLI);
8245   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8246     if (!LI->isVolatile())
8247       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8248   }
8249   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8250 }
8251 
8252 
8253 // If every incoming value to PN except the one for BB is a specific Constant,
8254 // return that, else return nullptr.
8255 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8256   Constant *IncomingVal = nullptr;
8257 
8258   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8259     if (PN->getIncomingBlock(i) == BB)
8260       continue;
8261 
8262     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8263     if (!CurrentVal)
8264       return nullptr;
8265 
8266     if (IncomingVal != CurrentVal) {
8267       if (IncomingVal)
8268         return nullptr;
8269       IncomingVal = CurrentVal;
8270     }
8271   }
8272 
8273   return IncomingVal;
8274 }
8275 
8276 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8277 /// in the header of its containing loop, we know the loop executes a
8278 /// constant number of times, and the PHI node is just a recurrence
8279 /// involving constants, fold it.
8280 Constant *
8281 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8282                                                    const APInt &BEs,
8283                                                    const Loop *L) {
8284   auto I = ConstantEvolutionLoopExitValue.find(PN);
8285   if (I != ConstantEvolutionLoopExitValue.end())
8286     return I->second;
8287 
8288   if (BEs.ugt(MaxBruteForceIterations))
8289     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8290 
8291   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8292 
8293   DenseMap<Instruction *, Constant *> CurrentIterVals;
8294   BasicBlock *Header = L->getHeader();
8295   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8296 
8297   BasicBlock *Latch = L->getLoopLatch();
8298   if (!Latch)
8299     return nullptr;
8300 
8301   for (PHINode &PHI : Header->phis()) {
8302     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8303       CurrentIterVals[&PHI] = StartCST;
8304   }
8305   if (!CurrentIterVals.count(PN))
8306     return RetVal = nullptr;
8307 
8308   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8309 
8310   // Execute the loop symbolically to determine the exit value.
8311   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8312          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8313 
8314   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8315   unsigned IterationNum = 0;
8316   const DataLayout &DL = getDataLayout();
8317   for (; ; ++IterationNum) {
8318     if (IterationNum == NumIterations)
8319       return RetVal = CurrentIterVals[PN];  // Got exit value!
8320 
8321     // Compute the value of the PHIs for the next iteration.
8322     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8323     DenseMap<Instruction *, Constant *> NextIterVals;
8324     Constant *NextPHI =
8325         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8326     if (!NextPHI)
8327       return nullptr;        // Couldn't evaluate!
8328     NextIterVals[PN] = NextPHI;
8329 
8330     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8331 
8332     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8333     // cease to be able to evaluate one of them or if they stop evolving,
8334     // because that doesn't necessarily prevent us from computing PN.
8335     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8336     for (const auto &I : CurrentIterVals) {
8337       PHINode *PHI = dyn_cast<PHINode>(I.first);
8338       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8339       PHIsToCompute.emplace_back(PHI, I.second);
8340     }
8341     // We use two distinct loops because EvaluateExpression may invalidate any
8342     // iterators into CurrentIterVals.
8343     for (const auto &I : PHIsToCompute) {
8344       PHINode *PHI = I.first;
8345       Constant *&NextPHI = NextIterVals[PHI];
8346       if (!NextPHI) {   // Not already computed.
8347         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8348         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8349       }
8350       if (NextPHI != I.second)
8351         StoppedEvolving = false;
8352     }
8353 
8354     // If all entries in CurrentIterVals == NextIterVals then we can stop
8355     // iterating, the loop can't continue to change.
8356     if (StoppedEvolving)
8357       return RetVal = CurrentIterVals[PN];
8358 
8359     CurrentIterVals.swap(NextIterVals);
8360   }
8361 }
8362 
8363 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8364                                                           Value *Cond,
8365                                                           bool ExitWhen) {
8366   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8367   if (!PN) return getCouldNotCompute();
8368 
8369   // If the loop is canonicalized, the PHI will have exactly two entries.
8370   // That's the only form we support here.
8371   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8372 
8373   DenseMap<Instruction *, Constant *> CurrentIterVals;
8374   BasicBlock *Header = L->getHeader();
8375   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8376 
8377   BasicBlock *Latch = L->getLoopLatch();
8378   assert(Latch && "Should follow from NumIncomingValues == 2!");
8379 
8380   for (PHINode &PHI : Header->phis()) {
8381     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8382       CurrentIterVals[&PHI] = StartCST;
8383   }
8384   if (!CurrentIterVals.count(PN))
8385     return getCouldNotCompute();
8386 
8387   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8388   // the loop symbolically to determine when the condition gets a value of
8389   // "ExitWhen".
8390   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8391   const DataLayout &DL = getDataLayout();
8392   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8393     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8394         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8395 
8396     // Couldn't symbolically evaluate.
8397     if (!CondVal) return getCouldNotCompute();
8398 
8399     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8400       ++NumBruteForceTripCountsComputed;
8401       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8402     }
8403 
8404     // Update all the PHI nodes for the next iteration.
8405     DenseMap<Instruction *, Constant *> NextIterVals;
8406 
8407     // Create a list of which PHIs we need to compute. We want to do this before
8408     // calling EvaluateExpression on them because that may invalidate iterators
8409     // into CurrentIterVals.
8410     SmallVector<PHINode *, 8> PHIsToCompute;
8411     for (const auto &I : CurrentIterVals) {
8412       PHINode *PHI = dyn_cast<PHINode>(I.first);
8413       if (!PHI || PHI->getParent() != Header) continue;
8414       PHIsToCompute.push_back(PHI);
8415     }
8416     for (PHINode *PHI : PHIsToCompute) {
8417       Constant *&NextPHI = NextIterVals[PHI];
8418       if (NextPHI) continue;    // Already computed!
8419 
8420       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8421       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8422     }
8423     CurrentIterVals.swap(NextIterVals);
8424   }
8425 
8426   // Too many iterations were needed to evaluate.
8427   return getCouldNotCompute();
8428 }
8429 
8430 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8431   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8432       ValuesAtScopes[V];
8433   // Check to see if we've folded this expression at this loop before.
8434   for (auto &LS : Values)
8435     if (LS.first == L)
8436       return LS.second ? LS.second : V;
8437 
8438   Values.emplace_back(L, nullptr);
8439 
8440   // Otherwise compute it.
8441   const SCEV *C = computeSCEVAtScope(V, L);
8442   for (auto &LS : reverse(ValuesAtScopes[V]))
8443     if (LS.first == L) {
8444       LS.second = C;
8445       break;
8446     }
8447   return C;
8448 }
8449 
8450 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8451 /// will return Constants for objects which aren't represented by a
8452 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8453 /// Returns NULL if the SCEV isn't representable as a Constant.
8454 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8455   switch (V->getSCEVType()) {
8456   case scCouldNotCompute:
8457   case scAddRecExpr:
8458     return nullptr;
8459   case scConstant:
8460     return cast<SCEVConstant>(V)->getValue();
8461   case scUnknown:
8462     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8463   case scSignExtend: {
8464     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8465     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8466       return ConstantExpr::getSExt(CastOp, SS->getType());
8467     return nullptr;
8468   }
8469   case scZeroExtend: {
8470     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8471     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8472       return ConstantExpr::getZExt(CastOp, SZ->getType());
8473     return nullptr;
8474   }
8475   case scPtrToInt: {
8476     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8477     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8478       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8479 
8480     return nullptr;
8481   }
8482   case scTruncate: {
8483     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8484     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8485       return ConstantExpr::getTrunc(CastOp, ST->getType());
8486     return nullptr;
8487   }
8488   case scAddExpr: {
8489     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8490     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8491       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8492         unsigned AS = PTy->getAddressSpace();
8493         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8494         C = ConstantExpr::getBitCast(C, DestPtrTy);
8495       }
8496       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8497         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8498         if (!C2)
8499           return nullptr;
8500 
8501         // First pointer!
8502         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8503           unsigned AS = C2->getType()->getPointerAddressSpace();
8504           std::swap(C, C2);
8505           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8506           // The offsets have been converted to bytes.  We can add bytes to an
8507           // i8* by GEP with the byte count in the first index.
8508           C = ConstantExpr::getBitCast(C, DestPtrTy);
8509         }
8510 
8511         // Don't bother trying to sum two pointers. We probably can't
8512         // statically compute a load that results from it anyway.
8513         if (C2->getType()->isPointerTy())
8514           return nullptr;
8515 
8516         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8517           if (PTy->getElementType()->isStructTy())
8518             C2 = ConstantExpr::getIntegerCast(
8519                 C2, Type::getInt32Ty(C->getContext()), true);
8520           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8521         } else
8522           C = ConstantExpr::getAdd(C, C2);
8523       }
8524       return C;
8525     }
8526     return nullptr;
8527   }
8528   case scMulExpr: {
8529     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8530     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8531       // Don't bother with pointers at all.
8532       if (C->getType()->isPointerTy())
8533         return nullptr;
8534       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8535         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8536         if (!C2 || C2->getType()->isPointerTy())
8537           return nullptr;
8538         C = ConstantExpr::getMul(C, C2);
8539       }
8540       return C;
8541     }
8542     return nullptr;
8543   }
8544   case scUDivExpr: {
8545     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8546     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8547       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8548         if (LHS->getType() == RHS->getType())
8549           return ConstantExpr::getUDiv(LHS, RHS);
8550     return nullptr;
8551   }
8552   case scSMaxExpr:
8553   case scUMaxExpr:
8554   case scSMinExpr:
8555   case scUMinExpr:
8556     return nullptr; // TODO: smax, umax, smin, umax.
8557   }
8558   llvm_unreachable("Unknown SCEV kind!");
8559 }
8560 
8561 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8562   if (isa<SCEVConstant>(V)) return V;
8563 
8564   // If this instruction is evolved from a constant-evolving PHI, compute the
8565   // exit value from the loop without using SCEVs.
8566   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8567     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8568       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8569         const Loop *CurrLoop = this->LI[I->getParent()];
8570         // Looking for loop exit value.
8571         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8572             PN->getParent() == CurrLoop->getHeader()) {
8573           // Okay, there is no closed form solution for the PHI node.  Check
8574           // to see if the loop that contains it has a known backedge-taken
8575           // count.  If so, we may be able to force computation of the exit
8576           // value.
8577           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8578           // This trivial case can show up in some degenerate cases where
8579           // the incoming IR has not yet been fully simplified.
8580           if (BackedgeTakenCount->isZero()) {
8581             Value *InitValue = nullptr;
8582             bool MultipleInitValues = false;
8583             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8584               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8585                 if (!InitValue)
8586                   InitValue = PN->getIncomingValue(i);
8587                 else if (InitValue != PN->getIncomingValue(i)) {
8588                   MultipleInitValues = true;
8589                   break;
8590                 }
8591               }
8592             }
8593             if (!MultipleInitValues && InitValue)
8594               return getSCEV(InitValue);
8595           }
8596           // Do we have a loop invariant value flowing around the backedge
8597           // for a loop which must execute the backedge?
8598           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8599               isKnownPositive(BackedgeTakenCount) &&
8600               PN->getNumIncomingValues() == 2) {
8601 
8602             unsigned InLoopPred =
8603                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8604             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8605             if (CurrLoop->isLoopInvariant(BackedgeVal))
8606               return getSCEV(BackedgeVal);
8607           }
8608           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8609             // Okay, we know how many times the containing loop executes.  If
8610             // this is a constant evolving PHI node, get the final value at
8611             // the specified iteration number.
8612             Constant *RV = getConstantEvolutionLoopExitValue(
8613                 PN, BTCC->getAPInt(), CurrLoop);
8614             if (RV) return getSCEV(RV);
8615           }
8616         }
8617 
8618         // If there is a single-input Phi, evaluate it at our scope. If we can
8619         // prove that this replacement does not break LCSSA form, use new value.
8620         if (PN->getNumOperands() == 1) {
8621           const SCEV *Input = getSCEV(PN->getOperand(0));
8622           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8623           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8624           // for the simplest case just support constants.
8625           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8626         }
8627       }
8628 
8629       // Okay, this is an expression that we cannot symbolically evaluate
8630       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8631       // the arguments into constants, and if so, try to constant propagate the
8632       // result.  This is particularly useful for computing loop exit values.
8633       if (CanConstantFold(I)) {
8634         SmallVector<Constant *, 4> Operands;
8635         bool MadeImprovement = false;
8636         for (Value *Op : I->operands()) {
8637           if (Constant *C = dyn_cast<Constant>(Op)) {
8638             Operands.push_back(C);
8639             continue;
8640           }
8641 
8642           // If any of the operands is non-constant and if they are
8643           // non-integer and non-pointer, don't even try to analyze them
8644           // with scev techniques.
8645           if (!isSCEVable(Op->getType()))
8646             return V;
8647 
8648           const SCEV *OrigV = getSCEV(Op);
8649           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8650           MadeImprovement |= OrigV != OpV;
8651 
8652           Constant *C = BuildConstantFromSCEV(OpV);
8653           if (!C) return V;
8654           if (C->getType() != Op->getType())
8655             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8656                                                               Op->getType(),
8657                                                               false),
8658                                       C, Op->getType());
8659           Operands.push_back(C);
8660         }
8661 
8662         // Check to see if getSCEVAtScope actually made an improvement.
8663         if (MadeImprovement) {
8664           Constant *C = nullptr;
8665           const DataLayout &DL = getDataLayout();
8666           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8667             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8668                                                 Operands[1], DL, &TLI);
8669           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8670             if (!Load->isVolatile())
8671               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8672                                                DL);
8673           } else
8674             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8675           if (!C) return V;
8676           return getSCEV(C);
8677         }
8678       }
8679     }
8680 
8681     // This is some other type of SCEVUnknown, just return it.
8682     return V;
8683   }
8684 
8685   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8686     // Avoid performing the look-up in the common case where the specified
8687     // expression has no loop-variant portions.
8688     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8689       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8690       if (OpAtScope != Comm->getOperand(i)) {
8691         // Okay, at least one of these operands is loop variant but might be
8692         // foldable.  Build a new instance of the folded commutative expression.
8693         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8694                                             Comm->op_begin()+i);
8695         NewOps.push_back(OpAtScope);
8696 
8697         for (++i; i != e; ++i) {
8698           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8699           NewOps.push_back(OpAtScope);
8700         }
8701         if (isa<SCEVAddExpr>(Comm))
8702           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8703         if (isa<SCEVMulExpr>(Comm))
8704           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8705         if (isa<SCEVMinMaxExpr>(Comm))
8706           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8707         llvm_unreachable("Unknown commutative SCEV type!");
8708       }
8709     }
8710     // If we got here, all operands are loop invariant.
8711     return Comm;
8712   }
8713 
8714   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8715     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8716     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8717     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8718       return Div;   // must be loop invariant
8719     return getUDivExpr(LHS, RHS);
8720   }
8721 
8722   // If this is a loop recurrence for a loop that does not contain L, then we
8723   // are dealing with the final value computed by the loop.
8724   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8725     // First, attempt to evaluate each operand.
8726     // Avoid performing the look-up in the common case where the specified
8727     // expression has no loop-variant portions.
8728     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8729       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8730       if (OpAtScope == AddRec->getOperand(i))
8731         continue;
8732 
8733       // Okay, at least one of these operands is loop variant but might be
8734       // foldable.  Build a new instance of the folded commutative expression.
8735       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8736                                           AddRec->op_begin()+i);
8737       NewOps.push_back(OpAtScope);
8738       for (++i; i != e; ++i)
8739         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8740 
8741       const SCEV *FoldedRec =
8742         getAddRecExpr(NewOps, AddRec->getLoop(),
8743                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8744       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8745       // The addrec may be folded to a nonrecurrence, for example, if the
8746       // induction variable is multiplied by zero after constant folding. Go
8747       // ahead and return the folded value.
8748       if (!AddRec)
8749         return FoldedRec;
8750       break;
8751     }
8752 
8753     // If the scope is outside the addrec's loop, evaluate it by using the
8754     // loop exit value of the addrec.
8755     if (!AddRec->getLoop()->contains(L)) {
8756       // To evaluate this recurrence, we need to know how many times the AddRec
8757       // loop iterates.  Compute this now.
8758       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8759       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8760 
8761       // Then, evaluate the AddRec.
8762       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8763     }
8764 
8765     return AddRec;
8766   }
8767 
8768   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8769     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8770     if (Op == Cast->getOperand())
8771       return Cast;  // must be loop invariant
8772     return getZeroExtendExpr(Op, Cast->getType());
8773   }
8774 
8775   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8776     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8777     if (Op == Cast->getOperand())
8778       return Cast;  // must be loop invariant
8779     return getSignExtendExpr(Op, Cast->getType());
8780   }
8781 
8782   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8783     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8784     if (Op == Cast->getOperand())
8785       return Cast;  // must be loop invariant
8786     return getTruncateExpr(Op, Cast->getType());
8787   }
8788 
8789   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8790     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8791     if (Op == Cast->getOperand())
8792       return Cast; // must be loop invariant
8793     return getPtrToIntExpr(Op, Cast->getType());
8794   }
8795 
8796   llvm_unreachable("Unknown SCEV type!");
8797 }
8798 
8799 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8800   return getSCEVAtScope(getSCEV(V), L);
8801 }
8802 
8803 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8804   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8805     return stripInjectiveFunctions(ZExt->getOperand());
8806   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8807     return stripInjectiveFunctions(SExt->getOperand());
8808   return S;
8809 }
8810 
8811 /// Finds the minimum unsigned root of the following equation:
8812 ///
8813 ///     A * X = B (mod N)
8814 ///
8815 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8816 /// A and B isn't important.
8817 ///
8818 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8819 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8820                                                ScalarEvolution &SE) {
8821   uint32_t BW = A.getBitWidth();
8822   assert(BW == SE.getTypeSizeInBits(B->getType()));
8823   assert(A != 0 && "A must be non-zero.");
8824 
8825   // 1. D = gcd(A, N)
8826   //
8827   // The gcd of A and N may have only one prime factor: 2. The number of
8828   // trailing zeros in A is its multiplicity
8829   uint32_t Mult2 = A.countTrailingZeros();
8830   // D = 2^Mult2
8831 
8832   // 2. Check if B is divisible by D.
8833   //
8834   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8835   // is not less than multiplicity of this prime factor for D.
8836   if (SE.GetMinTrailingZeros(B) < Mult2)
8837     return SE.getCouldNotCompute();
8838 
8839   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8840   // modulo (N / D).
8841   //
8842   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8843   // (N / D) in general. The inverse itself always fits into BW bits, though,
8844   // so we immediately truncate it.
8845   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8846   APInt Mod(BW + 1, 0);
8847   Mod.setBit(BW - Mult2);  // Mod = N / D
8848   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8849 
8850   // 4. Compute the minimum unsigned root of the equation:
8851   // I * (B / D) mod (N / D)
8852   // To simplify the computation, we factor out the divide by D:
8853   // (I * B mod N) / D
8854   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8855   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8856 }
8857 
8858 /// For a given quadratic addrec, generate coefficients of the corresponding
8859 /// quadratic equation, multiplied by a common value to ensure that they are
8860 /// integers.
8861 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8862 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8863 /// were multiplied by, and BitWidth is the bit width of the original addrec
8864 /// coefficients.
8865 /// This function returns None if the addrec coefficients are not compile-
8866 /// time constants.
8867 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8868 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8869   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8870   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8871   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8872   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8873   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8874                     << *AddRec << '\n');
8875 
8876   // We currently can only solve this if the coefficients are constants.
8877   if (!LC || !MC || !NC) {
8878     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8879     return None;
8880   }
8881 
8882   APInt L = LC->getAPInt();
8883   APInt M = MC->getAPInt();
8884   APInt N = NC->getAPInt();
8885   assert(!N.isNullValue() && "This is not a quadratic addrec");
8886 
8887   unsigned BitWidth = LC->getAPInt().getBitWidth();
8888   unsigned NewWidth = BitWidth + 1;
8889   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8890                     << BitWidth << '\n');
8891   // The sign-extension (as opposed to a zero-extension) here matches the
8892   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8893   N = N.sext(NewWidth);
8894   M = M.sext(NewWidth);
8895   L = L.sext(NewWidth);
8896 
8897   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8898   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8899   //   L+M, L+2M+N, L+3M+3N, ...
8900   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8901   //
8902   // The equation Acc = 0 is then
8903   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8904   // In a quadratic form it becomes:
8905   //   N n^2 + (2M-N) n + 2L = 0.
8906 
8907   APInt A = N;
8908   APInt B = 2 * M - A;
8909   APInt C = 2 * L;
8910   APInt T = APInt(NewWidth, 2);
8911   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8912                     << "x + " << C << ", coeff bw: " << NewWidth
8913                     << ", multiplied by " << T << '\n');
8914   return std::make_tuple(A, B, C, T, BitWidth);
8915 }
8916 
8917 /// Helper function to compare optional APInts:
8918 /// (a) if X and Y both exist, return min(X, Y),
8919 /// (b) if neither X nor Y exist, return None,
8920 /// (c) if exactly one of X and Y exists, return that value.
8921 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8922   if (X.hasValue() && Y.hasValue()) {
8923     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8924     APInt XW = X->sextOrSelf(W);
8925     APInt YW = Y->sextOrSelf(W);
8926     return XW.slt(YW) ? *X : *Y;
8927   }
8928   if (!X.hasValue() && !Y.hasValue())
8929     return None;
8930   return X.hasValue() ? *X : *Y;
8931 }
8932 
8933 /// Helper function to truncate an optional APInt to a given BitWidth.
8934 /// When solving addrec-related equations, it is preferable to return a value
8935 /// that has the same bit width as the original addrec's coefficients. If the
8936 /// solution fits in the original bit width, truncate it (except for i1).
8937 /// Returning a value of a different bit width may inhibit some optimizations.
8938 ///
8939 /// In general, a solution to a quadratic equation generated from an addrec
8940 /// may require BW+1 bits, where BW is the bit width of the addrec's
8941 /// coefficients. The reason is that the coefficients of the quadratic
8942 /// equation are BW+1 bits wide (to avoid truncation when converting from
8943 /// the addrec to the equation).
8944 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8945   if (!X.hasValue())
8946     return None;
8947   unsigned W = X->getBitWidth();
8948   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8949     return X->trunc(BitWidth);
8950   return X;
8951 }
8952 
8953 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8954 /// iterations. The values L, M, N are assumed to be signed, and they
8955 /// should all have the same bit widths.
8956 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8957 /// where BW is the bit width of the addrec's coefficients.
8958 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8959 /// returned as such, otherwise the bit width of the returned value may
8960 /// be greater than BW.
8961 ///
8962 /// This function returns None if
8963 /// (a) the addrec coefficients are not constant, or
8964 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8965 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8966 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8967 static Optional<APInt>
8968 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8969   APInt A, B, C, M;
8970   unsigned BitWidth;
8971   auto T = GetQuadraticEquation(AddRec);
8972   if (!T.hasValue())
8973     return None;
8974 
8975   std::tie(A, B, C, M, BitWidth) = *T;
8976   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8977   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8978   if (!X.hasValue())
8979     return None;
8980 
8981   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8982   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8983   if (!V->isZero())
8984     return None;
8985 
8986   return TruncIfPossible(X, BitWidth);
8987 }
8988 
8989 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8990 /// iterations. The values M, N are assumed to be signed, and they
8991 /// should all have the same bit widths.
8992 /// Find the least n such that c(n) does not belong to the given range,
8993 /// while c(n-1) does.
8994 ///
8995 /// This function returns None if
8996 /// (a) the addrec coefficients are not constant, or
8997 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8998 ///     bounds of the range.
8999 static Optional<APInt>
9000 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9001                           const ConstantRange &Range, ScalarEvolution &SE) {
9002   assert(AddRec->getOperand(0)->isZero() &&
9003          "Starting value of addrec should be 0");
9004   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9005                     << Range << ", addrec " << *AddRec << '\n');
9006   // This case is handled in getNumIterationsInRange. Here we can assume that
9007   // we start in the range.
9008   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9009          "Addrec's initial value should be in range");
9010 
9011   APInt A, B, C, M;
9012   unsigned BitWidth;
9013   auto T = GetQuadraticEquation(AddRec);
9014   if (!T.hasValue())
9015     return None;
9016 
9017   // Be careful about the return value: there can be two reasons for not
9018   // returning an actual number. First, if no solutions to the equations
9019   // were found, and second, if the solutions don't leave the given range.
9020   // The first case means that the actual solution is "unknown", the second
9021   // means that it's known, but not valid. If the solution is unknown, we
9022   // cannot make any conclusions.
9023   // Return a pair: the optional solution and a flag indicating if the
9024   // solution was found.
9025   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9026     // Solve for signed overflow and unsigned overflow, pick the lower
9027     // solution.
9028     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9029                       << Bound << " (before multiplying by " << M << ")\n");
9030     Bound *= M; // The quadratic equation multiplier.
9031 
9032     Optional<APInt> SO = None;
9033     if (BitWidth > 1) {
9034       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9035                            "signed overflow\n");
9036       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9037     }
9038     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9039                          "unsigned overflow\n");
9040     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9041                                                               BitWidth+1);
9042 
9043     auto LeavesRange = [&] (const APInt &X) {
9044       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9045       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9046       if (Range.contains(V0->getValue()))
9047         return false;
9048       // X should be at least 1, so X-1 is non-negative.
9049       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9050       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9051       if (Range.contains(V1->getValue()))
9052         return true;
9053       return false;
9054     };
9055 
9056     // If SolveQuadraticEquationWrap returns None, it means that there can
9057     // be a solution, but the function failed to find it. We cannot treat it
9058     // as "no solution".
9059     if (!SO.hasValue() || !UO.hasValue())
9060       return { None, false };
9061 
9062     // Check the smaller value first to see if it leaves the range.
9063     // At this point, both SO and UO must have values.
9064     Optional<APInt> Min = MinOptional(SO, UO);
9065     if (LeavesRange(*Min))
9066       return { Min, true };
9067     Optional<APInt> Max = Min == SO ? UO : SO;
9068     if (LeavesRange(*Max))
9069       return { Max, true };
9070 
9071     // Solutions were found, but were eliminated, hence the "true".
9072     return { None, true };
9073   };
9074 
9075   std::tie(A, B, C, M, BitWidth) = *T;
9076   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9077   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9078   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9079   auto SL = SolveForBoundary(Lower);
9080   auto SU = SolveForBoundary(Upper);
9081   // If any of the solutions was unknown, no meaninigful conclusions can
9082   // be made.
9083   if (!SL.second || !SU.second)
9084     return None;
9085 
9086   // Claim: The correct solution is not some value between Min and Max.
9087   //
9088   // Justification: Assuming that Min and Max are different values, one of
9089   // them is when the first signed overflow happens, the other is when the
9090   // first unsigned overflow happens. Crossing the range boundary is only
9091   // possible via an overflow (treating 0 as a special case of it, modeling
9092   // an overflow as crossing k*2^W for some k).
9093   //
9094   // The interesting case here is when Min was eliminated as an invalid
9095   // solution, but Max was not. The argument is that if there was another
9096   // overflow between Min and Max, it would also have been eliminated if
9097   // it was considered.
9098   //
9099   // For a given boundary, it is possible to have two overflows of the same
9100   // type (signed/unsigned) without having the other type in between: this
9101   // can happen when the vertex of the parabola is between the iterations
9102   // corresponding to the overflows. This is only possible when the two
9103   // overflows cross k*2^W for the same k. In such case, if the second one
9104   // left the range (and was the first one to do so), the first overflow
9105   // would have to enter the range, which would mean that either we had left
9106   // the range before or that we started outside of it. Both of these cases
9107   // are contradictions.
9108   //
9109   // Claim: In the case where SolveForBoundary returns None, the correct
9110   // solution is not some value between the Max for this boundary and the
9111   // Min of the other boundary.
9112   //
9113   // Justification: Assume that we had such Max_A and Min_B corresponding
9114   // to range boundaries A and B and such that Max_A < Min_B. If there was
9115   // a solution between Max_A and Min_B, it would have to be caused by an
9116   // overflow corresponding to either A or B. It cannot correspond to B,
9117   // since Min_B is the first occurrence of such an overflow. If it
9118   // corresponded to A, it would have to be either a signed or an unsigned
9119   // overflow that is larger than both eliminated overflows for A. But
9120   // between the eliminated overflows and this overflow, the values would
9121   // cover the entire value space, thus crossing the other boundary, which
9122   // is a contradiction.
9123 
9124   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9125 }
9126 
9127 ScalarEvolution::ExitLimit
9128 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9129                               bool AllowPredicates) {
9130 
9131   // This is only used for loops with a "x != y" exit test. The exit condition
9132   // is now expressed as a single expression, V = x-y. So the exit test is
9133   // effectively V != 0.  We know and take advantage of the fact that this
9134   // expression only being used in a comparison by zero context.
9135 
9136   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9137   // If the value is a constant
9138   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9139     // If the value is already zero, the branch will execute zero times.
9140     if (C->getValue()->isZero()) return C;
9141     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9142   }
9143 
9144   const SCEVAddRecExpr *AddRec =
9145       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9146 
9147   if (!AddRec && AllowPredicates)
9148     // Try to make this an AddRec using runtime tests, in the first X
9149     // iterations of this loop, where X is the SCEV expression found by the
9150     // algorithm below.
9151     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9152 
9153   if (!AddRec || AddRec->getLoop() != L)
9154     return getCouldNotCompute();
9155 
9156   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9157   // the quadratic equation to solve it.
9158   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9159     // We can only use this value if the chrec ends up with an exact zero
9160     // value at this index.  When solving for "X*X != 5", for example, we
9161     // should not accept a root of 2.
9162     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9163       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9164       return ExitLimit(R, R, false, Predicates);
9165     }
9166     return getCouldNotCompute();
9167   }
9168 
9169   // Otherwise we can only handle this if it is affine.
9170   if (!AddRec->isAffine())
9171     return getCouldNotCompute();
9172 
9173   // If this is an affine expression, the execution count of this branch is
9174   // the minimum unsigned root of the following equation:
9175   //
9176   //     Start + Step*N = 0 (mod 2^BW)
9177   //
9178   // equivalent to:
9179   //
9180   //             Step*N = -Start (mod 2^BW)
9181   //
9182   // where BW is the common bit width of Start and Step.
9183 
9184   // Get the initial value for the loop.
9185   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9186   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9187 
9188   // For now we handle only constant steps.
9189   //
9190   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9191   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9192   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9193   // We have not yet seen any such cases.
9194   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9195   if (!StepC || StepC->getValue()->isZero())
9196     return getCouldNotCompute();
9197 
9198   // For positive steps (counting up until unsigned overflow):
9199   //   N = -Start/Step (as unsigned)
9200   // For negative steps (counting down to zero):
9201   //   N = Start/-Step
9202   // First compute the unsigned distance from zero in the direction of Step.
9203   bool CountDown = StepC->getAPInt().isNegative();
9204   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9205 
9206   // Handle unitary steps, which cannot wraparound.
9207   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9208   //   N = Distance (as unsigned)
9209   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9210     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9211     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9212     if (MaxBECountBase.ult(MaxBECount))
9213       MaxBECount = MaxBECountBase;
9214 
9215     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9216     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9217     // case, and see if we can improve the bound.
9218     //
9219     // Explicitly handling this here is necessary because getUnsignedRange
9220     // isn't context-sensitive; it doesn't know that we only care about the
9221     // range inside the loop.
9222     const SCEV *Zero = getZero(Distance->getType());
9223     const SCEV *One = getOne(Distance->getType());
9224     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9225     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9226       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9227       // as "unsigned_max(Distance + 1) - 1".
9228       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9229       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9230     }
9231     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9232   }
9233 
9234   // If the condition controls loop exit (the loop exits only if the expression
9235   // is true) and the addition is no-wrap we can use unsigned divide to
9236   // compute the backedge count.  In this case, the step may not divide the
9237   // distance, but we don't care because if the condition is "missed" the loop
9238   // will have undefined behavior due to wrapping.
9239   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9240       loopHasNoAbnormalExits(AddRec->getLoop())) {
9241     const SCEV *Exact =
9242         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9243     const SCEV *Max =
9244         Exact == getCouldNotCompute()
9245             ? Exact
9246             : getConstant(getUnsignedRangeMax(Exact));
9247     return ExitLimit(Exact, Max, false, Predicates);
9248   }
9249 
9250   // Solve the general equation.
9251   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9252                                                getNegativeSCEV(Start), *this);
9253   const SCEV *M = E == getCouldNotCompute()
9254                       ? E
9255                       : getConstant(getUnsignedRangeMax(E));
9256   return ExitLimit(E, M, false, Predicates);
9257 }
9258 
9259 ScalarEvolution::ExitLimit
9260 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9261   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9262   // handle them yet except for the trivial case.  This could be expanded in the
9263   // future as needed.
9264 
9265   // If the value is a constant, check to see if it is known to be non-zero
9266   // already.  If so, the backedge will execute zero times.
9267   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9268     if (!C->getValue()->isZero())
9269       return getZero(C->getType());
9270     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9271   }
9272 
9273   // We could implement others, but I really doubt anyone writes loops like
9274   // this, and if they did, they would already be constant folded.
9275   return getCouldNotCompute();
9276 }
9277 
9278 std::pair<const BasicBlock *, const BasicBlock *>
9279 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9280     const {
9281   // If the block has a unique predecessor, then there is no path from the
9282   // predecessor to the block that does not go through the direct edge
9283   // from the predecessor to the block.
9284   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9285     return {Pred, BB};
9286 
9287   // A loop's header is defined to be a block that dominates the loop.
9288   // If the header has a unique predecessor outside the loop, it must be
9289   // a block that has exactly one successor that can reach the loop.
9290   if (const Loop *L = LI.getLoopFor(BB))
9291     return {L->getLoopPredecessor(), L->getHeader()};
9292 
9293   return {nullptr, nullptr};
9294 }
9295 
9296 /// SCEV structural equivalence is usually sufficient for testing whether two
9297 /// expressions are equal, however for the purposes of looking for a condition
9298 /// guarding a loop, it can be useful to be a little more general, since a
9299 /// front-end may have replicated the controlling expression.
9300 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9301   // Quick check to see if they are the same SCEV.
9302   if (A == B) return true;
9303 
9304   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9305     // Not all instructions that are "identical" compute the same value.  For
9306     // instance, two distinct alloca instructions allocating the same type are
9307     // identical and do not read memory; but compute distinct values.
9308     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9309   };
9310 
9311   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9312   // two different instructions with the same value. Check for this case.
9313   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9314     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9315       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9316         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9317           if (ComputesEqualValues(AI, BI))
9318             return true;
9319 
9320   // Otherwise assume they may have a different value.
9321   return false;
9322 }
9323 
9324 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9325                                            const SCEV *&LHS, const SCEV *&RHS,
9326                                            unsigned Depth) {
9327   bool Changed = false;
9328   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9329   // '0 != 0'.
9330   auto TrivialCase = [&](bool TriviallyTrue) {
9331     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9332     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9333     return true;
9334   };
9335   // If we hit the max recursion limit bail out.
9336   if (Depth >= 3)
9337     return false;
9338 
9339   // Canonicalize a constant to the right side.
9340   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9341     // Check for both operands constant.
9342     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9343       if (ConstantExpr::getICmp(Pred,
9344                                 LHSC->getValue(),
9345                                 RHSC->getValue())->isNullValue())
9346         return TrivialCase(false);
9347       else
9348         return TrivialCase(true);
9349     }
9350     // Otherwise swap the operands to put the constant on the right.
9351     std::swap(LHS, RHS);
9352     Pred = ICmpInst::getSwappedPredicate(Pred);
9353     Changed = true;
9354   }
9355 
9356   // If we're comparing an addrec with a value which is loop-invariant in the
9357   // addrec's loop, put the addrec on the left. Also make a dominance check,
9358   // as both operands could be addrecs loop-invariant in each other's loop.
9359   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9360     const Loop *L = AR->getLoop();
9361     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9362       std::swap(LHS, RHS);
9363       Pred = ICmpInst::getSwappedPredicate(Pred);
9364       Changed = true;
9365     }
9366   }
9367 
9368   // If there's a constant operand, canonicalize comparisons with boundary
9369   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9370   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9371     const APInt &RA = RC->getAPInt();
9372 
9373     bool SimplifiedByConstantRange = false;
9374 
9375     if (!ICmpInst::isEquality(Pred)) {
9376       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9377       if (ExactCR.isFullSet())
9378         return TrivialCase(true);
9379       else if (ExactCR.isEmptySet())
9380         return TrivialCase(false);
9381 
9382       APInt NewRHS;
9383       CmpInst::Predicate NewPred;
9384       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9385           ICmpInst::isEquality(NewPred)) {
9386         // We were able to convert an inequality to an equality.
9387         Pred = NewPred;
9388         RHS = getConstant(NewRHS);
9389         Changed = SimplifiedByConstantRange = true;
9390       }
9391     }
9392 
9393     if (!SimplifiedByConstantRange) {
9394       switch (Pred) {
9395       default:
9396         break;
9397       case ICmpInst::ICMP_EQ:
9398       case ICmpInst::ICMP_NE:
9399         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9400         if (!RA)
9401           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9402             if (const SCEVMulExpr *ME =
9403                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9404               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9405                   ME->getOperand(0)->isAllOnesValue()) {
9406                 RHS = AE->getOperand(1);
9407                 LHS = ME->getOperand(1);
9408                 Changed = true;
9409               }
9410         break;
9411 
9412 
9413         // The "Should have been caught earlier!" messages refer to the fact
9414         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9415         // should have fired on the corresponding cases, and canonicalized the
9416         // check to trivial case.
9417 
9418       case ICmpInst::ICMP_UGE:
9419         assert(!RA.isMinValue() && "Should have been caught earlier!");
9420         Pred = ICmpInst::ICMP_UGT;
9421         RHS = getConstant(RA - 1);
9422         Changed = true;
9423         break;
9424       case ICmpInst::ICMP_ULE:
9425         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9426         Pred = ICmpInst::ICMP_ULT;
9427         RHS = getConstant(RA + 1);
9428         Changed = true;
9429         break;
9430       case ICmpInst::ICMP_SGE:
9431         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9432         Pred = ICmpInst::ICMP_SGT;
9433         RHS = getConstant(RA - 1);
9434         Changed = true;
9435         break;
9436       case ICmpInst::ICMP_SLE:
9437         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9438         Pred = ICmpInst::ICMP_SLT;
9439         RHS = getConstant(RA + 1);
9440         Changed = true;
9441         break;
9442       }
9443     }
9444   }
9445 
9446   // Check for obvious equality.
9447   if (HasSameValue(LHS, RHS)) {
9448     if (ICmpInst::isTrueWhenEqual(Pred))
9449       return TrivialCase(true);
9450     if (ICmpInst::isFalseWhenEqual(Pred))
9451       return TrivialCase(false);
9452   }
9453 
9454   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9455   // adding or subtracting 1 from one of the operands.
9456   switch (Pred) {
9457   case ICmpInst::ICMP_SLE:
9458     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9459       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9460                        SCEV::FlagNSW);
9461       Pred = ICmpInst::ICMP_SLT;
9462       Changed = true;
9463     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9464       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9465                        SCEV::FlagNSW);
9466       Pred = ICmpInst::ICMP_SLT;
9467       Changed = true;
9468     }
9469     break;
9470   case ICmpInst::ICMP_SGE:
9471     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9472       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9473                        SCEV::FlagNSW);
9474       Pred = ICmpInst::ICMP_SGT;
9475       Changed = true;
9476     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9477       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9478                        SCEV::FlagNSW);
9479       Pred = ICmpInst::ICMP_SGT;
9480       Changed = true;
9481     }
9482     break;
9483   case ICmpInst::ICMP_ULE:
9484     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9485       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9486                        SCEV::FlagNUW);
9487       Pred = ICmpInst::ICMP_ULT;
9488       Changed = true;
9489     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9490       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9491       Pred = ICmpInst::ICMP_ULT;
9492       Changed = true;
9493     }
9494     break;
9495   case ICmpInst::ICMP_UGE:
9496     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9497       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9498       Pred = ICmpInst::ICMP_UGT;
9499       Changed = true;
9500     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9501       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9502                        SCEV::FlagNUW);
9503       Pred = ICmpInst::ICMP_UGT;
9504       Changed = true;
9505     }
9506     break;
9507   default:
9508     break;
9509   }
9510 
9511   // TODO: More simplifications are possible here.
9512 
9513   // Recursively simplify until we either hit a recursion limit or nothing
9514   // changes.
9515   if (Changed)
9516     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9517 
9518   return Changed;
9519 }
9520 
9521 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9522   return getSignedRangeMax(S).isNegative();
9523 }
9524 
9525 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9526   return getSignedRangeMin(S).isStrictlyPositive();
9527 }
9528 
9529 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9530   return !getSignedRangeMin(S).isNegative();
9531 }
9532 
9533 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9534   return !getSignedRangeMax(S).isStrictlyPositive();
9535 }
9536 
9537 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9538   return isKnownNegative(S) || isKnownPositive(S);
9539 }
9540 
9541 std::pair<const SCEV *, const SCEV *>
9542 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9543   // Compute SCEV on entry of loop L.
9544   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9545   if (Start == getCouldNotCompute())
9546     return { Start, Start };
9547   // Compute post increment SCEV for loop L.
9548   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9549   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9550   return { Start, PostInc };
9551 }
9552 
9553 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9554                                           const SCEV *LHS, const SCEV *RHS) {
9555   // First collect all loops.
9556   SmallPtrSet<const Loop *, 8> LoopsUsed;
9557   getUsedLoops(LHS, LoopsUsed);
9558   getUsedLoops(RHS, LoopsUsed);
9559 
9560   if (LoopsUsed.empty())
9561     return false;
9562 
9563   // Domination relationship must be a linear order on collected loops.
9564 #ifndef NDEBUG
9565   for (auto *L1 : LoopsUsed)
9566     for (auto *L2 : LoopsUsed)
9567       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9568               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9569              "Domination relationship is not a linear order");
9570 #endif
9571 
9572   const Loop *MDL =
9573       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9574                         [&](const Loop *L1, const Loop *L2) {
9575          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9576        });
9577 
9578   // Get init and post increment value for LHS.
9579   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9580   // if LHS contains unknown non-invariant SCEV then bail out.
9581   if (SplitLHS.first == getCouldNotCompute())
9582     return false;
9583   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9584   // Get init and post increment value for RHS.
9585   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9586   // if RHS contains unknown non-invariant SCEV then bail out.
9587   if (SplitRHS.first == getCouldNotCompute())
9588     return false;
9589   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9590   // It is possible that init SCEV contains an invariant load but it does
9591   // not dominate MDL and is not available at MDL loop entry, so we should
9592   // check it here.
9593   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9594       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9595     return false;
9596 
9597   // It seems backedge guard check is faster than entry one so in some cases
9598   // it can speed up whole estimation by short circuit
9599   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9600                                      SplitRHS.second) &&
9601          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9602 }
9603 
9604 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9605                                        const SCEV *LHS, const SCEV *RHS) {
9606   // Canonicalize the inputs first.
9607   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9608 
9609   if (isKnownViaInduction(Pred, LHS, RHS))
9610     return true;
9611 
9612   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9613     return true;
9614 
9615   // Otherwise see what can be done with some simple reasoning.
9616   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9617 }
9618 
9619 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
9620                                                   const SCEV *LHS,
9621                                                   const SCEV *RHS) {
9622   if (isKnownPredicate(Pred, LHS, RHS))
9623     return true;
9624   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
9625     return false;
9626   return None;
9627 }
9628 
9629 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9630                                          const SCEV *LHS, const SCEV *RHS,
9631                                          const Instruction *Context) {
9632   // TODO: Analyze guards and assumes from Context's block.
9633   return isKnownPredicate(Pred, LHS, RHS) ||
9634          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9635 }
9636 
9637 Optional<bool>
9638 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
9639                                      const SCEV *RHS,
9640                                      const Instruction *Context) {
9641   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
9642   if (KnownWithoutContext)
9643     return KnownWithoutContext;
9644 
9645   if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS))
9646     return true;
9647   else if (isBasicBlockEntryGuardedByCond(Context->getParent(),
9648                                           ICmpInst::getInversePredicate(Pred),
9649                                           LHS, RHS))
9650     return false;
9651   return None;
9652 }
9653 
9654 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9655                                               const SCEVAddRecExpr *LHS,
9656                                               const SCEV *RHS) {
9657   const Loop *L = LHS->getLoop();
9658   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9659          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9660 }
9661 
9662 Optional<ScalarEvolution::MonotonicPredicateType>
9663 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9664                                            ICmpInst::Predicate Pred) {
9665   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9666 
9667 #ifndef NDEBUG
9668   // Verify an invariant: inverting the predicate should turn a monotonically
9669   // increasing change to a monotonically decreasing one, and vice versa.
9670   if (Result) {
9671     auto ResultSwapped =
9672         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9673 
9674     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9675     assert(ResultSwapped.getValue() != Result.getValue() &&
9676            "monotonicity should flip as we flip the predicate");
9677   }
9678 #endif
9679 
9680   return Result;
9681 }
9682 
9683 Optional<ScalarEvolution::MonotonicPredicateType>
9684 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9685                                                ICmpInst::Predicate Pred) {
9686   // A zero step value for LHS means the induction variable is essentially a
9687   // loop invariant value. We don't really depend on the predicate actually
9688   // flipping from false to true (for increasing predicates, and the other way
9689   // around for decreasing predicates), all we care about is that *if* the
9690   // predicate changes then it only changes from false to true.
9691   //
9692   // A zero step value in itself is not very useful, but there may be places
9693   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9694   // as general as possible.
9695 
9696   // Only handle LE/LT/GE/GT predicates.
9697   if (!ICmpInst::isRelational(Pred))
9698     return None;
9699 
9700   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9701   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9702          "Should be greater or less!");
9703 
9704   // Check that AR does not wrap.
9705   if (ICmpInst::isUnsigned(Pred)) {
9706     if (!LHS->hasNoUnsignedWrap())
9707       return None;
9708     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9709   } else {
9710     assert(ICmpInst::isSigned(Pred) &&
9711            "Relational predicate is either signed or unsigned!");
9712     if (!LHS->hasNoSignedWrap())
9713       return None;
9714 
9715     const SCEV *Step = LHS->getStepRecurrence(*this);
9716 
9717     if (isKnownNonNegative(Step))
9718       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9719 
9720     if (isKnownNonPositive(Step))
9721       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9722 
9723     return None;
9724   }
9725 }
9726 
9727 Optional<ScalarEvolution::LoopInvariantPredicate>
9728 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9729                                            const SCEV *LHS, const SCEV *RHS,
9730                                            const Loop *L) {
9731 
9732   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9733   if (!isLoopInvariant(RHS, L)) {
9734     if (!isLoopInvariant(LHS, L))
9735       return None;
9736 
9737     std::swap(LHS, RHS);
9738     Pred = ICmpInst::getSwappedPredicate(Pred);
9739   }
9740 
9741   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9742   if (!ArLHS || ArLHS->getLoop() != L)
9743     return None;
9744 
9745   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9746   if (!MonotonicType)
9747     return None;
9748   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9749   // true as the loop iterates, and the backedge is control dependent on
9750   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9751   //
9752   //   * if the predicate was false in the first iteration then the predicate
9753   //     is never evaluated again, since the loop exits without taking the
9754   //     backedge.
9755   //   * if the predicate was true in the first iteration then it will
9756   //     continue to be true for all future iterations since it is
9757   //     monotonically increasing.
9758   //
9759   // For both the above possibilities, we can replace the loop varying
9760   // predicate with its value on the first iteration of the loop (which is
9761   // loop invariant).
9762   //
9763   // A similar reasoning applies for a monotonically decreasing predicate, by
9764   // replacing true with false and false with true in the above two bullets.
9765   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9766   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9767 
9768   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9769     return None;
9770 
9771   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9772 }
9773 
9774 Optional<ScalarEvolution::LoopInvariantPredicate>
9775 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9776     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9777     const Instruction *Context, const SCEV *MaxIter) {
9778   // Try to prove the following set of facts:
9779   // - The predicate is monotonic in the iteration space.
9780   // - If the check does not fail on the 1st iteration:
9781   //   - No overflow will happen during first MaxIter iterations;
9782   //   - It will not fail on the MaxIter'th iteration.
9783   // If the check does fail on the 1st iteration, we leave the loop and no
9784   // other checks matter.
9785 
9786   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9787   if (!isLoopInvariant(RHS, L)) {
9788     if (!isLoopInvariant(LHS, L))
9789       return None;
9790 
9791     std::swap(LHS, RHS);
9792     Pred = ICmpInst::getSwappedPredicate(Pred);
9793   }
9794 
9795   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9796   if (!AR || AR->getLoop() != L)
9797     return None;
9798 
9799   // The predicate must be relational (i.e. <, <=, >=, >).
9800   if (!ICmpInst::isRelational(Pred))
9801     return None;
9802 
9803   // TODO: Support steps other than +/- 1.
9804   const SCEV *Step = AR->getStepRecurrence(*this);
9805   auto *One = getOne(Step->getType());
9806   auto *MinusOne = getNegativeSCEV(One);
9807   if (Step != One && Step != MinusOne)
9808     return None;
9809 
9810   // Type mismatch here means that MaxIter is potentially larger than max
9811   // unsigned value in start type, which mean we cannot prove no wrap for the
9812   // indvar.
9813   if (AR->getType() != MaxIter->getType())
9814     return None;
9815 
9816   // Value of IV on suggested last iteration.
9817   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9818   // Does it still meet the requirement?
9819   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
9820     return None;
9821   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9822   // not exceed max unsigned value of this type), this effectively proves
9823   // that there is no wrap during the iteration. To prove that there is no
9824   // signed/unsigned wrap, we need to check that
9825   // Start <= Last for step = 1 or Start >= Last for step = -1.
9826   ICmpInst::Predicate NoOverflowPred =
9827       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9828   if (Step == MinusOne)
9829     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9830   const SCEV *Start = AR->getStart();
9831   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9832     return None;
9833 
9834   // Everything is fine.
9835   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
9836 }
9837 
9838 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9839     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9840   if (HasSameValue(LHS, RHS))
9841     return ICmpInst::isTrueWhenEqual(Pred);
9842 
9843   // This code is split out from isKnownPredicate because it is called from
9844   // within isLoopEntryGuardedByCond.
9845 
9846   auto CheckRanges = [&](const ConstantRange &RangeLHS,
9847                          const ConstantRange &RangeRHS) {
9848     return RangeLHS.icmp(Pred, RangeRHS);
9849   };
9850 
9851   // The check at the top of the function catches the case where the values are
9852   // known to be equal.
9853   if (Pred == CmpInst::ICMP_EQ)
9854     return false;
9855 
9856   if (Pred == CmpInst::ICMP_NE)
9857     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9858            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9859            isKnownNonZero(getMinusSCEV(LHS, RHS));
9860 
9861   if (CmpInst::isSigned(Pred))
9862     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9863 
9864   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9865 }
9866 
9867 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9868                                                     const SCEV *LHS,
9869                                                     const SCEV *RHS) {
9870   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9871   // Return Y via OutY.
9872   auto MatchBinaryAddToConst =
9873       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9874              SCEV::NoWrapFlags ExpectedFlags) {
9875     const SCEV *NonConstOp, *ConstOp;
9876     SCEV::NoWrapFlags FlagsPresent;
9877 
9878     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9879         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9880       return false;
9881 
9882     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9883     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9884   };
9885 
9886   APInt C;
9887 
9888   switch (Pred) {
9889   default:
9890     break;
9891 
9892   case ICmpInst::ICMP_SGE:
9893     std::swap(LHS, RHS);
9894     LLVM_FALLTHROUGH;
9895   case ICmpInst::ICMP_SLE:
9896     // X s<= (X + C)<nsw> if C >= 0
9897     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9898       return true;
9899 
9900     // (X + C)<nsw> s<= X if C <= 0
9901     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9902         !C.isStrictlyPositive())
9903       return true;
9904     break;
9905 
9906   case ICmpInst::ICMP_SGT:
9907     std::swap(LHS, RHS);
9908     LLVM_FALLTHROUGH;
9909   case ICmpInst::ICMP_SLT:
9910     // X s< (X + C)<nsw> if C > 0
9911     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9912         C.isStrictlyPositive())
9913       return true;
9914 
9915     // (X + C)<nsw> s< X if C < 0
9916     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9917       return true;
9918     break;
9919 
9920   case ICmpInst::ICMP_UGE:
9921     std::swap(LHS, RHS);
9922     LLVM_FALLTHROUGH;
9923   case ICmpInst::ICMP_ULE:
9924     // X u<= (X + C)<nuw> for any C
9925     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9926       return true;
9927     break;
9928 
9929   case ICmpInst::ICMP_UGT:
9930     std::swap(LHS, RHS);
9931     LLVM_FALLTHROUGH;
9932   case ICmpInst::ICMP_ULT:
9933     // X u< (X + C)<nuw> if C != 0
9934     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9935       return true;
9936     break;
9937   }
9938 
9939   return false;
9940 }
9941 
9942 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9943                                                    const SCEV *LHS,
9944                                                    const SCEV *RHS) {
9945   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9946     return false;
9947 
9948   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9949   // the stack can result in exponential time complexity.
9950   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9951 
9952   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9953   //
9954   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9955   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9956   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9957   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9958   // use isKnownPredicate later if needed.
9959   return isKnownNonNegative(RHS) &&
9960          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9961          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9962 }
9963 
9964 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9965                                         ICmpInst::Predicate Pred,
9966                                         const SCEV *LHS, const SCEV *RHS) {
9967   // No need to even try if we know the module has no guards.
9968   if (!HasGuards)
9969     return false;
9970 
9971   return any_of(*BB, [&](const Instruction &I) {
9972     using namespace llvm::PatternMatch;
9973 
9974     Value *Condition;
9975     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9976                          m_Value(Condition))) &&
9977            isImpliedCond(Pred, LHS, RHS, Condition, false);
9978   });
9979 }
9980 
9981 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9982 /// protected by a conditional between LHS and RHS.  This is used to
9983 /// to eliminate casts.
9984 bool
9985 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9986                                              ICmpInst::Predicate Pred,
9987                                              const SCEV *LHS, const SCEV *RHS) {
9988   // Interpret a null as meaning no loop, where there is obviously no guard
9989   // (interprocedural conditions notwithstanding).
9990   if (!L) return true;
9991 
9992   if (VerifyIR)
9993     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9994            "This cannot be done on broken IR!");
9995 
9996 
9997   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9998     return true;
9999 
10000   BasicBlock *Latch = L->getLoopLatch();
10001   if (!Latch)
10002     return false;
10003 
10004   BranchInst *LoopContinuePredicate =
10005     dyn_cast<BranchInst>(Latch->getTerminator());
10006   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10007       isImpliedCond(Pred, LHS, RHS,
10008                     LoopContinuePredicate->getCondition(),
10009                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10010     return true;
10011 
10012   // We don't want more than one activation of the following loops on the stack
10013   // -- that can lead to O(n!) time complexity.
10014   if (WalkingBEDominatingConds)
10015     return false;
10016 
10017   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10018 
10019   // See if we can exploit a trip count to prove the predicate.
10020   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10021   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10022   if (LatchBECount != getCouldNotCompute()) {
10023     // We know that Latch branches back to the loop header exactly
10024     // LatchBECount times.  This means the backdege condition at Latch is
10025     // equivalent to  "{0,+,1} u< LatchBECount".
10026     Type *Ty = LatchBECount->getType();
10027     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10028     const SCEV *LoopCounter =
10029       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10030     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10031                       LatchBECount))
10032       return true;
10033   }
10034 
10035   // Check conditions due to any @llvm.assume intrinsics.
10036   for (auto &AssumeVH : AC.assumptions()) {
10037     if (!AssumeVH)
10038       continue;
10039     auto *CI = cast<CallInst>(AssumeVH);
10040     if (!DT.dominates(CI, Latch->getTerminator()))
10041       continue;
10042 
10043     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10044       return true;
10045   }
10046 
10047   // If the loop is not reachable from the entry block, we risk running into an
10048   // infinite loop as we walk up into the dom tree.  These loops do not matter
10049   // anyway, so we just return a conservative answer when we see them.
10050   if (!DT.isReachableFromEntry(L->getHeader()))
10051     return false;
10052 
10053   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10054     return true;
10055 
10056   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10057        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10058     assert(DTN && "should reach the loop header before reaching the root!");
10059 
10060     BasicBlock *BB = DTN->getBlock();
10061     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10062       return true;
10063 
10064     BasicBlock *PBB = BB->getSinglePredecessor();
10065     if (!PBB)
10066       continue;
10067 
10068     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10069     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10070       continue;
10071 
10072     Value *Condition = ContinuePredicate->getCondition();
10073 
10074     // If we have an edge `E` within the loop body that dominates the only
10075     // latch, the condition guarding `E` also guards the backedge.  This
10076     // reasoning works only for loops with a single latch.
10077 
10078     BasicBlockEdge DominatingEdge(PBB, BB);
10079     if (DominatingEdge.isSingleEdge()) {
10080       // We're constructively (and conservatively) enumerating edges within the
10081       // loop body that dominate the latch.  The dominator tree better agree
10082       // with us on this:
10083       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10084 
10085       if (isImpliedCond(Pred, LHS, RHS, Condition,
10086                         BB != ContinuePredicate->getSuccessor(0)))
10087         return true;
10088     }
10089   }
10090 
10091   return false;
10092 }
10093 
10094 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10095                                                      ICmpInst::Predicate Pred,
10096                                                      const SCEV *LHS,
10097                                                      const SCEV *RHS) {
10098   if (VerifyIR)
10099     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10100            "This cannot be done on broken IR!");
10101 
10102   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10103   // the facts (a >= b && a != b) separately. A typical situation is when the
10104   // non-strict comparison is known from ranges and non-equality is known from
10105   // dominating predicates. If we are proving strict comparison, we always try
10106   // to prove non-equality and non-strict comparison separately.
10107   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10108   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10109   bool ProvedNonStrictComparison = false;
10110   bool ProvedNonEquality = false;
10111 
10112   auto SplitAndProve =
10113     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10114     if (!ProvedNonStrictComparison)
10115       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10116     if (!ProvedNonEquality)
10117       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10118     if (ProvedNonStrictComparison && ProvedNonEquality)
10119       return true;
10120     return false;
10121   };
10122 
10123   if (ProvingStrictComparison) {
10124     auto ProofFn = [&](ICmpInst::Predicate P) {
10125       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10126     };
10127     if (SplitAndProve(ProofFn))
10128       return true;
10129   }
10130 
10131   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10132   auto ProveViaGuard = [&](const BasicBlock *Block) {
10133     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10134       return true;
10135     if (ProvingStrictComparison) {
10136       auto ProofFn = [&](ICmpInst::Predicate P) {
10137         return isImpliedViaGuard(Block, P, LHS, RHS);
10138       };
10139       if (SplitAndProve(ProofFn))
10140         return true;
10141     }
10142     return false;
10143   };
10144 
10145   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10146   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10147     const Instruction *Context = &BB->front();
10148     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10149       return true;
10150     if (ProvingStrictComparison) {
10151       auto ProofFn = [&](ICmpInst::Predicate P) {
10152         return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context);
10153       };
10154       if (SplitAndProve(ProofFn))
10155         return true;
10156     }
10157     return false;
10158   };
10159 
10160   // Starting at the block's predecessor, climb up the predecessor chain, as long
10161   // as there are predecessors that can be found that have unique successors
10162   // leading to the original block.
10163   const Loop *ContainingLoop = LI.getLoopFor(BB);
10164   const BasicBlock *PredBB;
10165   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10166     PredBB = ContainingLoop->getLoopPredecessor();
10167   else
10168     PredBB = BB->getSinglePredecessor();
10169   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10170        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10171     if (ProveViaGuard(Pair.first))
10172       return true;
10173 
10174     const BranchInst *LoopEntryPredicate =
10175         dyn_cast<BranchInst>(Pair.first->getTerminator());
10176     if (!LoopEntryPredicate ||
10177         LoopEntryPredicate->isUnconditional())
10178       continue;
10179 
10180     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10181                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10182       return true;
10183   }
10184 
10185   // Check conditions due to any @llvm.assume intrinsics.
10186   for (auto &AssumeVH : AC.assumptions()) {
10187     if (!AssumeVH)
10188       continue;
10189     auto *CI = cast<CallInst>(AssumeVH);
10190     if (!DT.dominates(CI, BB))
10191       continue;
10192 
10193     if (ProveViaCond(CI->getArgOperand(0), false))
10194       return true;
10195   }
10196 
10197   return false;
10198 }
10199 
10200 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10201                                                ICmpInst::Predicate Pred,
10202                                                const SCEV *LHS,
10203                                                const SCEV *RHS) {
10204   // Interpret a null as meaning no loop, where there is obviously no guard
10205   // (interprocedural conditions notwithstanding).
10206   if (!L)
10207     return false;
10208 
10209   // Both LHS and RHS must be available at loop entry.
10210   assert(isAvailableAtLoopEntry(LHS, L) &&
10211          "LHS is not available at Loop Entry");
10212   assert(isAvailableAtLoopEntry(RHS, L) &&
10213          "RHS is not available at Loop Entry");
10214 
10215   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10216     return true;
10217 
10218   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10219 }
10220 
10221 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10222                                     const SCEV *RHS,
10223                                     const Value *FoundCondValue, bool Inverse,
10224                                     const Instruction *Context) {
10225   // False conditions implies anything. Do not bother analyzing it further.
10226   if (FoundCondValue ==
10227       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10228     return true;
10229 
10230   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10231     return false;
10232 
10233   auto ClearOnExit =
10234       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10235 
10236   // Recursively handle And and Or conditions.
10237   const Value *Op0, *Op1;
10238   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10239     if (!Inverse)
10240       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10241               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10242   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10243     if (Inverse)
10244       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10245               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10246   }
10247 
10248   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10249   if (!ICI) return false;
10250 
10251   // Now that we found a conditional branch that dominates the loop or controls
10252   // the loop latch. Check to see if it is the comparison we are looking for.
10253   ICmpInst::Predicate FoundPred;
10254   if (Inverse)
10255     FoundPred = ICI->getInversePredicate();
10256   else
10257     FoundPred = ICI->getPredicate();
10258 
10259   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10260   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10261 
10262   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10263 }
10264 
10265 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10266                                     const SCEV *RHS,
10267                                     ICmpInst::Predicate FoundPred,
10268                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10269                                     const Instruction *Context) {
10270   // Balance the types.
10271   if (getTypeSizeInBits(LHS->getType()) <
10272       getTypeSizeInBits(FoundLHS->getType())) {
10273     // For unsigned and equality predicates, try to prove that both found
10274     // operands fit into narrow unsigned range. If so, try to prove facts in
10275     // narrow types.
10276     if (!CmpInst::isSigned(FoundPred)) {
10277       auto *NarrowType = LHS->getType();
10278       auto *WideType = FoundLHS->getType();
10279       auto BitWidth = getTypeSizeInBits(NarrowType);
10280       const SCEV *MaxValue = getZeroExtendExpr(
10281           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10282       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10283           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10284         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10285         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10286         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10287                                        TruncFoundRHS, Context))
10288           return true;
10289       }
10290     }
10291 
10292     if (CmpInst::isSigned(Pred)) {
10293       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10294       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10295     } else {
10296       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10297       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10298     }
10299   } else if (getTypeSizeInBits(LHS->getType()) >
10300       getTypeSizeInBits(FoundLHS->getType())) {
10301     if (CmpInst::isSigned(FoundPred)) {
10302       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10303       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10304     } else {
10305       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10306       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10307     }
10308   }
10309   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10310                                     FoundRHS, Context);
10311 }
10312 
10313 bool ScalarEvolution::isImpliedCondBalancedTypes(
10314     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10315     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10316     const Instruction *Context) {
10317   assert(getTypeSizeInBits(LHS->getType()) ==
10318              getTypeSizeInBits(FoundLHS->getType()) &&
10319          "Types should be balanced!");
10320   // Canonicalize the query to match the way instcombine will have
10321   // canonicalized the comparison.
10322   if (SimplifyICmpOperands(Pred, LHS, RHS))
10323     if (LHS == RHS)
10324       return CmpInst::isTrueWhenEqual(Pred);
10325   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10326     if (FoundLHS == FoundRHS)
10327       return CmpInst::isFalseWhenEqual(FoundPred);
10328 
10329   // Check to see if we can make the LHS or RHS match.
10330   if (LHS == FoundRHS || RHS == FoundLHS) {
10331     if (isa<SCEVConstant>(RHS)) {
10332       std::swap(FoundLHS, FoundRHS);
10333       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10334     } else {
10335       std::swap(LHS, RHS);
10336       Pred = ICmpInst::getSwappedPredicate(Pred);
10337     }
10338   }
10339 
10340   // Check whether the found predicate is the same as the desired predicate.
10341   if (FoundPred == Pred)
10342     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10343 
10344   // Check whether swapping the found predicate makes it the same as the
10345   // desired predicate.
10346   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10347     // We can write the implication
10348     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10349     // using one of the following ways:
10350     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10351     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10352     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10353     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10354     // Forms 1. and 2. require swapping the operands of one condition. Don't
10355     // do this if it would break canonical constant/addrec ordering.
10356     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10357       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10358                                    Context);
10359     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10360       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10361 
10362     // There's no clear preference between forms 3. and 4., try both.
10363     return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10364                                  FoundLHS, FoundRHS, Context) ||
10365            isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10366                                  getNotSCEV(FoundRHS), Context);
10367   }
10368 
10369   // Unsigned comparison is the same as signed comparison when both the operands
10370   // are non-negative.
10371   if (CmpInst::isUnsigned(FoundPred) &&
10372       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10373       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10374     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10375 
10376   // Check if we can make progress by sharpening ranges.
10377   if (FoundPred == ICmpInst::ICMP_NE &&
10378       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10379 
10380     const SCEVConstant *C = nullptr;
10381     const SCEV *V = nullptr;
10382 
10383     if (isa<SCEVConstant>(FoundLHS)) {
10384       C = cast<SCEVConstant>(FoundLHS);
10385       V = FoundRHS;
10386     } else {
10387       C = cast<SCEVConstant>(FoundRHS);
10388       V = FoundLHS;
10389     }
10390 
10391     // The guarding predicate tells us that C != V. If the known range
10392     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10393     // range we consider has to correspond to same signedness as the
10394     // predicate we're interested in folding.
10395 
10396     APInt Min = ICmpInst::isSigned(Pred) ?
10397         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10398 
10399     if (Min == C->getAPInt()) {
10400       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10401       // This is true even if (Min + 1) wraps around -- in case of
10402       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10403 
10404       APInt SharperMin = Min + 1;
10405 
10406       switch (Pred) {
10407         case ICmpInst::ICMP_SGE:
10408         case ICmpInst::ICMP_UGE:
10409           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10410           // RHS, we're done.
10411           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10412                                     Context))
10413             return true;
10414           LLVM_FALLTHROUGH;
10415 
10416         case ICmpInst::ICMP_SGT:
10417         case ICmpInst::ICMP_UGT:
10418           // We know from the range information that (V `Pred` Min ||
10419           // V == Min).  We know from the guarding condition that !(V
10420           // == Min).  This gives us
10421           //
10422           //       V `Pred` Min || V == Min && !(V == Min)
10423           //   =>  V `Pred` Min
10424           //
10425           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10426 
10427           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10428                                     Context))
10429             return true;
10430           break;
10431 
10432         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10433         case ICmpInst::ICMP_SLE:
10434         case ICmpInst::ICMP_ULE:
10435           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10436                                     LHS, V, getConstant(SharperMin), Context))
10437             return true;
10438           LLVM_FALLTHROUGH;
10439 
10440         case ICmpInst::ICMP_SLT:
10441         case ICmpInst::ICMP_ULT:
10442           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10443                                     LHS, V, getConstant(Min), Context))
10444             return true;
10445           break;
10446 
10447         default:
10448           // No change
10449           break;
10450       }
10451     }
10452   }
10453 
10454   // Check whether the actual condition is beyond sufficient.
10455   if (FoundPred == ICmpInst::ICMP_EQ)
10456     if (ICmpInst::isTrueWhenEqual(Pred))
10457       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10458         return true;
10459   if (Pred == ICmpInst::ICMP_NE)
10460     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10461       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10462                                 Context))
10463         return true;
10464 
10465   // Otherwise assume the worst.
10466   return false;
10467 }
10468 
10469 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10470                                      const SCEV *&L, const SCEV *&R,
10471                                      SCEV::NoWrapFlags &Flags) {
10472   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10473   if (!AE || AE->getNumOperands() != 2)
10474     return false;
10475 
10476   L = AE->getOperand(0);
10477   R = AE->getOperand(1);
10478   Flags = AE->getNoWrapFlags();
10479   return true;
10480 }
10481 
10482 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10483                                                            const SCEV *Less) {
10484   // We avoid subtracting expressions here because this function is usually
10485   // fairly deep in the call stack (i.e. is called many times).
10486 
10487   // X - X = 0.
10488   if (More == Less)
10489     return APInt(getTypeSizeInBits(More->getType()), 0);
10490 
10491   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10492     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10493     const auto *MAR = cast<SCEVAddRecExpr>(More);
10494 
10495     if (LAR->getLoop() != MAR->getLoop())
10496       return None;
10497 
10498     // We look at affine expressions only; not for correctness but to keep
10499     // getStepRecurrence cheap.
10500     if (!LAR->isAffine() || !MAR->isAffine())
10501       return None;
10502 
10503     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10504       return None;
10505 
10506     Less = LAR->getStart();
10507     More = MAR->getStart();
10508 
10509     // fall through
10510   }
10511 
10512   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10513     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10514     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10515     return M - L;
10516   }
10517 
10518   SCEV::NoWrapFlags Flags;
10519   const SCEV *LLess = nullptr, *RLess = nullptr;
10520   const SCEV *LMore = nullptr, *RMore = nullptr;
10521   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10522   // Compare (X + C1) vs X.
10523   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10524     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10525       if (RLess == More)
10526         return -(C1->getAPInt());
10527 
10528   // Compare X vs (X + C2).
10529   if (splitBinaryAdd(More, LMore, RMore, Flags))
10530     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10531       if (RMore == Less)
10532         return C2->getAPInt();
10533 
10534   // Compare (X + C1) vs (X + C2).
10535   if (C1 && C2 && RLess == RMore)
10536     return C2->getAPInt() - C1->getAPInt();
10537 
10538   return None;
10539 }
10540 
10541 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10542     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10543     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10544   // Try to recognize the following pattern:
10545   //
10546   //   FoundRHS = ...
10547   // ...
10548   // loop:
10549   //   FoundLHS = {Start,+,W}
10550   // context_bb: // Basic block from the same loop
10551   //   known(Pred, FoundLHS, FoundRHS)
10552   //
10553   // If some predicate is known in the context of a loop, it is also known on
10554   // each iteration of this loop, including the first iteration. Therefore, in
10555   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10556   // prove the original pred using this fact.
10557   if (!Context)
10558     return false;
10559   const BasicBlock *ContextBB = Context->getParent();
10560   // Make sure AR varies in the context block.
10561   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10562     const Loop *L = AR->getLoop();
10563     // Make sure that context belongs to the loop and executes on 1st iteration
10564     // (if it ever executes at all).
10565     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10566       return false;
10567     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10568       return false;
10569     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10570   }
10571 
10572   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10573     const Loop *L = AR->getLoop();
10574     // Make sure that context belongs to the loop and executes on 1st iteration
10575     // (if it ever executes at all).
10576     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10577       return false;
10578     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10579       return false;
10580     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10581   }
10582 
10583   return false;
10584 }
10585 
10586 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10587     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10588     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10589   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10590     return false;
10591 
10592   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10593   if (!AddRecLHS)
10594     return false;
10595 
10596   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10597   if (!AddRecFoundLHS)
10598     return false;
10599 
10600   // We'd like to let SCEV reason about control dependencies, so we constrain
10601   // both the inequalities to be about add recurrences on the same loop.  This
10602   // way we can use isLoopEntryGuardedByCond later.
10603 
10604   const Loop *L = AddRecFoundLHS->getLoop();
10605   if (L != AddRecLHS->getLoop())
10606     return false;
10607 
10608   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10609   //
10610   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10611   //                                                                  ... (2)
10612   //
10613   // Informal proof for (2), assuming (1) [*]:
10614   //
10615   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10616   //
10617   // Then
10618   //
10619   //       FoundLHS s< FoundRHS s< INT_MIN - C
10620   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10621   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10622   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10623   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10624   // <=>  FoundLHS + C s< FoundRHS + C
10625   //
10626   // [*]: (1) can be proved by ruling out overflow.
10627   //
10628   // [**]: This can be proved by analyzing all the four possibilities:
10629   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10630   //    (A s>= 0, B s>= 0).
10631   //
10632   // Note:
10633   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10634   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10635   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10636   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10637   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10638   // C)".
10639 
10640   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10641   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10642   if (!LDiff || !RDiff || *LDiff != *RDiff)
10643     return false;
10644 
10645   if (LDiff->isMinValue())
10646     return true;
10647 
10648   APInt FoundRHSLimit;
10649 
10650   if (Pred == CmpInst::ICMP_ULT) {
10651     FoundRHSLimit = -(*RDiff);
10652   } else {
10653     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10654     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10655   }
10656 
10657   // Try to prove (1) or (2), as needed.
10658   return isAvailableAtLoopEntry(FoundRHS, L) &&
10659          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10660                                   getConstant(FoundRHSLimit));
10661 }
10662 
10663 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10664                                         const SCEV *LHS, const SCEV *RHS,
10665                                         const SCEV *FoundLHS,
10666                                         const SCEV *FoundRHS, unsigned Depth) {
10667   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10668 
10669   auto ClearOnExit = make_scope_exit([&]() {
10670     if (LPhi) {
10671       bool Erased = PendingMerges.erase(LPhi);
10672       assert(Erased && "Failed to erase LPhi!");
10673       (void)Erased;
10674     }
10675     if (RPhi) {
10676       bool Erased = PendingMerges.erase(RPhi);
10677       assert(Erased && "Failed to erase RPhi!");
10678       (void)Erased;
10679     }
10680   });
10681 
10682   // Find respective Phis and check that they are not being pending.
10683   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10684     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10685       if (!PendingMerges.insert(Phi).second)
10686         return false;
10687       LPhi = Phi;
10688     }
10689   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10690     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10691       // If we detect a loop of Phi nodes being processed by this method, for
10692       // example:
10693       //
10694       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10695       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10696       //
10697       // we don't want to deal with a case that complex, so return conservative
10698       // answer false.
10699       if (!PendingMerges.insert(Phi).second)
10700         return false;
10701       RPhi = Phi;
10702     }
10703 
10704   // If none of LHS, RHS is a Phi, nothing to do here.
10705   if (!LPhi && !RPhi)
10706     return false;
10707 
10708   // If there is a SCEVUnknown Phi we are interested in, make it left.
10709   if (!LPhi) {
10710     std::swap(LHS, RHS);
10711     std::swap(FoundLHS, FoundRHS);
10712     std::swap(LPhi, RPhi);
10713     Pred = ICmpInst::getSwappedPredicate(Pred);
10714   }
10715 
10716   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10717   const BasicBlock *LBB = LPhi->getParent();
10718   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10719 
10720   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10721     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10722            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10723            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10724   };
10725 
10726   if (RPhi && RPhi->getParent() == LBB) {
10727     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10728     // If we compare two Phis from the same block, and for each entry block
10729     // the predicate is true for incoming values from this block, then the
10730     // predicate is also true for the Phis.
10731     for (const BasicBlock *IncBB : predecessors(LBB)) {
10732       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10733       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10734       if (!ProvedEasily(L, R))
10735         return false;
10736     }
10737   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10738     // Case two: RHS is also a Phi from the same basic block, and it is an
10739     // AddRec. It means that there is a loop which has both AddRec and Unknown
10740     // PHIs, for it we can compare incoming values of AddRec from above the loop
10741     // and latch with their respective incoming values of LPhi.
10742     // TODO: Generalize to handle loops with many inputs in a header.
10743     if (LPhi->getNumIncomingValues() != 2) return false;
10744 
10745     auto *RLoop = RAR->getLoop();
10746     auto *Predecessor = RLoop->getLoopPredecessor();
10747     assert(Predecessor && "Loop with AddRec with no predecessor?");
10748     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10749     if (!ProvedEasily(L1, RAR->getStart()))
10750       return false;
10751     auto *Latch = RLoop->getLoopLatch();
10752     assert(Latch && "Loop with AddRec with no latch?");
10753     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10754     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10755       return false;
10756   } else {
10757     // In all other cases go over inputs of LHS and compare each of them to RHS,
10758     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10759     // At this point RHS is either a non-Phi, or it is a Phi from some block
10760     // different from LBB.
10761     for (const BasicBlock *IncBB : predecessors(LBB)) {
10762       // Check that RHS is available in this block.
10763       if (!dominates(RHS, IncBB))
10764         return false;
10765       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10766       if (!ProvedEasily(L, RHS))
10767         return false;
10768     }
10769   }
10770   return true;
10771 }
10772 
10773 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10774                                             const SCEV *LHS, const SCEV *RHS,
10775                                             const SCEV *FoundLHS,
10776                                             const SCEV *FoundRHS,
10777                                             const Instruction *Context) {
10778   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10779     return true;
10780 
10781   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10782     return true;
10783 
10784   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10785                                           Context))
10786     return true;
10787 
10788   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10789                                      FoundLHS, FoundRHS);
10790 }
10791 
10792 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10793 template <typename MinMaxExprType>
10794 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10795                                  const SCEV *Candidate) {
10796   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10797   if (!MinMaxExpr)
10798     return false;
10799 
10800   return is_contained(MinMaxExpr->operands(), Candidate);
10801 }
10802 
10803 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10804                                            ICmpInst::Predicate Pred,
10805                                            const SCEV *LHS, const SCEV *RHS) {
10806   // If both sides are affine addrecs for the same loop, with equal
10807   // steps, and we know the recurrences don't wrap, then we only
10808   // need to check the predicate on the starting values.
10809 
10810   if (!ICmpInst::isRelational(Pred))
10811     return false;
10812 
10813   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10814   if (!LAR)
10815     return false;
10816   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10817   if (!RAR)
10818     return false;
10819   if (LAR->getLoop() != RAR->getLoop())
10820     return false;
10821   if (!LAR->isAffine() || !RAR->isAffine())
10822     return false;
10823 
10824   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10825     return false;
10826 
10827   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10828                          SCEV::FlagNSW : SCEV::FlagNUW;
10829   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10830     return false;
10831 
10832   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10833 }
10834 
10835 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10836 /// expression?
10837 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10838                                         ICmpInst::Predicate Pred,
10839                                         const SCEV *LHS, const SCEV *RHS) {
10840   switch (Pred) {
10841   default:
10842     return false;
10843 
10844   case ICmpInst::ICMP_SGE:
10845     std::swap(LHS, RHS);
10846     LLVM_FALLTHROUGH;
10847   case ICmpInst::ICMP_SLE:
10848     return
10849         // min(A, ...) <= A
10850         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10851         // A <= max(A, ...)
10852         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10853 
10854   case ICmpInst::ICMP_UGE:
10855     std::swap(LHS, RHS);
10856     LLVM_FALLTHROUGH;
10857   case ICmpInst::ICMP_ULE:
10858     return
10859         // min(A, ...) <= A
10860         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10861         // A <= max(A, ...)
10862         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10863   }
10864 
10865   llvm_unreachable("covered switch fell through?!");
10866 }
10867 
10868 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10869                                              const SCEV *LHS, const SCEV *RHS,
10870                                              const SCEV *FoundLHS,
10871                                              const SCEV *FoundRHS,
10872                                              unsigned Depth) {
10873   assert(getTypeSizeInBits(LHS->getType()) ==
10874              getTypeSizeInBits(RHS->getType()) &&
10875          "LHS and RHS have different sizes?");
10876   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10877              getTypeSizeInBits(FoundRHS->getType()) &&
10878          "FoundLHS and FoundRHS have different sizes?");
10879   // We want to avoid hurting the compile time with analysis of too big trees.
10880   if (Depth > MaxSCEVOperationsImplicationDepth)
10881     return false;
10882 
10883   // We only want to work with GT comparison so far.
10884   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10885     Pred = CmpInst::getSwappedPredicate(Pred);
10886     std::swap(LHS, RHS);
10887     std::swap(FoundLHS, FoundRHS);
10888   }
10889 
10890   // For unsigned, try to reduce it to corresponding signed comparison.
10891   if (Pred == ICmpInst::ICMP_UGT)
10892     // We can replace unsigned predicate with its signed counterpart if all
10893     // involved values are non-negative.
10894     // TODO: We could have better support for unsigned.
10895     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10896       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10897       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10898       // use this fact to prove that LHS and RHS are non-negative.
10899       const SCEV *MinusOne = getMinusOne(LHS->getType());
10900       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10901                                 FoundRHS) &&
10902           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10903                                 FoundRHS))
10904         Pred = ICmpInst::ICMP_SGT;
10905     }
10906 
10907   if (Pred != ICmpInst::ICMP_SGT)
10908     return false;
10909 
10910   auto GetOpFromSExt = [&](const SCEV *S) {
10911     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10912       return Ext->getOperand();
10913     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10914     // the constant in some cases.
10915     return S;
10916   };
10917 
10918   // Acquire values from extensions.
10919   auto *OrigLHS = LHS;
10920   auto *OrigFoundLHS = FoundLHS;
10921   LHS = GetOpFromSExt(LHS);
10922   FoundLHS = GetOpFromSExt(FoundLHS);
10923 
10924   // Is the SGT predicate can be proved trivially or using the found context.
10925   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10926     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10927            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10928                                   FoundRHS, Depth + 1);
10929   };
10930 
10931   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10932     // We want to avoid creation of any new non-constant SCEV. Since we are
10933     // going to compare the operands to RHS, we should be certain that we don't
10934     // need any size extensions for this. So let's decline all cases when the
10935     // sizes of types of LHS and RHS do not match.
10936     // TODO: Maybe try to get RHS from sext to catch more cases?
10937     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10938       return false;
10939 
10940     // Should not overflow.
10941     if (!LHSAddExpr->hasNoSignedWrap())
10942       return false;
10943 
10944     auto *LL = LHSAddExpr->getOperand(0);
10945     auto *LR = LHSAddExpr->getOperand(1);
10946     auto *MinusOne = getMinusOne(RHS->getType());
10947 
10948     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10949     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10950       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10951     };
10952     // Try to prove the following rule:
10953     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10954     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10955     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10956       return true;
10957   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10958     Value *LL, *LR;
10959     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10960 
10961     using namespace llvm::PatternMatch;
10962 
10963     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10964       // Rules for division.
10965       // We are going to perform some comparisons with Denominator and its
10966       // derivative expressions. In general case, creating a SCEV for it may
10967       // lead to a complex analysis of the entire graph, and in particular it
10968       // can request trip count recalculation for the same loop. This would
10969       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10970       // this, we only want to create SCEVs that are constants in this section.
10971       // So we bail if Denominator is not a constant.
10972       if (!isa<ConstantInt>(LR))
10973         return false;
10974 
10975       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10976 
10977       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10978       // then a SCEV for the numerator already exists and matches with FoundLHS.
10979       auto *Numerator = getExistingSCEV(LL);
10980       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10981         return false;
10982 
10983       // Make sure that the numerator matches with FoundLHS and the denominator
10984       // is positive.
10985       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10986         return false;
10987 
10988       auto *DTy = Denominator->getType();
10989       auto *FRHSTy = FoundRHS->getType();
10990       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10991         // One of types is a pointer and another one is not. We cannot extend
10992         // them properly to a wider type, so let us just reject this case.
10993         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10994         // to avoid this check.
10995         return false;
10996 
10997       // Given that:
10998       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10999       auto *WTy = getWiderType(DTy, FRHSTy);
11000       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11001       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11002 
11003       // Try to prove the following rule:
11004       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11005       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11006       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11007       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11008       if (isKnownNonPositive(RHS) &&
11009           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11010         return true;
11011 
11012       // Try to prove the following rule:
11013       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11014       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11015       // If we divide it by Denominator > 2, then:
11016       // 1. If FoundLHS is negative, then the result is 0.
11017       // 2. If FoundLHS is non-negative, then the result is non-negative.
11018       // Anyways, the result is non-negative.
11019       auto *MinusOne = getMinusOne(WTy);
11020       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11021       if (isKnownNegative(RHS) &&
11022           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11023         return true;
11024     }
11025   }
11026 
11027   // If our expression contained SCEVUnknown Phis, and we split it down and now
11028   // need to prove something for them, try to prove the predicate for every
11029   // possible incoming values of those Phis.
11030   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11031     return true;
11032 
11033   return false;
11034 }
11035 
11036 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11037                                         const SCEV *LHS, const SCEV *RHS) {
11038   // zext x u<= sext x, sext x s<= zext x
11039   switch (Pred) {
11040   case ICmpInst::ICMP_SGE:
11041     std::swap(LHS, RHS);
11042     LLVM_FALLTHROUGH;
11043   case ICmpInst::ICMP_SLE: {
11044     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11045     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11046     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11047     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11048       return true;
11049     break;
11050   }
11051   case ICmpInst::ICMP_UGE:
11052     std::swap(LHS, RHS);
11053     LLVM_FALLTHROUGH;
11054   case ICmpInst::ICMP_ULE: {
11055     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11056     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11057     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11058     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11059       return true;
11060     break;
11061   }
11062   default:
11063     break;
11064   };
11065   return false;
11066 }
11067 
11068 bool
11069 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11070                                            const SCEV *LHS, const SCEV *RHS) {
11071   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11072          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11073          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11074          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11075          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11076 }
11077 
11078 bool
11079 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11080                                              const SCEV *LHS, const SCEV *RHS,
11081                                              const SCEV *FoundLHS,
11082                                              const SCEV *FoundRHS) {
11083   switch (Pred) {
11084   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11085   case ICmpInst::ICMP_EQ:
11086   case ICmpInst::ICMP_NE:
11087     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11088       return true;
11089     break;
11090   case ICmpInst::ICMP_SLT:
11091   case ICmpInst::ICMP_SLE:
11092     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11093         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11094       return true;
11095     break;
11096   case ICmpInst::ICMP_SGT:
11097   case ICmpInst::ICMP_SGE:
11098     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11099         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11100       return true;
11101     break;
11102   case ICmpInst::ICMP_ULT:
11103   case ICmpInst::ICMP_ULE:
11104     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11105         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11106       return true;
11107     break;
11108   case ICmpInst::ICMP_UGT:
11109   case ICmpInst::ICMP_UGE:
11110     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11111         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11112       return true;
11113     break;
11114   }
11115 
11116   // Maybe it can be proved via operations?
11117   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11118     return true;
11119 
11120   return false;
11121 }
11122 
11123 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11124                                                      const SCEV *LHS,
11125                                                      const SCEV *RHS,
11126                                                      const SCEV *FoundLHS,
11127                                                      const SCEV *FoundRHS) {
11128   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11129     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11130     // reduce the compile time impact of this optimization.
11131     return false;
11132 
11133   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11134   if (!Addend)
11135     return false;
11136 
11137   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11138 
11139   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11140   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11141   ConstantRange FoundLHSRange =
11142       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
11143 
11144   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11145   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11146 
11147   // We can also compute the range of values for `LHS` that satisfy the
11148   // consequent, "`LHS` `Pred` `RHS`":
11149   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11150   // The antecedent implies the consequent if every value of `LHS` that
11151   // satisfies the antecedent also satisfies the consequent.
11152   return LHSRange.icmp(Pred, ConstRHS);
11153 }
11154 
11155 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11156                                          bool IsSigned, bool NoWrap) {
11157   assert(isKnownPositive(Stride) && "Positive stride expected!");
11158 
11159   if (NoWrap) return false;
11160 
11161   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11162   const SCEV *One = getOne(Stride->getType());
11163 
11164   if (IsSigned) {
11165     APInt MaxRHS = getSignedRangeMax(RHS);
11166     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11167     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11168 
11169     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11170     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11171   }
11172 
11173   APInt MaxRHS = getUnsignedRangeMax(RHS);
11174   APInt MaxValue = APInt::getMaxValue(BitWidth);
11175   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11176 
11177   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11178   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11179 }
11180 
11181 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11182                                          bool IsSigned, bool NoWrap) {
11183   if (NoWrap) return false;
11184 
11185   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11186   const SCEV *One = getOne(Stride->getType());
11187 
11188   if (IsSigned) {
11189     APInt MinRHS = getSignedRangeMin(RHS);
11190     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11191     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11192 
11193     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11194     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11195   }
11196 
11197   APInt MinRHS = getUnsignedRangeMin(RHS);
11198   APInt MinValue = APInt::getMinValue(BitWidth);
11199   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11200 
11201   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11202   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11203 }
11204 
11205 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
11206                                             bool Equality) {
11207   const SCEV *One = getOne(Step->getType());
11208   Delta = Equality ? getAddExpr(Delta, Step)
11209                    : getAddExpr(Delta, getMinusSCEV(Step, One));
11210   return getUDivExpr(Delta, Step);
11211 }
11212 
11213 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11214                                                     const SCEV *Stride,
11215                                                     const SCEV *End,
11216                                                     unsigned BitWidth,
11217                                                     bool IsSigned) {
11218 
11219   assert(!isKnownNonPositive(Stride) &&
11220          "Stride is expected strictly positive!");
11221   // Calculate the maximum backedge count based on the range of values
11222   // permitted by Start, End, and Stride.
11223   const SCEV *MaxBECount;
11224   APInt MinStart =
11225       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11226 
11227   APInt StrideForMaxBECount =
11228       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11229 
11230   // We already know that the stride is positive, so we paper over conservatism
11231   // in our range computation by forcing StrideForMaxBECount to be at least one.
11232   // In theory this is unnecessary, but we expect MaxBECount to be a
11233   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11234   // is nothing to constant fold it to).
11235   APInt One(BitWidth, 1, IsSigned);
11236   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11237 
11238   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11239                             : APInt::getMaxValue(BitWidth);
11240   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11241 
11242   // Although End can be a MAX expression we estimate MaxEnd considering only
11243   // the case End = RHS of the loop termination condition. This is safe because
11244   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11245   // taken count.
11246   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11247                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11248 
11249   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11250                               getConstant(StrideForMaxBECount) /* Step */,
11251                               false /* Equality */);
11252 
11253   return MaxBECount;
11254 }
11255 
11256 ScalarEvolution::ExitLimit
11257 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11258                                   const Loop *L, bool IsSigned,
11259                                   bool ControlsExit, bool AllowPredicates) {
11260   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11261 
11262   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11263   bool PredicatedIV = false;
11264 
11265   if (!IV && AllowPredicates) {
11266     // Try to make this an AddRec using runtime tests, in the first X
11267     // iterations of this loop, where X is the SCEV expression found by the
11268     // algorithm below.
11269     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11270     PredicatedIV = true;
11271   }
11272 
11273   // Avoid weird loops
11274   if (!IV || IV->getLoop() != L || !IV->isAffine())
11275     return getCouldNotCompute();
11276 
11277   bool NoWrap = ControlsExit &&
11278                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11279 
11280   const SCEV *Stride = IV->getStepRecurrence(*this);
11281 
11282   bool PositiveStride = isKnownPositive(Stride);
11283 
11284   // Avoid negative or zero stride values.
11285   if (!PositiveStride) {
11286     // We can compute the correct backedge taken count for loops with unknown
11287     // strides if we can prove that the loop is not an infinite loop with side
11288     // effects. Here's the loop structure we are trying to handle -
11289     //
11290     // i = start
11291     // do {
11292     //   A[i] = i;
11293     //   i += s;
11294     // } while (i < end);
11295     //
11296     // The backedge taken count for such loops is evaluated as -
11297     // (max(end, start + stride) - start - 1) /u stride
11298     //
11299     // The additional preconditions that we need to check to prove correctness
11300     // of the above formula is as follows -
11301     //
11302     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11303     //    NoWrap flag).
11304     // b) loop is single exit with no side effects.
11305     //
11306     //
11307     // Precondition a) implies that if the stride is negative, this is a single
11308     // trip loop. The backedge taken count formula reduces to zero in this case.
11309     //
11310     // Precondition b) implies that the unknown stride cannot be zero otherwise
11311     // we have UB.
11312     //
11313     // The positive stride case is the same as isKnownPositive(Stride) returning
11314     // true (original behavior of the function).
11315     //
11316     // We want to make sure that the stride is truly unknown as there are edge
11317     // cases where ScalarEvolution propagates no wrap flags to the
11318     // post-increment/decrement IV even though the increment/decrement operation
11319     // itself is wrapping. The computed backedge taken count may be wrong in
11320     // such cases. This is prevented by checking that the stride is not known to
11321     // be either positive or non-positive. For example, no wrap flags are
11322     // propagated to the post-increment IV of this loop with a trip count of 2 -
11323     //
11324     // unsigned char i;
11325     // for(i=127; i<128; i+=129)
11326     //   A[i] = i;
11327     //
11328     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11329         !loopHasNoSideEffects(L))
11330       return getCouldNotCompute();
11331   } else if (!Stride->isOne() &&
11332              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11333     // Avoid proven overflow cases: this will ensure that the backedge taken
11334     // count will not generate any unsigned overflow. Relaxed no-overflow
11335     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11336     // undefined behaviors like the case of C language.
11337     return getCouldNotCompute();
11338 
11339   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11340                                       : ICmpInst::ICMP_ULT;
11341   const SCEV *Start = IV->getStart();
11342   const SCEV *End = RHS;
11343   // When the RHS is not invariant, we do not know the end bound of the loop and
11344   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11345   // calculate the MaxBECount, given the start, stride and max value for the end
11346   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11347   // checked above).
11348   if (!isLoopInvariant(RHS, L)) {
11349     const SCEV *MaxBECount = computeMaxBECountForLT(
11350         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11351     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11352                      false /*MaxOrZero*/, Predicates);
11353   }
11354   // If the backedge is taken at least once, then it will be taken
11355   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11356   // is the LHS value of the less-than comparison the first time it is evaluated
11357   // and End is the RHS.
11358   const SCEV *BECountIfBackedgeTaken =
11359     computeBECount(getMinusSCEV(End, Start), Stride, false);
11360   // If the loop entry is guarded by the result of the backedge test of the
11361   // first loop iteration, then we know the backedge will be taken at least
11362   // once and so the backedge taken count is as above. If not then we use the
11363   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11364   // as if the backedge is taken at least once max(End,Start) is End and so the
11365   // result is as above, and if not max(End,Start) is Start so we get a backedge
11366   // count of zero.
11367   const SCEV *BECount;
11368   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11369     BECount = BECountIfBackedgeTaken;
11370   else {
11371     // If we know that RHS >= Start in the context of loop, then we know that
11372     // max(RHS, Start) = RHS at this point.
11373     if (isLoopEntryGuardedByCond(
11374             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11375       End = RHS;
11376     else
11377       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11378     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11379   }
11380 
11381   const SCEV *MaxBECount;
11382   bool MaxOrZero = false;
11383   if (isa<SCEVConstant>(BECount))
11384     MaxBECount = BECount;
11385   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11386     // If we know exactly how many times the backedge will be taken if it's
11387     // taken at least once, then the backedge count will either be that or
11388     // zero.
11389     MaxBECount = BECountIfBackedgeTaken;
11390     MaxOrZero = true;
11391   } else {
11392     MaxBECount = computeMaxBECountForLT(
11393         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11394   }
11395 
11396   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11397       !isa<SCEVCouldNotCompute>(BECount))
11398     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11399 
11400   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11401 }
11402 
11403 ScalarEvolution::ExitLimit
11404 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11405                                      const Loop *L, bool IsSigned,
11406                                      bool ControlsExit, bool AllowPredicates) {
11407   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11408   // We handle only IV > Invariant
11409   if (!isLoopInvariant(RHS, L))
11410     return getCouldNotCompute();
11411 
11412   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11413   if (!IV && AllowPredicates)
11414     // Try to make this an AddRec using runtime tests, in the first X
11415     // iterations of this loop, where X is the SCEV expression found by the
11416     // algorithm below.
11417     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11418 
11419   // Avoid weird loops
11420   if (!IV || IV->getLoop() != L || !IV->isAffine())
11421     return getCouldNotCompute();
11422 
11423   bool NoWrap = ControlsExit &&
11424                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11425 
11426   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11427 
11428   // Avoid negative or zero stride values
11429   if (!isKnownPositive(Stride))
11430     return getCouldNotCompute();
11431 
11432   // Avoid proven overflow cases: this will ensure that the backedge taken count
11433   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11434   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11435   // behaviors like the case of C language.
11436   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11437     return getCouldNotCompute();
11438 
11439   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11440                                       : ICmpInst::ICMP_UGT;
11441 
11442   const SCEV *Start = IV->getStart();
11443   const SCEV *End = RHS;
11444   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11445     // If we know that Start >= RHS in the context of loop, then we know that
11446     // min(RHS, Start) = RHS at this point.
11447     if (isLoopEntryGuardedByCond(
11448             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11449       End = RHS;
11450     else
11451       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11452   }
11453 
11454   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11455 
11456   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11457                             : getUnsignedRangeMax(Start);
11458 
11459   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11460                              : getUnsignedRangeMin(Stride);
11461 
11462   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11463   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11464                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11465 
11466   // Although End can be a MIN expression we estimate MinEnd considering only
11467   // the case End = RHS. This is safe because in the other case (Start - End)
11468   // is zero, leading to a zero maximum backedge taken count.
11469   APInt MinEnd =
11470     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11471              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11472 
11473   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11474                                ? BECount
11475                                : computeBECount(getConstant(MaxStart - MinEnd),
11476                                                 getConstant(MinStride), false);
11477 
11478   if (isa<SCEVCouldNotCompute>(MaxBECount))
11479     MaxBECount = BECount;
11480 
11481   return ExitLimit(BECount, MaxBECount, false, Predicates);
11482 }
11483 
11484 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11485                                                     ScalarEvolution &SE) const {
11486   if (Range.isFullSet())  // Infinite loop.
11487     return SE.getCouldNotCompute();
11488 
11489   // If the start is a non-zero constant, shift the range to simplify things.
11490   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11491     if (!SC->getValue()->isZero()) {
11492       SmallVector<const SCEV *, 4> Operands(operands());
11493       Operands[0] = SE.getZero(SC->getType());
11494       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11495                                              getNoWrapFlags(FlagNW));
11496       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11497         return ShiftedAddRec->getNumIterationsInRange(
11498             Range.subtract(SC->getAPInt()), SE);
11499       // This is strange and shouldn't happen.
11500       return SE.getCouldNotCompute();
11501     }
11502 
11503   // The only time we can solve this is when we have all constant indices.
11504   // Otherwise, we cannot determine the overflow conditions.
11505   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11506     return SE.getCouldNotCompute();
11507 
11508   // Okay at this point we know that all elements of the chrec are constants and
11509   // that the start element is zero.
11510 
11511   // First check to see if the range contains zero.  If not, the first
11512   // iteration exits.
11513   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11514   if (!Range.contains(APInt(BitWidth, 0)))
11515     return SE.getZero(getType());
11516 
11517   if (isAffine()) {
11518     // If this is an affine expression then we have this situation:
11519     //   Solve {0,+,A} in Range  ===  Ax in Range
11520 
11521     // We know that zero is in the range.  If A is positive then we know that
11522     // the upper value of the range must be the first possible exit value.
11523     // If A is negative then the lower of the range is the last possible loop
11524     // value.  Also note that we already checked for a full range.
11525     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11526     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11527 
11528     // The exit value should be (End+A)/A.
11529     APInt ExitVal = (End + A).udiv(A);
11530     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11531 
11532     // Evaluate at the exit value.  If we really did fall out of the valid
11533     // range, then we computed our trip count, otherwise wrap around or other
11534     // things must have happened.
11535     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11536     if (Range.contains(Val->getValue()))
11537       return SE.getCouldNotCompute();  // Something strange happened
11538 
11539     // Ensure that the previous value is in the range.  This is a sanity check.
11540     assert(Range.contains(
11541            EvaluateConstantChrecAtConstant(this,
11542            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11543            "Linear scev computation is off in a bad way!");
11544     return SE.getConstant(ExitValue);
11545   }
11546 
11547   if (isQuadratic()) {
11548     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11549       return SE.getConstant(S.getValue());
11550   }
11551 
11552   return SE.getCouldNotCompute();
11553 }
11554 
11555 const SCEVAddRecExpr *
11556 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11557   assert(getNumOperands() > 1 && "AddRec with zero step?");
11558   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11559   // but in this case we cannot guarantee that the value returned will be an
11560   // AddRec because SCEV does not have a fixed point where it stops
11561   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11562   // may happen if we reach arithmetic depth limit while simplifying. So we
11563   // construct the returned value explicitly.
11564   SmallVector<const SCEV *, 3> Ops;
11565   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11566   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11567   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11568     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11569   // We know that the last operand is not a constant zero (otherwise it would
11570   // have been popped out earlier). This guarantees us that if the result has
11571   // the same last operand, then it will also not be popped out, meaning that
11572   // the returned value will be an AddRec.
11573   const SCEV *Last = getOperand(getNumOperands() - 1);
11574   assert(!Last->isZero() && "Recurrency with zero step?");
11575   Ops.push_back(Last);
11576   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11577                                                SCEV::FlagAnyWrap));
11578 }
11579 
11580 // Return true when S contains at least an undef value.
11581 static inline bool containsUndefs(const SCEV *S) {
11582   return SCEVExprContains(S, [](const SCEV *S) {
11583     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11584       return isa<UndefValue>(SU->getValue());
11585     return false;
11586   });
11587 }
11588 
11589 namespace {
11590 
11591 // Collect all steps of SCEV expressions.
11592 struct SCEVCollectStrides {
11593   ScalarEvolution &SE;
11594   SmallVectorImpl<const SCEV *> &Strides;
11595 
11596   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11597       : SE(SE), Strides(S) {}
11598 
11599   bool follow(const SCEV *S) {
11600     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11601       Strides.push_back(AR->getStepRecurrence(SE));
11602     return true;
11603   }
11604 
11605   bool isDone() const { return false; }
11606 };
11607 
11608 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11609 struct SCEVCollectTerms {
11610   SmallVectorImpl<const SCEV *> &Terms;
11611 
11612   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11613 
11614   bool follow(const SCEV *S) {
11615     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11616         isa<SCEVSignExtendExpr>(S)) {
11617       if (!containsUndefs(S))
11618         Terms.push_back(S);
11619 
11620       // Stop recursion: once we collected a term, do not walk its operands.
11621       return false;
11622     }
11623 
11624     // Keep looking.
11625     return true;
11626   }
11627 
11628   bool isDone() const { return false; }
11629 };
11630 
11631 // Check if a SCEV contains an AddRecExpr.
11632 struct SCEVHasAddRec {
11633   bool &ContainsAddRec;
11634 
11635   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11636     ContainsAddRec = false;
11637   }
11638 
11639   bool follow(const SCEV *S) {
11640     if (isa<SCEVAddRecExpr>(S)) {
11641       ContainsAddRec = true;
11642 
11643       // Stop recursion: once we collected a term, do not walk its operands.
11644       return false;
11645     }
11646 
11647     // Keep looking.
11648     return true;
11649   }
11650 
11651   bool isDone() const { return false; }
11652 };
11653 
11654 // Find factors that are multiplied with an expression that (possibly as a
11655 // subexpression) contains an AddRecExpr. In the expression:
11656 //
11657 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11658 //
11659 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11660 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11661 // parameters as they form a product with an induction variable.
11662 //
11663 // This collector expects all array size parameters to be in the same MulExpr.
11664 // It might be necessary to later add support for collecting parameters that are
11665 // spread over different nested MulExpr.
11666 struct SCEVCollectAddRecMultiplies {
11667   SmallVectorImpl<const SCEV *> &Terms;
11668   ScalarEvolution &SE;
11669 
11670   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11671       : Terms(T), SE(SE) {}
11672 
11673   bool follow(const SCEV *S) {
11674     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11675       bool HasAddRec = false;
11676       SmallVector<const SCEV *, 0> Operands;
11677       for (auto Op : Mul->operands()) {
11678         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11679         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11680           Operands.push_back(Op);
11681         } else if (Unknown) {
11682           HasAddRec = true;
11683         } else {
11684           bool ContainsAddRec = false;
11685           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11686           visitAll(Op, ContiansAddRec);
11687           HasAddRec |= ContainsAddRec;
11688         }
11689       }
11690       if (Operands.size() == 0)
11691         return true;
11692 
11693       if (!HasAddRec)
11694         return false;
11695 
11696       Terms.push_back(SE.getMulExpr(Operands));
11697       // Stop recursion: once we collected a term, do not walk its operands.
11698       return false;
11699     }
11700 
11701     // Keep looking.
11702     return true;
11703   }
11704 
11705   bool isDone() const { return false; }
11706 };
11707 
11708 } // end anonymous namespace
11709 
11710 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11711 /// two places:
11712 ///   1) The strides of AddRec expressions.
11713 ///   2) Unknowns that are multiplied with AddRec expressions.
11714 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11715     SmallVectorImpl<const SCEV *> &Terms) {
11716   SmallVector<const SCEV *, 4> Strides;
11717   SCEVCollectStrides StrideCollector(*this, Strides);
11718   visitAll(Expr, StrideCollector);
11719 
11720   LLVM_DEBUG({
11721     dbgs() << "Strides:\n";
11722     for (const SCEV *S : Strides)
11723       dbgs() << *S << "\n";
11724   });
11725 
11726   for (const SCEV *S : Strides) {
11727     SCEVCollectTerms TermCollector(Terms);
11728     visitAll(S, TermCollector);
11729   }
11730 
11731   LLVM_DEBUG({
11732     dbgs() << "Terms:\n";
11733     for (const SCEV *T : Terms)
11734       dbgs() << *T << "\n";
11735   });
11736 
11737   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11738   visitAll(Expr, MulCollector);
11739 }
11740 
11741 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11742                                    SmallVectorImpl<const SCEV *> &Terms,
11743                                    SmallVectorImpl<const SCEV *> &Sizes) {
11744   int Last = Terms.size() - 1;
11745   const SCEV *Step = Terms[Last];
11746 
11747   // End of recursion.
11748   if (Last == 0) {
11749     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11750       SmallVector<const SCEV *, 2> Qs;
11751       for (const SCEV *Op : M->operands())
11752         if (!isa<SCEVConstant>(Op))
11753           Qs.push_back(Op);
11754 
11755       Step = SE.getMulExpr(Qs);
11756     }
11757 
11758     Sizes.push_back(Step);
11759     return true;
11760   }
11761 
11762   for (const SCEV *&Term : Terms) {
11763     // Normalize the terms before the next call to findArrayDimensionsRec.
11764     const SCEV *Q, *R;
11765     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11766 
11767     // Bail out when GCD does not evenly divide one of the terms.
11768     if (!R->isZero())
11769       return false;
11770 
11771     Term = Q;
11772   }
11773 
11774   // Remove all SCEVConstants.
11775   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
11776 
11777   if (Terms.size() > 0)
11778     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11779       return false;
11780 
11781   Sizes.push_back(Step);
11782   return true;
11783 }
11784 
11785 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11786 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11787   for (const SCEV *T : Terms)
11788     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11789       return true;
11790 
11791   return false;
11792 }
11793 
11794 // Return the number of product terms in S.
11795 static inline int numberOfTerms(const SCEV *S) {
11796   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11797     return Expr->getNumOperands();
11798   return 1;
11799 }
11800 
11801 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11802   if (isa<SCEVConstant>(T))
11803     return nullptr;
11804 
11805   if (isa<SCEVUnknown>(T))
11806     return T;
11807 
11808   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11809     SmallVector<const SCEV *, 2> Factors;
11810     for (const SCEV *Op : M->operands())
11811       if (!isa<SCEVConstant>(Op))
11812         Factors.push_back(Op);
11813 
11814     return SE.getMulExpr(Factors);
11815   }
11816 
11817   return T;
11818 }
11819 
11820 /// Return the size of an element read or written by Inst.
11821 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11822   Type *Ty;
11823   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11824     Ty = Store->getValueOperand()->getType();
11825   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11826     Ty = Load->getType();
11827   else
11828     return nullptr;
11829 
11830   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11831   return getSizeOfExpr(ETy, Ty);
11832 }
11833 
11834 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11835                                           SmallVectorImpl<const SCEV *> &Sizes,
11836                                           const SCEV *ElementSize) {
11837   if (Terms.size() < 1 || !ElementSize)
11838     return;
11839 
11840   // Early return when Terms do not contain parameters: we do not delinearize
11841   // non parametric SCEVs.
11842   if (!containsParameters(Terms))
11843     return;
11844 
11845   LLVM_DEBUG({
11846     dbgs() << "Terms:\n";
11847     for (const SCEV *T : Terms)
11848       dbgs() << *T << "\n";
11849   });
11850 
11851   // Remove duplicates.
11852   array_pod_sort(Terms.begin(), Terms.end());
11853   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11854 
11855   // Put larger terms first.
11856   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11857     return numberOfTerms(LHS) > numberOfTerms(RHS);
11858   });
11859 
11860   // Try to divide all terms by the element size. If term is not divisible by
11861   // element size, proceed with the original term.
11862   for (const SCEV *&Term : Terms) {
11863     const SCEV *Q, *R;
11864     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11865     if (!Q->isZero())
11866       Term = Q;
11867   }
11868 
11869   SmallVector<const SCEV *, 4> NewTerms;
11870 
11871   // Remove constant factors.
11872   for (const SCEV *T : Terms)
11873     if (const SCEV *NewT = removeConstantFactors(*this, T))
11874       NewTerms.push_back(NewT);
11875 
11876   LLVM_DEBUG({
11877     dbgs() << "Terms after sorting:\n";
11878     for (const SCEV *T : NewTerms)
11879       dbgs() << *T << "\n";
11880   });
11881 
11882   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11883     Sizes.clear();
11884     return;
11885   }
11886 
11887   // The last element to be pushed into Sizes is the size of an element.
11888   Sizes.push_back(ElementSize);
11889 
11890   LLVM_DEBUG({
11891     dbgs() << "Sizes:\n";
11892     for (const SCEV *S : Sizes)
11893       dbgs() << *S << "\n";
11894   });
11895 }
11896 
11897 void ScalarEvolution::computeAccessFunctions(
11898     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11899     SmallVectorImpl<const SCEV *> &Sizes) {
11900   // Early exit in case this SCEV is not an affine multivariate function.
11901   if (Sizes.empty())
11902     return;
11903 
11904   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11905     if (!AR->isAffine())
11906       return;
11907 
11908   const SCEV *Res = Expr;
11909   int Last = Sizes.size() - 1;
11910   for (int i = Last; i >= 0; i--) {
11911     const SCEV *Q, *R;
11912     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11913 
11914     LLVM_DEBUG({
11915       dbgs() << "Res: " << *Res << "\n";
11916       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11917       dbgs() << "Res divided by Sizes[i]:\n";
11918       dbgs() << "Quotient: " << *Q << "\n";
11919       dbgs() << "Remainder: " << *R << "\n";
11920     });
11921 
11922     Res = Q;
11923 
11924     // Do not record the last subscript corresponding to the size of elements in
11925     // the array.
11926     if (i == Last) {
11927 
11928       // Bail out if the remainder is too complex.
11929       if (isa<SCEVAddRecExpr>(R)) {
11930         Subscripts.clear();
11931         Sizes.clear();
11932         return;
11933       }
11934 
11935       continue;
11936     }
11937 
11938     // Record the access function for the current subscript.
11939     Subscripts.push_back(R);
11940   }
11941 
11942   // Also push in last position the remainder of the last division: it will be
11943   // the access function of the innermost dimension.
11944   Subscripts.push_back(Res);
11945 
11946   std::reverse(Subscripts.begin(), Subscripts.end());
11947 
11948   LLVM_DEBUG({
11949     dbgs() << "Subscripts:\n";
11950     for (const SCEV *S : Subscripts)
11951       dbgs() << *S << "\n";
11952   });
11953 }
11954 
11955 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11956 /// sizes of an array access. Returns the remainder of the delinearization that
11957 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11958 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11959 /// expressions in the stride and base of a SCEV corresponding to the
11960 /// computation of a GCD (greatest common divisor) of base and stride.  When
11961 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11962 ///
11963 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11964 ///
11965 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11966 ///
11967 ///    for (long i = 0; i < n; i++)
11968 ///      for (long j = 0; j < m; j++)
11969 ///        for (long k = 0; k < o; k++)
11970 ///          A[i][j][k] = 1.0;
11971 ///  }
11972 ///
11973 /// the delinearization input is the following AddRec SCEV:
11974 ///
11975 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11976 ///
11977 /// From this SCEV, we are able to say that the base offset of the access is %A
11978 /// because it appears as an offset that does not divide any of the strides in
11979 /// the loops:
11980 ///
11981 ///  CHECK: Base offset: %A
11982 ///
11983 /// and then SCEV->delinearize determines the size of some of the dimensions of
11984 /// the array as these are the multiples by which the strides are happening:
11985 ///
11986 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11987 ///
11988 /// Note that the outermost dimension remains of UnknownSize because there are
11989 /// no strides that would help identifying the size of the last dimension: when
11990 /// the array has been statically allocated, one could compute the size of that
11991 /// dimension by dividing the overall size of the array by the size of the known
11992 /// dimensions: %m * %o * 8.
11993 ///
11994 /// Finally delinearize provides the access functions for the array reference
11995 /// that does correspond to A[i][j][k] of the above C testcase:
11996 ///
11997 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11998 ///
11999 /// The testcases are checking the output of a function pass:
12000 /// DelinearizationPass that walks through all loads and stores of a function
12001 /// asking for the SCEV of the memory access with respect to all enclosing
12002 /// loops, calling SCEV->delinearize on that and printing the results.
12003 void ScalarEvolution::delinearize(const SCEV *Expr,
12004                                  SmallVectorImpl<const SCEV *> &Subscripts,
12005                                  SmallVectorImpl<const SCEV *> &Sizes,
12006                                  const SCEV *ElementSize) {
12007   // First step: collect parametric terms.
12008   SmallVector<const SCEV *, 4> Terms;
12009   collectParametricTerms(Expr, Terms);
12010 
12011   if (Terms.empty())
12012     return;
12013 
12014   // Second step: find subscript sizes.
12015   findArrayDimensions(Terms, Sizes, ElementSize);
12016 
12017   if (Sizes.empty())
12018     return;
12019 
12020   // Third step: compute the access functions for each subscript.
12021   computeAccessFunctions(Expr, Subscripts, Sizes);
12022 
12023   if (Subscripts.empty())
12024     return;
12025 
12026   LLVM_DEBUG({
12027     dbgs() << "succeeded to delinearize " << *Expr << "\n";
12028     dbgs() << "ArrayDecl[UnknownSize]";
12029     for (const SCEV *S : Sizes)
12030       dbgs() << "[" << *S << "]";
12031 
12032     dbgs() << "\nArrayRef";
12033     for (const SCEV *S : Subscripts)
12034       dbgs() << "[" << *S << "]";
12035     dbgs() << "\n";
12036   });
12037 }
12038 
12039 bool ScalarEvolution::getIndexExpressionsFromGEP(
12040     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
12041     SmallVectorImpl<int> &Sizes) {
12042   assert(Subscripts.empty() && Sizes.empty() &&
12043          "Expected output lists to be empty on entry to this function.");
12044   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
12045   Type *Ty = GEP->getPointerOperandType();
12046   bool DroppedFirstDim = false;
12047   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
12048     const SCEV *Expr = getSCEV(GEP->getOperand(i));
12049     if (i == 1) {
12050       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
12051         Ty = PtrTy->getElementType();
12052       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
12053         Ty = ArrayTy->getElementType();
12054       } else {
12055         Subscripts.clear();
12056         Sizes.clear();
12057         return false;
12058       }
12059       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
12060         if (Const->getValue()->isZero()) {
12061           DroppedFirstDim = true;
12062           continue;
12063         }
12064       Subscripts.push_back(Expr);
12065       continue;
12066     }
12067 
12068     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
12069     if (!ArrayTy) {
12070       Subscripts.clear();
12071       Sizes.clear();
12072       return false;
12073     }
12074 
12075     Subscripts.push_back(Expr);
12076     if (!(DroppedFirstDim && i == 2))
12077       Sizes.push_back(ArrayTy->getNumElements());
12078 
12079     Ty = ArrayTy->getElementType();
12080   }
12081   return !Subscripts.empty();
12082 }
12083 
12084 //===----------------------------------------------------------------------===//
12085 //                   SCEVCallbackVH Class Implementation
12086 //===----------------------------------------------------------------------===//
12087 
12088 void ScalarEvolution::SCEVCallbackVH::deleted() {
12089   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12090   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12091     SE->ConstantEvolutionLoopExitValue.erase(PN);
12092   SE->eraseValueFromMap(getValPtr());
12093   // this now dangles!
12094 }
12095 
12096 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12097   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12098 
12099   // Forget all the expressions associated with users of the old value,
12100   // so that future queries will recompute the expressions using the new
12101   // value.
12102   Value *Old = getValPtr();
12103   SmallVector<User *, 16> Worklist(Old->users());
12104   SmallPtrSet<User *, 8> Visited;
12105   while (!Worklist.empty()) {
12106     User *U = Worklist.pop_back_val();
12107     // Deleting the Old value will cause this to dangle. Postpone
12108     // that until everything else is done.
12109     if (U == Old)
12110       continue;
12111     if (!Visited.insert(U).second)
12112       continue;
12113     if (PHINode *PN = dyn_cast<PHINode>(U))
12114       SE->ConstantEvolutionLoopExitValue.erase(PN);
12115     SE->eraseValueFromMap(U);
12116     llvm::append_range(Worklist, U->users());
12117   }
12118   // Delete the Old value.
12119   if (PHINode *PN = dyn_cast<PHINode>(Old))
12120     SE->ConstantEvolutionLoopExitValue.erase(PN);
12121   SE->eraseValueFromMap(Old);
12122   // this now dangles!
12123 }
12124 
12125 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12126   : CallbackVH(V), SE(se) {}
12127 
12128 //===----------------------------------------------------------------------===//
12129 //                   ScalarEvolution Class Implementation
12130 //===----------------------------------------------------------------------===//
12131 
12132 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12133                                  AssumptionCache &AC, DominatorTree &DT,
12134                                  LoopInfo &LI)
12135     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12136       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12137       LoopDispositions(64), BlockDispositions(64) {
12138   // To use guards for proving predicates, we need to scan every instruction in
12139   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12140   // time if the IR does not actually contain any calls to
12141   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12142   //
12143   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12144   // to _add_ guards to the module when there weren't any before, and wants
12145   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12146   // efficient in lieu of being smart in that rather obscure case.
12147 
12148   auto *GuardDecl = F.getParent()->getFunction(
12149       Intrinsic::getName(Intrinsic::experimental_guard));
12150   HasGuards = GuardDecl && !GuardDecl->use_empty();
12151 }
12152 
12153 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12154     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12155       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12156       ValueExprMap(std::move(Arg.ValueExprMap)),
12157       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12158       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12159       PendingMerges(std::move(Arg.PendingMerges)),
12160       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12161       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12162       PredicatedBackedgeTakenCounts(
12163           std::move(Arg.PredicatedBackedgeTakenCounts)),
12164       ConstantEvolutionLoopExitValue(
12165           std::move(Arg.ConstantEvolutionLoopExitValue)),
12166       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12167       LoopDispositions(std::move(Arg.LoopDispositions)),
12168       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12169       BlockDispositions(std::move(Arg.BlockDispositions)),
12170       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12171       SignedRanges(std::move(Arg.SignedRanges)),
12172       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12173       UniquePreds(std::move(Arg.UniquePreds)),
12174       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12175       LoopUsers(std::move(Arg.LoopUsers)),
12176       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12177       FirstUnknown(Arg.FirstUnknown) {
12178   Arg.FirstUnknown = nullptr;
12179 }
12180 
12181 ScalarEvolution::~ScalarEvolution() {
12182   // Iterate through all the SCEVUnknown instances and call their
12183   // destructors, so that they release their references to their values.
12184   for (SCEVUnknown *U = FirstUnknown; U;) {
12185     SCEVUnknown *Tmp = U;
12186     U = U->Next;
12187     Tmp->~SCEVUnknown();
12188   }
12189   FirstUnknown = nullptr;
12190 
12191   ExprValueMap.clear();
12192   ValueExprMap.clear();
12193   HasRecMap.clear();
12194 
12195   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
12196   // that a loop had multiple computable exits.
12197   for (auto &BTCI : BackedgeTakenCounts)
12198     BTCI.second.clear();
12199   for (auto &BTCI : PredicatedBackedgeTakenCounts)
12200     BTCI.second.clear();
12201 
12202   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12203   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12204   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12205   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12206   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12207 }
12208 
12209 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12210   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12211 }
12212 
12213 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12214                           const Loop *L) {
12215   // Print all inner loops first
12216   for (Loop *I : *L)
12217     PrintLoopInfo(OS, SE, I);
12218 
12219   OS << "Loop ";
12220   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12221   OS << ": ";
12222 
12223   SmallVector<BasicBlock *, 8> ExitingBlocks;
12224   L->getExitingBlocks(ExitingBlocks);
12225   if (ExitingBlocks.size() != 1)
12226     OS << "<multiple exits> ";
12227 
12228   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12229     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12230   else
12231     OS << "Unpredictable backedge-taken count.\n";
12232 
12233   if (ExitingBlocks.size() > 1)
12234     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12235       OS << "  exit count for " << ExitingBlock->getName() << ": "
12236          << *SE->getExitCount(L, ExitingBlock) << "\n";
12237     }
12238 
12239   OS << "Loop ";
12240   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12241   OS << ": ";
12242 
12243   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12244     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12245     if (SE->isBackedgeTakenCountMaxOrZero(L))
12246       OS << ", actual taken count either this or zero.";
12247   } else {
12248     OS << "Unpredictable max backedge-taken count. ";
12249   }
12250 
12251   OS << "\n"
12252         "Loop ";
12253   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12254   OS << ": ";
12255 
12256   SCEVUnionPredicate Pred;
12257   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12258   if (!isa<SCEVCouldNotCompute>(PBT)) {
12259     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12260     OS << " Predicates:\n";
12261     Pred.print(OS, 4);
12262   } else {
12263     OS << "Unpredictable predicated backedge-taken count. ";
12264   }
12265   OS << "\n";
12266 
12267   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12268     OS << "Loop ";
12269     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12270     OS << ": ";
12271     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12272   }
12273 }
12274 
12275 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12276   switch (LD) {
12277   case ScalarEvolution::LoopVariant:
12278     return "Variant";
12279   case ScalarEvolution::LoopInvariant:
12280     return "Invariant";
12281   case ScalarEvolution::LoopComputable:
12282     return "Computable";
12283   }
12284   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12285 }
12286 
12287 void ScalarEvolution::print(raw_ostream &OS) const {
12288   // ScalarEvolution's implementation of the print method is to print
12289   // out SCEV values of all instructions that are interesting. Doing
12290   // this potentially causes it to create new SCEV objects though,
12291   // which technically conflicts with the const qualifier. This isn't
12292   // observable from outside the class though, so casting away the
12293   // const isn't dangerous.
12294   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12295 
12296   if (ClassifyExpressions) {
12297     OS << "Classifying expressions for: ";
12298     F.printAsOperand(OS, /*PrintType=*/false);
12299     OS << "\n";
12300     for (Instruction &I : instructions(F))
12301       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12302         OS << I << '\n';
12303         OS << "  -->  ";
12304         const SCEV *SV = SE.getSCEV(&I);
12305         SV->print(OS);
12306         if (!isa<SCEVCouldNotCompute>(SV)) {
12307           OS << " U: ";
12308           SE.getUnsignedRange(SV).print(OS);
12309           OS << " S: ";
12310           SE.getSignedRange(SV).print(OS);
12311         }
12312 
12313         const Loop *L = LI.getLoopFor(I.getParent());
12314 
12315         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12316         if (AtUse != SV) {
12317           OS << "  -->  ";
12318           AtUse->print(OS);
12319           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12320             OS << " U: ";
12321             SE.getUnsignedRange(AtUse).print(OS);
12322             OS << " S: ";
12323             SE.getSignedRange(AtUse).print(OS);
12324           }
12325         }
12326 
12327         if (L) {
12328           OS << "\t\t" "Exits: ";
12329           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12330           if (!SE.isLoopInvariant(ExitValue, L)) {
12331             OS << "<<Unknown>>";
12332           } else {
12333             OS << *ExitValue;
12334           }
12335 
12336           bool First = true;
12337           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12338             if (First) {
12339               OS << "\t\t" "LoopDispositions: { ";
12340               First = false;
12341             } else {
12342               OS << ", ";
12343             }
12344 
12345             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12346             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12347           }
12348 
12349           for (auto *InnerL : depth_first(L)) {
12350             if (InnerL == L)
12351               continue;
12352             if (First) {
12353               OS << "\t\t" "LoopDispositions: { ";
12354               First = false;
12355             } else {
12356               OS << ", ";
12357             }
12358 
12359             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12360             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12361           }
12362 
12363           OS << " }";
12364         }
12365 
12366         OS << "\n";
12367       }
12368   }
12369 
12370   OS << "Determining loop execution counts for: ";
12371   F.printAsOperand(OS, /*PrintType=*/false);
12372   OS << "\n";
12373   for (Loop *I : LI)
12374     PrintLoopInfo(OS, &SE, I);
12375 }
12376 
12377 ScalarEvolution::LoopDisposition
12378 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12379   auto &Values = LoopDispositions[S];
12380   for (auto &V : Values) {
12381     if (V.getPointer() == L)
12382       return V.getInt();
12383   }
12384   Values.emplace_back(L, LoopVariant);
12385   LoopDisposition D = computeLoopDisposition(S, L);
12386   auto &Values2 = LoopDispositions[S];
12387   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12388     if (V.getPointer() == L) {
12389       V.setInt(D);
12390       break;
12391     }
12392   }
12393   return D;
12394 }
12395 
12396 ScalarEvolution::LoopDisposition
12397 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12398   switch (S->getSCEVType()) {
12399   case scConstant:
12400     return LoopInvariant;
12401   case scPtrToInt:
12402   case scTruncate:
12403   case scZeroExtend:
12404   case scSignExtend:
12405     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12406   case scAddRecExpr: {
12407     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12408 
12409     // If L is the addrec's loop, it's computable.
12410     if (AR->getLoop() == L)
12411       return LoopComputable;
12412 
12413     // Add recurrences are never invariant in the function-body (null loop).
12414     if (!L)
12415       return LoopVariant;
12416 
12417     // Everything that is not defined at loop entry is variant.
12418     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12419       return LoopVariant;
12420     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12421            " dominate the contained loop's header?");
12422 
12423     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12424     if (AR->getLoop()->contains(L))
12425       return LoopInvariant;
12426 
12427     // This recurrence is variant w.r.t. L if any of its operands
12428     // are variant.
12429     for (auto *Op : AR->operands())
12430       if (!isLoopInvariant(Op, L))
12431         return LoopVariant;
12432 
12433     // Otherwise it's loop-invariant.
12434     return LoopInvariant;
12435   }
12436   case scAddExpr:
12437   case scMulExpr:
12438   case scUMaxExpr:
12439   case scSMaxExpr:
12440   case scUMinExpr:
12441   case scSMinExpr: {
12442     bool HasVarying = false;
12443     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12444       LoopDisposition D = getLoopDisposition(Op, L);
12445       if (D == LoopVariant)
12446         return LoopVariant;
12447       if (D == LoopComputable)
12448         HasVarying = true;
12449     }
12450     return HasVarying ? LoopComputable : LoopInvariant;
12451   }
12452   case scUDivExpr: {
12453     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12454     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12455     if (LD == LoopVariant)
12456       return LoopVariant;
12457     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12458     if (RD == LoopVariant)
12459       return LoopVariant;
12460     return (LD == LoopInvariant && RD == LoopInvariant) ?
12461            LoopInvariant : LoopComputable;
12462   }
12463   case scUnknown:
12464     // All non-instruction values are loop invariant.  All instructions are loop
12465     // invariant if they are not contained in the specified loop.
12466     // Instructions are never considered invariant in the function body
12467     // (null loop) because they are defined within the "loop".
12468     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12469       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12470     return LoopInvariant;
12471   case scCouldNotCompute:
12472     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12473   }
12474   llvm_unreachable("Unknown SCEV kind!");
12475 }
12476 
12477 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12478   return getLoopDisposition(S, L) == LoopInvariant;
12479 }
12480 
12481 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12482   return getLoopDisposition(S, L) == LoopComputable;
12483 }
12484 
12485 ScalarEvolution::BlockDisposition
12486 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12487   auto &Values = BlockDispositions[S];
12488   for (auto &V : Values) {
12489     if (V.getPointer() == BB)
12490       return V.getInt();
12491   }
12492   Values.emplace_back(BB, DoesNotDominateBlock);
12493   BlockDisposition D = computeBlockDisposition(S, BB);
12494   auto &Values2 = BlockDispositions[S];
12495   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12496     if (V.getPointer() == BB) {
12497       V.setInt(D);
12498       break;
12499     }
12500   }
12501   return D;
12502 }
12503 
12504 ScalarEvolution::BlockDisposition
12505 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12506   switch (S->getSCEVType()) {
12507   case scConstant:
12508     return ProperlyDominatesBlock;
12509   case scPtrToInt:
12510   case scTruncate:
12511   case scZeroExtend:
12512   case scSignExtend:
12513     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12514   case scAddRecExpr: {
12515     // This uses a "dominates" query instead of "properly dominates" query
12516     // to test for proper dominance too, because the instruction which
12517     // produces the addrec's value is a PHI, and a PHI effectively properly
12518     // dominates its entire containing block.
12519     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12520     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12521       return DoesNotDominateBlock;
12522 
12523     // Fall through into SCEVNAryExpr handling.
12524     LLVM_FALLTHROUGH;
12525   }
12526   case scAddExpr:
12527   case scMulExpr:
12528   case scUMaxExpr:
12529   case scSMaxExpr:
12530   case scUMinExpr:
12531   case scSMinExpr: {
12532     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12533     bool Proper = true;
12534     for (const SCEV *NAryOp : NAry->operands()) {
12535       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12536       if (D == DoesNotDominateBlock)
12537         return DoesNotDominateBlock;
12538       if (D == DominatesBlock)
12539         Proper = false;
12540     }
12541     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12542   }
12543   case scUDivExpr: {
12544     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12545     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12546     BlockDisposition LD = getBlockDisposition(LHS, BB);
12547     if (LD == DoesNotDominateBlock)
12548       return DoesNotDominateBlock;
12549     BlockDisposition RD = getBlockDisposition(RHS, BB);
12550     if (RD == DoesNotDominateBlock)
12551       return DoesNotDominateBlock;
12552     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12553       ProperlyDominatesBlock : DominatesBlock;
12554   }
12555   case scUnknown:
12556     if (Instruction *I =
12557           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12558       if (I->getParent() == BB)
12559         return DominatesBlock;
12560       if (DT.properlyDominates(I->getParent(), BB))
12561         return ProperlyDominatesBlock;
12562       return DoesNotDominateBlock;
12563     }
12564     return ProperlyDominatesBlock;
12565   case scCouldNotCompute:
12566     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12567   }
12568   llvm_unreachable("Unknown SCEV kind!");
12569 }
12570 
12571 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12572   return getBlockDisposition(S, BB) >= DominatesBlock;
12573 }
12574 
12575 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12576   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12577 }
12578 
12579 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12580   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12581 }
12582 
12583 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12584   auto IsS = [&](const SCEV *X) { return S == X; };
12585   auto ContainsS = [&](const SCEV *X) {
12586     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12587   };
12588   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12589 }
12590 
12591 void
12592 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12593   ValuesAtScopes.erase(S);
12594   LoopDispositions.erase(S);
12595   BlockDispositions.erase(S);
12596   UnsignedRanges.erase(S);
12597   SignedRanges.erase(S);
12598   ExprValueMap.erase(S);
12599   HasRecMap.erase(S);
12600   MinTrailingZerosCache.erase(S);
12601 
12602   for (auto I = PredicatedSCEVRewrites.begin();
12603        I != PredicatedSCEVRewrites.end();) {
12604     std::pair<const SCEV *, const Loop *> Entry = I->first;
12605     if (Entry.first == S)
12606       PredicatedSCEVRewrites.erase(I++);
12607     else
12608       ++I;
12609   }
12610 
12611   auto RemoveSCEVFromBackedgeMap =
12612       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12613         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12614           BackedgeTakenInfo &BEInfo = I->second;
12615           if (BEInfo.hasOperand(S, this)) {
12616             BEInfo.clear();
12617             Map.erase(I++);
12618           } else
12619             ++I;
12620         }
12621       };
12622 
12623   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12624   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12625 }
12626 
12627 void
12628 ScalarEvolution::getUsedLoops(const SCEV *S,
12629                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12630   struct FindUsedLoops {
12631     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12632         : LoopsUsed(LoopsUsed) {}
12633     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12634     bool follow(const SCEV *S) {
12635       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12636         LoopsUsed.insert(AR->getLoop());
12637       return true;
12638     }
12639 
12640     bool isDone() const { return false; }
12641   };
12642 
12643   FindUsedLoops F(LoopsUsed);
12644   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12645 }
12646 
12647 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12648   SmallPtrSet<const Loop *, 8> LoopsUsed;
12649   getUsedLoops(S, LoopsUsed);
12650   for (auto *L : LoopsUsed)
12651     LoopUsers[L].push_back(S);
12652 }
12653 
12654 void ScalarEvolution::verify() const {
12655   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12656   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12657 
12658   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12659 
12660   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12661   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12662     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12663 
12664     const SCEV *visitConstant(const SCEVConstant *Constant) {
12665       return SE.getConstant(Constant->getAPInt());
12666     }
12667 
12668     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12669       return SE.getUnknown(Expr->getValue());
12670     }
12671 
12672     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12673       return SE.getCouldNotCompute();
12674     }
12675   };
12676 
12677   SCEVMapper SCM(SE2);
12678 
12679   while (!LoopStack.empty()) {
12680     auto *L = LoopStack.pop_back_val();
12681     llvm::append_range(LoopStack, *L);
12682 
12683     auto *CurBECount = SCM.visit(
12684         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12685     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12686 
12687     if (CurBECount == SE2.getCouldNotCompute() ||
12688         NewBECount == SE2.getCouldNotCompute()) {
12689       // NB! This situation is legal, but is very suspicious -- whatever pass
12690       // change the loop to make a trip count go from could not compute to
12691       // computable or vice-versa *should have* invalidated SCEV.  However, we
12692       // choose not to assert here (for now) since we don't want false
12693       // positives.
12694       continue;
12695     }
12696 
12697     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12698       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12699       // not propagate undef aggressively).  This means we can (and do) fail
12700       // verification in cases where a transform makes the trip count of a loop
12701       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12702       // both cases the loop iterates "undef" times, but SCEV thinks we
12703       // increased the trip count of the loop by 1 incorrectly.
12704       continue;
12705     }
12706 
12707     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12708         SE.getTypeSizeInBits(NewBECount->getType()))
12709       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12710     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12711              SE.getTypeSizeInBits(NewBECount->getType()))
12712       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12713 
12714     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12715 
12716     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12717     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12718       dbgs() << "Trip Count for " << *L << " Changed!\n";
12719       dbgs() << "Old: " << *CurBECount << "\n";
12720       dbgs() << "New: " << *NewBECount << "\n";
12721       dbgs() << "Delta: " << *Delta << "\n";
12722       std::abort();
12723     }
12724   }
12725 
12726   // Collect all valid loops currently in LoopInfo.
12727   SmallPtrSet<Loop *, 32> ValidLoops;
12728   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12729   while (!Worklist.empty()) {
12730     Loop *L = Worklist.pop_back_val();
12731     if (ValidLoops.contains(L))
12732       continue;
12733     ValidLoops.insert(L);
12734     Worklist.append(L->begin(), L->end());
12735   }
12736   // Check for SCEV expressions referencing invalid/deleted loops.
12737   for (auto &KV : ValueExprMap) {
12738     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12739     if (!AR)
12740       continue;
12741     assert(ValidLoops.contains(AR->getLoop()) &&
12742            "AddRec references invalid loop");
12743   }
12744 }
12745 
12746 bool ScalarEvolution::invalidate(
12747     Function &F, const PreservedAnalyses &PA,
12748     FunctionAnalysisManager::Invalidator &Inv) {
12749   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12750   // of its dependencies is invalidated.
12751   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12752   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12753          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12754          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12755          Inv.invalidate<LoopAnalysis>(F, PA);
12756 }
12757 
12758 AnalysisKey ScalarEvolutionAnalysis::Key;
12759 
12760 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12761                                              FunctionAnalysisManager &AM) {
12762   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12763                          AM.getResult<AssumptionAnalysis>(F),
12764                          AM.getResult<DominatorTreeAnalysis>(F),
12765                          AM.getResult<LoopAnalysis>(F));
12766 }
12767 
12768 PreservedAnalyses
12769 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12770   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12771   return PreservedAnalyses::all();
12772 }
12773 
12774 PreservedAnalyses
12775 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12776   // For compatibility with opt's -analyze feature under legacy pass manager
12777   // which was not ported to NPM. This keeps tests using
12778   // update_analyze_test_checks.py working.
12779   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12780      << F.getName() << "':\n";
12781   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12782   return PreservedAnalyses::all();
12783 }
12784 
12785 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12786                       "Scalar Evolution Analysis", false, true)
12787 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12788 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12789 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12790 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12791 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12792                     "Scalar Evolution Analysis", false, true)
12793 
12794 char ScalarEvolutionWrapperPass::ID = 0;
12795 
12796 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12797   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12798 }
12799 
12800 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12801   SE.reset(new ScalarEvolution(
12802       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12803       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12804       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12805       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12806   return false;
12807 }
12808 
12809 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12810 
12811 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12812   SE->print(OS);
12813 }
12814 
12815 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12816   if (!VerifySCEV)
12817     return;
12818 
12819   SE->verify();
12820 }
12821 
12822 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12823   AU.setPreservesAll();
12824   AU.addRequiredTransitive<AssumptionCacheTracker>();
12825   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12826   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12827   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12828 }
12829 
12830 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12831                                                         const SCEV *RHS) {
12832   FoldingSetNodeID ID;
12833   assert(LHS->getType() == RHS->getType() &&
12834          "Type mismatch between LHS and RHS");
12835   // Unique this node based on the arguments
12836   ID.AddInteger(SCEVPredicate::P_Equal);
12837   ID.AddPointer(LHS);
12838   ID.AddPointer(RHS);
12839   void *IP = nullptr;
12840   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12841     return S;
12842   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12843       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12844   UniquePreds.InsertNode(Eq, IP);
12845   return Eq;
12846 }
12847 
12848 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12849     const SCEVAddRecExpr *AR,
12850     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12851   FoldingSetNodeID ID;
12852   // Unique this node based on the arguments
12853   ID.AddInteger(SCEVPredicate::P_Wrap);
12854   ID.AddPointer(AR);
12855   ID.AddInteger(AddedFlags);
12856   void *IP = nullptr;
12857   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12858     return S;
12859   auto *OF = new (SCEVAllocator)
12860       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12861   UniquePreds.InsertNode(OF, IP);
12862   return OF;
12863 }
12864 
12865 namespace {
12866 
12867 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12868 public:
12869 
12870   /// Rewrites \p S in the context of a loop L and the SCEV predication
12871   /// infrastructure.
12872   ///
12873   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12874   /// equivalences present in \p Pred.
12875   ///
12876   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12877   /// \p NewPreds such that the result will be an AddRecExpr.
12878   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12879                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12880                              SCEVUnionPredicate *Pred) {
12881     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12882     return Rewriter.visit(S);
12883   }
12884 
12885   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12886     if (Pred) {
12887       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12888       for (auto *Pred : ExprPreds)
12889         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12890           if (IPred->getLHS() == Expr)
12891             return IPred->getRHS();
12892     }
12893     return convertToAddRecWithPreds(Expr);
12894   }
12895 
12896   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12897     const SCEV *Operand = visit(Expr->getOperand());
12898     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12899     if (AR && AR->getLoop() == L && AR->isAffine()) {
12900       // This couldn't be folded because the operand didn't have the nuw
12901       // flag. Add the nusw flag as an assumption that we could make.
12902       const SCEV *Step = AR->getStepRecurrence(SE);
12903       Type *Ty = Expr->getType();
12904       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12905         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12906                                 SE.getSignExtendExpr(Step, Ty), L,
12907                                 AR->getNoWrapFlags());
12908     }
12909     return SE.getZeroExtendExpr(Operand, Expr->getType());
12910   }
12911 
12912   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12913     const SCEV *Operand = visit(Expr->getOperand());
12914     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12915     if (AR && AR->getLoop() == L && AR->isAffine()) {
12916       // This couldn't be folded because the operand didn't have the nsw
12917       // flag. Add the nssw flag as an assumption that we could make.
12918       const SCEV *Step = AR->getStepRecurrence(SE);
12919       Type *Ty = Expr->getType();
12920       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12921         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12922                                 SE.getSignExtendExpr(Step, Ty), L,
12923                                 AR->getNoWrapFlags());
12924     }
12925     return SE.getSignExtendExpr(Operand, Expr->getType());
12926   }
12927 
12928 private:
12929   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12930                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12931                         SCEVUnionPredicate *Pred)
12932       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12933 
12934   bool addOverflowAssumption(const SCEVPredicate *P) {
12935     if (!NewPreds) {
12936       // Check if we've already made this assumption.
12937       return Pred && Pred->implies(P);
12938     }
12939     NewPreds->insert(P);
12940     return true;
12941   }
12942 
12943   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12944                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12945     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12946     return addOverflowAssumption(A);
12947   }
12948 
12949   // If \p Expr represents a PHINode, we try to see if it can be represented
12950   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12951   // to add this predicate as a runtime overflow check, we return the AddRec.
12952   // If \p Expr does not meet these conditions (is not a PHI node, or we
12953   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12954   // return \p Expr.
12955   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12956     if (!isa<PHINode>(Expr->getValue()))
12957       return Expr;
12958     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12959     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12960     if (!PredicatedRewrite)
12961       return Expr;
12962     for (auto *P : PredicatedRewrite->second){
12963       // Wrap predicates from outer loops are not supported.
12964       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12965         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12966         if (L != AR->getLoop())
12967           return Expr;
12968       }
12969       if (!addOverflowAssumption(P))
12970         return Expr;
12971     }
12972     return PredicatedRewrite->first;
12973   }
12974 
12975   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12976   SCEVUnionPredicate *Pred;
12977   const Loop *L;
12978 };
12979 
12980 } // end anonymous namespace
12981 
12982 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12983                                                    SCEVUnionPredicate &Preds) {
12984   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12985 }
12986 
12987 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12988     const SCEV *S, const Loop *L,
12989     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12990   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12991   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12992   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12993 
12994   if (!AddRec)
12995     return nullptr;
12996 
12997   // Since the transformation was successful, we can now transfer the SCEV
12998   // predicates.
12999   for (auto *P : TransformPreds)
13000     Preds.insert(P);
13001 
13002   return AddRec;
13003 }
13004 
13005 /// SCEV predicates
13006 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13007                              SCEVPredicateKind Kind)
13008     : FastID(ID), Kind(Kind) {}
13009 
13010 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13011                                        const SCEV *LHS, const SCEV *RHS)
13012     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13013   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13014   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13015 }
13016 
13017 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13018   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13019 
13020   if (!Op)
13021     return false;
13022 
13023   return Op->LHS == LHS && Op->RHS == RHS;
13024 }
13025 
13026 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13027 
13028 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13029 
13030 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13031   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13032 }
13033 
13034 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13035                                      const SCEVAddRecExpr *AR,
13036                                      IncrementWrapFlags Flags)
13037     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13038 
13039 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13040 
13041 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13042   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13043 
13044   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13045 }
13046 
13047 bool SCEVWrapPredicate::isAlwaysTrue() const {
13048   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13049   IncrementWrapFlags IFlags = Flags;
13050 
13051   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13052     IFlags = clearFlags(IFlags, IncrementNSSW);
13053 
13054   return IFlags == IncrementAnyWrap;
13055 }
13056 
13057 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13058   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13059   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13060     OS << "<nusw>";
13061   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13062     OS << "<nssw>";
13063   OS << "\n";
13064 }
13065 
13066 SCEVWrapPredicate::IncrementWrapFlags
13067 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13068                                    ScalarEvolution &SE) {
13069   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13070   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13071 
13072   // We can safely transfer the NSW flag as NSSW.
13073   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13074     ImpliedFlags = IncrementNSSW;
13075 
13076   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13077     // If the increment is positive, the SCEV NUW flag will also imply the
13078     // WrapPredicate NUSW flag.
13079     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13080       if (Step->getValue()->getValue().isNonNegative())
13081         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13082   }
13083 
13084   return ImpliedFlags;
13085 }
13086 
13087 /// Union predicates don't get cached so create a dummy set ID for it.
13088 SCEVUnionPredicate::SCEVUnionPredicate()
13089     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13090 
13091 bool SCEVUnionPredicate::isAlwaysTrue() const {
13092   return all_of(Preds,
13093                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13094 }
13095 
13096 ArrayRef<const SCEVPredicate *>
13097 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13098   auto I = SCEVToPreds.find(Expr);
13099   if (I == SCEVToPreds.end())
13100     return ArrayRef<const SCEVPredicate *>();
13101   return I->second;
13102 }
13103 
13104 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13105   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13106     return all_of(Set->Preds,
13107                   [this](const SCEVPredicate *I) { return this->implies(I); });
13108 
13109   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13110   if (ScevPredsIt == SCEVToPreds.end())
13111     return false;
13112   auto &SCEVPreds = ScevPredsIt->second;
13113 
13114   return any_of(SCEVPreds,
13115                 [N](const SCEVPredicate *I) { return I->implies(N); });
13116 }
13117 
13118 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13119 
13120 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13121   for (auto Pred : Preds)
13122     Pred->print(OS, Depth);
13123 }
13124 
13125 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13126   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13127     for (auto Pred : Set->Preds)
13128       add(Pred);
13129     return;
13130   }
13131 
13132   if (implies(N))
13133     return;
13134 
13135   const SCEV *Key = N->getExpr();
13136   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13137                 " associated expression!");
13138 
13139   SCEVToPreds[Key].push_back(N);
13140   Preds.push_back(N);
13141 }
13142 
13143 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13144                                                      Loop &L)
13145     : SE(SE), L(L) {}
13146 
13147 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13148   const SCEV *Expr = SE.getSCEV(V);
13149   RewriteEntry &Entry = RewriteMap[Expr];
13150 
13151   // If we already have an entry and the version matches, return it.
13152   if (Entry.second && Generation == Entry.first)
13153     return Entry.second;
13154 
13155   // We found an entry but it's stale. Rewrite the stale entry
13156   // according to the current predicate.
13157   if (Entry.second)
13158     Expr = Entry.second;
13159 
13160   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13161   Entry = {Generation, NewSCEV};
13162 
13163   return NewSCEV;
13164 }
13165 
13166 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13167   if (!BackedgeCount) {
13168     SCEVUnionPredicate BackedgePred;
13169     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13170     addPredicate(BackedgePred);
13171   }
13172   return BackedgeCount;
13173 }
13174 
13175 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13176   if (Preds.implies(&Pred))
13177     return;
13178   Preds.add(&Pred);
13179   updateGeneration();
13180 }
13181 
13182 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13183   return Preds;
13184 }
13185 
13186 void PredicatedScalarEvolution::updateGeneration() {
13187   // If the generation number wrapped recompute everything.
13188   if (++Generation == 0) {
13189     for (auto &II : RewriteMap) {
13190       const SCEV *Rewritten = II.second.second;
13191       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13192     }
13193   }
13194 }
13195 
13196 void PredicatedScalarEvolution::setNoOverflow(
13197     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13198   const SCEV *Expr = getSCEV(V);
13199   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13200 
13201   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13202 
13203   // Clear the statically implied flags.
13204   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13205   addPredicate(*SE.getWrapPredicate(AR, Flags));
13206 
13207   auto II = FlagsMap.insert({V, Flags});
13208   if (!II.second)
13209     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13210 }
13211 
13212 bool PredicatedScalarEvolution::hasNoOverflow(
13213     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13214   const SCEV *Expr = getSCEV(V);
13215   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13216 
13217   Flags = SCEVWrapPredicate::clearFlags(
13218       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13219 
13220   auto II = FlagsMap.find(V);
13221 
13222   if (II != FlagsMap.end())
13223     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13224 
13225   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13226 }
13227 
13228 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13229   const SCEV *Expr = this->getSCEV(V);
13230   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13231   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13232 
13233   if (!New)
13234     return nullptr;
13235 
13236   for (auto *P : NewPreds)
13237     Preds.add(P);
13238 
13239   updateGeneration();
13240   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13241   return New;
13242 }
13243 
13244 PredicatedScalarEvolution::PredicatedScalarEvolution(
13245     const PredicatedScalarEvolution &Init)
13246     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13247       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13248   for (auto I : Init.FlagsMap)
13249     FlagsMap.insert(I);
13250 }
13251 
13252 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13253   // For each block.
13254   for (auto *BB : L.getBlocks())
13255     for (auto &I : *BB) {
13256       if (!SE.isSCEVable(I.getType()))
13257         continue;
13258 
13259       auto *Expr = SE.getSCEV(&I);
13260       auto II = RewriteMap.find(Expr);
13261 
13262       if (II == RewriteMap.end())
13263         continue;
13264 
13265       // Don't print things that are not interesting.
13266       if (II->second.second == Expr)
13267         continue;
13268 
13269       OS.indent(Depth) << "[PSE]" << I << ":\n";
13270       OS.indent(Depth + 2) << *Expr << "\n";
13271       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13272     }
13273 }
13274 
13275 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13276 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13277 // for URem with constant power-of-2 second operands.
13278 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13279 // 4, A / B becomes X / 8).
13280 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13281                                 const SCEV *&RHS) {
13282   // Try to match 'zext (trunc A to iB) to iY', which is used
13283   // for URem with constant power-of-2 second operands. Make sure the size of
13284   // the operand A matches the size of the whole expressions.
13285   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13286     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13287       LHS = Trunc->getOperand();
13288       // Bail out if the type of the LHS is larger than the type of the
13289       // expression for now.
13290       if (getTypeSizeInBits(LHS->getType()) >
13291           getTypeSizeInBits(Expr->getType()))
13292         return false;
13293       if (LHS->getType() != Expr->getType())
13294         LHS = getZeroExtendExpr(LHS, Expr->getType());
13295       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13296                         << getTypeSizeInBits(Trunc->getType()));
13297       return true;
13298     }
13299   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13300   if (Add == nullptr || Add->getNumOperands() != 2)
13301     return false;
13302 
13303   const SCEV *A = Add->getOperand(1);
13304   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13305 
13306   if (Mul == nullptr)
13307     return false;
13308 
13309   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13310     // (SomeExpr + (-(SomeExpr / B) * B)).
13311     if (Expr == getURemExpr(A, B)) {
13312       LHS = A;
13313       RHS = B;
13314       return true;
13315     }
13316     return false;
13317   };
13318 
13319   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13320   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13321     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13322            MatchURemWithDivisor(Mul->getOperand(2));
13323 
13324   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13325   if (Mul->getNumOperands() == 2)
13326     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13327            MatchURemWithDivisor(Mul->getOperand(0)) ||
13328            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13329            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13330   return false;
13331 }
13332 
13333 const SCEV *
13334 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13335   SmallVector<BasicBlock*, 16> ExitingBlocks;
13336   L->getExitingBlocks(ExitingBlocks);
13337 
13338   // Form an expression for the maximum exit count possible for this loop. We
13339   // merge the max and exact information to approximate a version of
13340   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13341   SmallVector<const SCEV*, 4> ExitCounts;
13342   for (BasicBlock *ExitingBB : ExitingBlocks) {
13343     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13344     if (isa<SCEVCouldNotCompute>(ExitCount))
13345       ExitCount = getExitCount(L, ExitingBB,
13346                                   ScalarEvolution::ConstantMaximum);
13347     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13348       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13349              "We should only have known counts for exiting blocks that "
13350              "dominate latch!");
13351       ExitCounts.push_back(ExitCount);
13352     }
13353   }
13354   if (ExitCounts.empty())
13355     return getCouldNotCompute();
13356   return getUMinFromMismatchedTypes(ExitCounts);
13357 }
13358 
13359 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13360 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13361 /// we cannot guarantee that the replacement is loop invariant in the loop of
13362 /// the AddRec.
13363 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13364   ValueToSCEVMapTy &Map;
13365 
13366 public:
13367   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13368       : SCEVRewriteVisitor(SE), Map(M) {}
13369 
13370   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13371 
13372   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13373     auto I = Map.find(Expr->getValue());
13374     if (I == Map.end())
13375       return Expr;
13376     return I->second;
13377   }
13378 };
13379 
13380 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13381   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13382                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13383     // If we have LHS == 0, check if LHS is computing a property of some unknown
13384     // SCEV %v which we can rewrite %v to express explicitly.
13385     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13386     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13387         RHSC->getValue()->isNullValue()) {
13388       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13389       // explicitly express that.
13390       const SCEV *URemLHS = nullptr;
13391       const SCEV *URemRHS = nullptr;
13392       if (matchURem(LHS, URemLHS, URemRHS)) {
13393         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13394           Value *V = LHSUnknown->getValue();
13395           auto Multiple =
13396               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13397                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13398           RewriteMap[V] = Multiple;
13399           return;
13400         }
13401       }
13402     }
13403 
13404     if (!isa<SCEVUnknown>(LHS)) {
13405       std::swap(LHS, RHS);
13406       Predicate = CmpInst::getSwappedPredicate(Predicate);
13407     }
13408 
13409     // For now, limit to conditions that provide information about unknown
13410     // expressions.
13411     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13412     if (!LHSUnknown)
13413       return;
13414 
13415     // TODO: use information from more predicates.
13416     switch (Predicate) {
13417     case CmpInst::ICMP_ULT: {
13418       if (!containsAddRecurrence(RHS)) {
13419         const SCEV *Base = LHS;
13420         auto I = RewriteMap.find(LHSUnknown->getValue());
13421         if (I != RewriteMap.end())
13422           Base = I->second;
13423 
13424         RewriteMap[LHSUnknown->getValue()] =
13425             getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13426       }
13427       break;
13428     }
13429     case CmpInst::ICMP_ULE: {
13430       if (!containsAddRecurrence(RHS)) {
13431         const SCEV *Base = LHS;
13432         auto I = RewriteMap.find(LHSUnknown->getValue());
13433         if (I != RewriteMap.end())
13434           Base = I->second;
13435         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13436       }
13437       break;
13438     }
13439     case CmpInst::ICMP_EQ:
13440       if (isa<SCEVConstant>(RHS))
13441         RewriteMap[LHSUnknown->getValue()] = RHS;
13442       break;
13443     case CmpInst::ICMP_NE:
13444       if (isa<SCEVConstant>(RHS) &&
13445           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13446         RewriteMap[LHSUnknown->getValue()] =
13447             getUMaxExpr(LHS, getOne(RHS->getType()));
13448       break;
13449     default:
13450       break;
13451     }
13452   };
13453   // Starting at the loop predecessor, climb up the predecessor chain, as long
13454   // as there are predecessors that can be found that have unique successors
13455   // leading to the original header.
13456   // TODO: share this logic with isLoopEntryGuardedByCond.
13457   ValueToSCEVMapTy RewriteMap;
13458   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13459            L->getLoopPredecessor(), L->getHeader());
13460        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13461 
13462     const BranchInst *LoopEntryPredicate =
13463         dyn_cast<BranchInst>(Pair.first->getTerminator());
13464     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13465       continue;
13466 
13467     // TODO: use information from more complex conditions, e.g. AND expressions.
13468     auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13469     if (!Cmp)
13470       continue;
13471 
13472     auto Predicate = Cmp->getPredicate();
13473     if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13474       Predicate = CmpInst::getInversePredicate(Predicate);
13475     CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13476                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13477   }
13478 
13479   // Also collect information from assumptions dominating the loop.
13480   for (auto &AssumeVH : AC.assumptions()) {
13481     if (!AssumeVH)
13482       continue;
13483     auto *AssumeI = cast<CallInst>(AssumeVH);
13484     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13485     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13486       continue;
13487     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13488                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13489   }
13490 
13491   if (RewriteMap.empty())
13492     return Expr;
13493   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13494   return Rewriter.visit(Expr);
13495 }
13496