1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionDivision.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/InitializePasses.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/KnownBits.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <climits>
128 #include <cstddef>
129 #include <cstdint>
130 #include <cstdlib>
131 #include <map>
132 #include <memory>
133 #include <tuple>
134 #include <utility>
135 #include <vector>
136 
137 using namespace llvm;
138 using namespace PatternMatch;
139 
140 #define DEBUG_TYPE "scalar-evolution"
141 
142 STATISTIC(NumTripCountsComputed,
143           "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed,
145           "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147           "Number of loops with trip counts computed by force");
148 
149 static cl::opt<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151                         cl::ZeroOrMore,
152                         cl::desc("Maximum number of iterations SCEV will "
153                                  "symbolically execute a constant "
154                                  "derived loop"),
155                         cl::init(100));
156 
157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
158 static cl::opt<bool> VerifySCEV(
159     "verify-scev", cl::Hidden,
160     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
161 static cl::opt<bool> VerifySCEVStrict(
162     "verify-scev-strict", cl::Hidden,
163     cl::desc("Enable stricter verification with -verify-scev is passed"));
164 static cl::opt<bool>
165     VerifySCEVMap("verify-scev-maps", cl::Hidden,
166                   cl::desc("Verify no dangling value in ScalarEvolution's "
167                            "ExprValueMap (slow)"));
168 
169 static cl::opt<bool> VerifyIR(
170     "scev-verify-ir", cl::Hidden,
171     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
172     cl::init(false));
173 
174 static cl::opt<unsigned> MulOpsInlineThreshold(
175     "scev-mulops-inline-threshold", cl::Hidden,
176     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
177     cl::init(32));
178 
179 static cl::opt<unsigned> AddOpsInlineThreshold(
180     "scev-addops-inline-threshold", cl::Hidden,
181     cl::desc("Threshold for inlining addition operands into a SCEV"),
182     cl::init(500));
183 
184 static cl::opt<unsigned> MaxSCEVCompareDepth(
185     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
187     cl::init(32));
188 
189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
190     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
191     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
192     cl::init(2));
193 
194 static cl::opt<unsigned> MaxValueCompareDepth(
195     "scalar-evolution-max-value-compare-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive value complexity comparisons"),
197     cl::init(2));
198 
199 static cl::opt<unsigned>
200     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
201                   cl::desc("Maximum depth of recursive arithmetics"),
202                   cl::init(32));
203 
204 static cl::opt<unsigned> MaxConstantEvolvingDepth(
205     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
206     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
207 
208 static cl::opt<unsigned>
209     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
210                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
211                  cl::init(8));
212 
213 static cl::opt<unsigned>
214     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
215                   cl::desc("Max coefficients in AddRec during evolving"),
216                   cl::init(8));
217 
218 static cl::opt<unsigned>
219     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
220                   cl::desc("Size of the expression which is considered huge"),
221                   cl::init(4096));
222 
223 static cl::opt<bool>
224 ClassifyExpressions("scalar-evolution-classify-expressions",
225     cl::Hidden, cl::init(true),
226     cl::desc("When printing analysis, include information on every instruction"));
227 
228 static cl::opt<bool> UseExpensiveRangeSharpening(
229     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
230     cl::init(false),
231     cl::desc("Use more powerful methods of sharpening expression ranges. May "
232              "be costly in terms of compile time"));
233 
234 //===----------------------------------------------------------------------===//
235 //                           SCEV class definitions
236 //===----------------------------------------------------------------------===//
237 
238 //===----------------------------------------------------------------------===//
239 // Implementation of the SCEV class.
240 //
241 
242 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
243 LLVM_DUMP_METHOD void SCEV::dump() const {
244   print(dbgs());
245   dbgs() << '\n';
246 }
247 #endif
248 
249 void SCEV::print(raw_ostream &OS) const {
250   switch (getSCEVType()) {
251   case scConstant:
252     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
253     return;
254   case scPtrToInt: {
255     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
256     const SCEV *Op = PtrToInt->getOperand();
257     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
258        << *PtrToInt->getType() << ")";
259     return;
260   }
261   case scTruncate: {
262     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
263     const SCEV *Op = Trunc->getOperand();
264     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
265        << *Trunc->getType() << ")";
266     return;
267   }
268   case scZeroExtend: {
269     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
270     const SCEV *Op = ZExt->getOperand();
271     OS << "(zext " << *Op->getType() << " " << *Op << " to "
272        << *ZExt->getType() << ")";
273     return;
274   }
275   case scSignExtend: {
276     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
277     const SCEV *Op = SExt->getOperand();
278     OS << "(sext " << *Op->getType() << " " << *Op << " to "
279        << *SExt->getType() << ")";
280     return;
281   }
282   case scAddRecExpr: {
283     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
284     OS << "{" << *AR->getOperand(0);
285     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
286       OS << ",+," << *AR->getOperand(i);
287     OS << "}<";
288     if (AR->hasNoUnsignedWrap())
289       OS << "nuw><";
290     if (AR->hasNoSignedWrap())
291       OS << "nsw><";
292     if (AR->hasNoSelfWrap() &&
293         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
294       OS << "nw><";
295     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
296     OS << ">";
297     return;
298   }
299   case scAddExpr:
300   case scMulExpr:
301   case scUMaxExpr:
302   case scSMaxExpr:
303   case scUMinExpr:
304   case scSMinExpr: {
305     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
306     const char *OpStr = nullptr;
307     switch (NAry->getSCEVType()) {
308     case scAddExpr: OpStr = " + "; break;
309     case scMulExpr: OpStr = " * "; break;
310     case scUMaxExpr: OpStr = " umax "; break;
311     case scSMaxExpr: OpStr = " smax "; break;
312     case scUMinExpr:
313       OpStr = " umin ";
314       break;
315     case scSMinExpr:
316       OpStr = " smin ";
317       break;
318     default:
319       llvm_unreachable("There are no other nary expression types.");
320     }
321     OS << "(";
322     ListSeparator LS(OpStr);
323     for (const SCEV *Op : NAry->operands())
324       OS << LS << *Op;
325     OS << ")";
326     switch (NAry->getSCEVType()) {
327     case scAddExpr:
328     case scMulExpr:
329       if (NAry->hasNoUnsignedWrap())
330         OS << "<nuw>";
331       if (NAry->hasNoSignedWrap())
332         OS << "<nsw>";
333       break;
334     default:
335       // Nothing to print for other nary expressions.
336       break;
337     }
338     return;
339   }
340   case scUDivExpr: {
341     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
342     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
343     return;
344   }
345   case scUnknown: {
346     const SCEVUnknown *U = cast<SCEVUnknown>(this);
347     Type *AllocTy;
348     if (U->isSizeOf(AllocTy)) {
349       OS << "sizeof(" << *AllocTy << ")";
350       return;
351     }
352     if (U->isAlignOf(AllocTy)) {
353       OS << "alignof(" << *AllocTy << ")";
354       return;
355     }
356 
357     Type *CTy;
358     Constant *FieldNo;
359     if (U->isOffsetOf(CTy, FieldNo)) {
360       OS << "offsetof(" << *CTy << ", ";
361       FieldNo->printAsOperand(OS, false);
362       OS << ")";
363       return;
364     }
365 
366     // Otherwise just print it normally.
367     U->getValue()->printAsOperand(OS, false);
368     return;
369   }
370   case scCouldNotCompute:
371     OS << "***COULDNOTCOMPUTE***";
372     return;
373   }
374   llvm_unreachable("Unknown SCEV kind!");
375 }
376 
377 Type *SCEV::getType() const {
378   switch (getSCEVType()) {
379   case scConstant:
380     return cast<SCEVConstant>(this)->getType();
381   case scPtrToInt:
382   case scTruncate:
383   case scZeroExtend:
384   case scSignExtend:
385     return cast<SCEVCastExpr>(this)->getType();
386   case scAddRecExpr:
387     return cast<SCEVAddRecExpr>(this)->getType();
388   case scMulExpr:
389     return cast<SCEVMulExpr>(this)->getType();
390   case scUMaxExpr:
391   case scSMaxExpr:
392   case scUMinExpr:
393   case scSMinExpr:
394     return cast<SCEVMinMaxExpr>(this)->getType();
395   case scAddExpr:
396     return cast<SCEVAddExpr>(this)->getType();
397   case scUDivExpr:
398     return cast<SCEVUDivExpr>(this)->getType();
399   case scUnknown:
400     return cast<SCEVUnknown>(this)->getType();
401   case scCouldNotCompute:
402     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
403   }
404   llvm_unreachable("Unknown SCEV kind!");
405 }
406 
407 bool SCEV::isZero() const {
408   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
409     return SC->getValue()->isZero();
410   return false;
411 }
412 
413 bool SCEV::isOne() const {
414   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
415     return SC->getValue()->isOne();
416   return false;
417 }
418 
419 bool SCEV::isAllOnesValue() const {
420   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
421     return SC->getValue()->isMinusOne();
422   return false;
423 }
424 
425 bool SCEV::isNonConstantNegative() const {
426   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
427   if (!Mul) return false;
428 
429   // If there is a constant factor, it will be first.
430   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
431   if (!SC) return false;
432 
433   // Return true if the value is negative, this matches things like (-42 * V).
434   return SC->getAPInt().isNegative();
435 }
436 
437 SCEVCouldNotCompute::SCEVCouldNotCompute() :
438   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
439 
440 bool SCEVCouldNotCompute::classof(const SCEV *S) {
441   return S->getSCEVType() == scCouldNotCompute;
442 }
443 
444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
445   FoldingSetNodeID ID;
446   ID.AddInteger(scConstant);
447   ID.AddPointer(V);
448   void *IP = nullptr;
449   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
450   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
451   UniqueSCEVs.InsertNode(S, IP);
452   return S;
453 }
454 
455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
456   return getConstant(ConstantInt::get(getContext(), Val));
457 }
458 
459 const SCEV *
460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
461   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
462   return getConstant(ConstantInt::get(ITy, V, isSigned));
463 }
464 
465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
466                            const SCEV *op, Type *ty)
467     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
468   Operands[0] = op;
469 }
470 
471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
472                                    Type *ITy)
473     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
474   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
475          "Must be a non-bit-width-changing pointer-to-integer cast!");
476 }
477 
478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
479                                            SCEVTypes SCEVTy, const SCEV *op,
480                                            Type *ty)
481     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
482 
483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
484                                    Type *ty)
485     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
486   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
487          "Cannot truncate non-integer value!");
488 }
489 
490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
491                                        const SCEV *op, Type *ty)
492     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
493   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
494          "Cannot zero extend non-integer value!");
495 }
496 
497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
498                                        const SCEV *op, Type *ty)
499     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
500   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
501          "Cannot sign extend non-integer value!");
502 }
503 
504 void SCEVUnknown::deleted() {
505   // Clear this SCEVUnknown from various maps.
506   SE->forgetMemoizedResults(this);
507 
508   // Remove this SCEVUnknown from the uniquing map.
509   SE->UniqueSCEVs.RemoveNode(this);
510 
511   // Release the value.
512   setValPtr(nullptr);
513 }
514 
515 void SCEVUnknown::allUsesReplacedWith(Value *New) {
516   // Remove this SCEVUnknown from the uniquing map.
517   SE->UniqueSCEVs.RemoveNode(this);
518 
519   // Update this SCEVUnknown to point to the new value. This is needed
520   // because there may still be outstanding SCEVs which still point to
521   // this SCEVUnknown.
522   setValPtr(New);
523 }
524 
525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
526   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
527     if (VCE->getOpcode() == Instruction::PtrToInt)
528       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
529         if (CE->getOpcode() == Instruction::GetElementPtr &&
530             CE->getOperand(0)->isNullValue() &&
531             CE->getNumOperands() == 2)
532           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
533             if (CI->isOne()) {
534               AllocTy = cast<GEPOperator>(CE)->getSourceElementType();
535               return true;
536             }
537 
538   return false;
539 }
540 
541 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
542   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
543     if (VCE->getOpcode() == Instruction::PtrToInt)
544       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
545         if (CE->getOpcode() == Instruction::GetElementPtr &&
546             CE->getOperand(0)->isNullValue()) {
547           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
548           if (StructType *STy = dyn_cast<StructType>(Ty))
549             if (!STy->isPacked() &&
550                 CE->getNumOperands() == 3 &&
551                 CE->getOperand(1)->isNullValue()) {
552               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
553                 if (CI->isOne() &&
554                     STy->getNumElements() == 2 &&
555                     STy->getElementType(0)->isIntegerTy(1)) {
556                   AllocTy = STy->getElementType(1);
557                   return true;
558                 }
559             }
560         }
561 
562   return false;
563 }
564 
565 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
566   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
567     if (VCE->getOpcode() == Instruction::PtrToInt)
568       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
569         if (CE->getOpcode() == Instruction::GetElementPtr &&
570             CE->getNumOperands() == 3 &&
571             CE->getOperand(0)->isNullValue() &&
572             CE->getOperand(1)->isNullValue()) {
573           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
574           // Ignore vector types here so that ScalarEvolutionExpander doesn't
575           // emit getelementptrs that index into vectors.
576           if (Ty->isStructTy() || Ty->isArrayTy()) {
577             CTy = Ty;
578             FieldNo = CE->getOperand(2);
579             return true;
580           }
581         }
582 
583   return false;
584 }
585 
586 //===----------------------------------------------------------------------===//
587 //                               SCEV Utilities
588 //===----------------------------------------------------------------------===//
589 
590 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
591 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
592 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
593 /// have been previously deemed to be "equally complex" by this routine.  It is
594 /// intended to avoid exponential time complexity in cases like:
595 ///
596 ///   %a = f(%x, %y)
597 ///   %b = f(%a, %a)
598 ///   %c = f(%b, %b)
599 ///
600 ///   %d = f(%x, %y)
601 ///   %e = f(%d, %d)
602 ///   %f = f(%e, %e)
603 ///
604 ///   CompareValueComplexity(%f, %c)
605 ///
606 /// Since we do not continue running this routine on expression trees once we
607 /// have seen unequal values, there is no need to track them in the cache.
608 static int
609 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
610                        const LoopInfo *const LI, Value *LV, Value *RV,
611                        unsigned Depth) {
612   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
613     return 0;
614 
615   // Order pointer values after integer values. This helps SCEVExpander form
616   // GEPs.
617   bool LIsPointer = LV->getType()->isPointerTy(),
618        RIsPointer = RV->getType()->isPointerTy();
619   if (LIsPointer != RIsPointer)
620     return (int)LIsPointer - (int)RIsPointer;
621 
622   // Compare getValueID values.
623   unsigned LID = LV->getValueID(), RID = RV->getValueID();
624   if (LID != RID)
625     return (int)LID - (int)RID;
626 
627   // Sort arguments by their position.
628   if (const auto *LA = dyn_cast<Argument>(LV)) {
629     const auto *RA = cast<Argument>(RV);
630     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
631     return (int)LArgNo - (int)RArgNo;
632   }
633 
634   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
635     const auto *RGV = cast<GlobalValue>(RV);
636 
637     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
638       auto LT = GV->getLinkage();
639       return !(GlobalValue::isPrivateLinkage(LT) ||
640                GlobalValue::isInternalLinkage(LT));
641     };
642 
643     // Use the names to distinguish the two values, but only if the
644     // names are semantically important.
645     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
646       return LGV->getName().compare(RGV->getName());
647   }
648 
649   // For instructions, compare their loop depth, and their operand count.  This
650   // is pretty loose.
651   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
652     const auto *RInst = cast<Instruction>(RV);
653 
654     // Compare loop depths.
655     const BasicBlock *LParent = LInst->getParent(),
656                      *RParent = RInst->getParent();
657     if (LParent != RParent) {
658       unsigned LDepth = LI->getLoopDepth(LParent),
659                RDepth = LI->getLoopDepth(RParent);
660       if (LDepth != RDepth)
661         return (int)LDepth - (int)RDepth;
662     }
663 
664     // Compare the number of operands.
665     unsigned LNumOps = LInst->getNumOperands(),
666              RNumOps = RInst->getNumOperands();
667     if (LNumOps != RNumOps)
668       return (int)LNumOps - (int)RNumOps;
669 
670     for (unsigned Idx : seq(0u, LNumOps)) {
671       int Result =
672           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
673                                  RInst->getOperand(Idx), Depth + 1);
674       if (Result != 0)
675         return Result;
676     }
677   }
678 
679   EqCacheValue.unionSets(LV, RV);
680   return 0;
681 }
682 
683 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
684 // than RHS, respectively. A three-way result allows recursive comparisons to be
685 // more efficient.
686 // If the max analysis depth was reached, return None, assuming we do not know
687 // if they are equivalent for sure.
688 static Optional<int>
689 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
690                       EquivalenceClasses<const Value *> &EqCacheValue,
691                       const LoopInfo *const LI, const SCEV *LHS,
692                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
693   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
694   if (LHS == RHS)
695     return 0;
696 
697   // Primarily, sort the SCEVs by their getSCEVType().
698   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
699   if (LType != RType)
700     return (int)LType - (int)RType;
701 
702   if (EqCacheSCEV.isEquivalent(LHS, RHS))
703     return 0;
704 
705   if (Depth > MaxSCEVCompareDepth)
706     return None;
707 
708   // Aside from the getSCEVType() ordering, the particular ordering
709   // isn't very important except that it's beneficial to be consistent,
710   // so that (a + b) and (b + a) don't end up as different expressions.
711   switch (LType) {
712   case scUnknown: {
713     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
714     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
715 
716     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
717                                    RU->getValue(), Depth + 1);
718     if (X == 0)
719       EqCacheSCEV.unionSets(LHS, RHS);
720     return X;
721   }
722 
723   case scConstant: {
724     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
725     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
726 
727     // Compare constant values.
728     const APInt &LA = LC->getAPInt();
729     const APInt &RA = RC->getAPInt();
730     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
731     if (LBitWidth != RBitWidth)
732       return (int)LBitWidth - (int)RBitWidth;
733     return LA.ult(RA) ? -1 : 1;
734   }
735 
736   case scAddRecExpr: {
737     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
738     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
739 
740     // There is always a dominance between two recs that are used by one SCEV,
741     // so we can safely sort recs by loop header dominance. We require such
742     // order in getAddExpr.
743     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
744     if (LLoop != RLoop) {
745       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
746       assert(LHead != RHead && "Two loops share the same header?");
747       if (DT.dominates(LHead, RHead))
748         return 1;
749       else
750         assert(DT.dominates(RHead, LHead) &&
751                "No dominance between recurrences used by one SCEV?");
752       return -1;
753     }
754 
755     // Addrec complexity grows with operand count.
756     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
757     if (LNumOps != RNumOps)
758       return (int)LNumOps - (int)RNumOps;
759 
760     // Lexicographically compare.
761     for (unsigned i = 0; i != LNumOps; ++i) {
762       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
763                                      LA->getOperand(i), RA->getOperand(i), DT,
764                                      Depth + 1);
765       if (X != 0)
766         return X;
767     }
768     EqCacheSCEV.unionSets(LHS, RHS);
769     return 0;
770   }
771 
772   case scAddExpr:
773   case scMulExpr:
774   case scSMaxExpr:
775   case scUMaxExpr:
776   case scSMinExpr:
777   case scUMinExpr: {
778     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
779     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
780 
781     // Lexicographically compare n-ary expressions.
782     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
783     if (LNumOps != RNumOps)
784       return (int)LNumOps - (int)RNumOps;
785 
786     for (unsigned i = 0; i != LNumOps; ++i) {
787       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
788                                      LC->getOperand(i), RC->getOperand(i), DT,
789                                      Depth + 1);
790       if (X != 0)
791         return X;
792     }
793     EqCacheSCEV.unionSets(LHS, RHS);
794     return 0;
795   }
796 
797   case scUDivExpr: {
798     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
799     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
800 
801     // Lexicographically compare udiv expressions.
802     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
803                                    RC->getLHS(), DT, Depth + 1);
804     if (X != 0)
805       return X;
806     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
807                               RC->getRHS(), DT, Depth + 1);
808     if (X == 0)
809       EqCacheSCEV.unionSets(LHS, RHS);
810     return X;
811   }
812 
813   case scPtrToInt:
814   case scTruncate:
815   case scZeroExtend:
816   case scSignExtend: {
817     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
818     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
819 
820     // Compare cast expressions by operand.
821     auto X =
822         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
823                               RC->getOperand(), DT, Depth + 1);
824     if (X == 0)
825       EqCacheSCEV.unionSets(LHS, RHS);
826     return X;
827   }
828 
829   case scCouldNotCompute:
830     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
831   }
832   llvm_unreachable("Unknown SCEV kind!");
833 }
834 
835 /// Given a list of SCEV objects, order them by their complexity, and group
836 /// objects of the same complexity together by value.  When this routine is
837 /// finished, we know that any duplicates in the vector are consecutive and that
838 /// complexity is monotonically increasing.
839 ///
840 /// Note that we go take special precautions to ensure that we get deterministic
841 /// results from this routine.  In other words, we don't want the results of
842 /// this to depend on where the addresses of various SCEV objects happened to
843 /// land in memory.
844 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
845                               LoopInfo *LI, DominatorTree &DT) {
846   if (Ops.size() < 2) return;  // Noop
847 
848   EquivalenceClasses<const SCEV *> EqCacheSCEV;
849   EquivalenceClasses<const Value *> EqCacheValue;
850 
851   // Whether LHS has provably less complexity than RHS.
852   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
853     auto Complexity =
854         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
855     return Complexity && *Complexity < 0;
856   };
857   if (Ops.size() == 2) {
858     // This is the common case, which also happens to be trivially simple.
859     // Special case it.
860     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
861     if (IsLessComplex(RHS, LHS))
862       std::swap(LHS, RHS);
863     return;
864   }
865 
866   // Do the rough sort by complexity.
867   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
868     return IsLessComplex(LHS, RHS);
869   });
870 
871   // Now that we are sorted by complexity, group elements of the same
872   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
873   // be extremely short in practice.  Note that we take this approach because we
874   // do not want to depend on the addresses of the objects we are grouping.
875   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
876     const SCEV *S = Ops[i];
877     unsigned Complexity = S->getSCEVType();
878 
879     // If there are any objects of the same complexity and same value as this
880     // one, group them.
881     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
882       if (Ops[j] == S) { // Found a duplicate.
883         // Move it to immediately after i'th element.
884         std::swap(Ops[i+1], Ops[j]);
885         ++i;   // no need to rescan it.
886         if (i == e-2) return;  // Done!
887       }
888     }
889   }
890 }
891 
892 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
893 /// least HugeExprThreshold nodes).
894 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
895   return any_of(Ops, [](const SCEV *S) {
896     return S->getExpressionSize() >= HugeExprThreshold;
897   });
898 }
899 
900 //===----------------------------------------------------------------------===//
901 //                      Simple SCEV method implementations
902 //===----------------------------------------------------------------------===//
903 
904 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
905 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
906                                        ScalarEvolution &SE,
907                                        Type *ResultTy) {
908   // Handle the simplest case efficiently.
909   if (K == 1)
910     return SE.getTruncateOrZeroExtend(It, ResultTy);
911 
912   // We are using the following formula for BC(It, K):
913   //
914   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
915   //
916   // Suppose, W is the bitwidth of the return value.  We must be prepared for
917   // overflow.  Hence, we must assure that the result of our computation is
918   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
919   // safe in modular arithmetic.
920   //
921   // However, this code doesn't use exactly that formula; the formula it uses
922   // is something like the following, where T is the number of factors of 2 in
923   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
924   // exponentiation:
925   //
926   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
927   //
928   // This formula is trivially equivalent to the previous formula.  However,
929   // this formula can be implemented much more efficiently.  The trick is that
930   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
931   // arithmetic.  To do exact division in modular arithmetic, all we have
932   // to do is multiply by the inverse.  Therefore, this step can be done at
933   // width W.
934   //
935   // The next issue is how to safely do the division by 2^T.  The way this
936   // is done is by doing the multiplication step at a width of at least W + T
937   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
938   // when we perform the division by 2^T (which is equivalent to a right shift
939   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
940   // truncated out after the division by 2^T.
941   //
942   // In comparison to just directly using the first formula, this technique
943   // is much more efficient; using the first formula requires W * K bits,
944   // but this formula less than W + K bits. Also, the first formula requires
945   // a division step, whereas this formula only requires multiplies and shifts.
946   //
947   // It doesn't matter whether the subtraction step is done in the calculation
948   // width or the input iteration count's width; if the subtraction overflows,
949   // the result must be zero anyway.  We prefer here to do it in the width of
950   // the induction variable because it helps a lot for certain cases; CodeGen
951   // isn't smart enough to ignore the overflow, which leads to much less
952   // efficient code if the width of the subtraction is wider than the native
953   // register width.
954   //
955   // (It's possible to not widen at all by pulling out factors of 2 before
956   // the multiplication; for example, K=2 can be calculated as
957   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
958   // extra arithmetic, so it's not an obvious win, and it gets
959   // much more complicated for K > 3.)
960 
961   // Protection from insane SCEVs; this bound is conservative,
962   // but it probably doesn't matter.
963   if (K > 1000)
964     return SE.getCouldNotCompute();
965 
966   unsigned W = SE.getTypeSizeInBits(ResultTy);
967 
968   // Calculate K! / 2^T and T; we divide out the factors of two before
969   // multiplying for calculating K! / 2^T to avoid overflow.
970   // Other overflow doesn't matter because we only care about the bottom
971   // W bits of the result.
972   APInt OddFactorial(W, 1);
973   unsigned T = 1;
974   for (unsigned i = 3; i <= K; ++i) {
975     APInt Mult(W, i);
976     unsigned TwoFactors = Mult.countTrailingZeros();
977     T += TwoFactors;
978     Mult.lshrInPlace(TwoFactors);
979     OddFactorial *= Mult;
980   }
981 
982   // We need at least W + T bits for the multiplication step
983   unsigned CalculationBits = W + T;
984 
985   // Calculate 2^T, at width T+W.
986   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
987 
988   // Calculate the multiplicative inverse of K! / 2^T;
989   // this multiplication factor will perform the exact division by
990   // K! / 2^T.
991   APInt Mod = APInt::getSignedMinValue(W+1);
992   APInt MultiplyFactor = OddFactorial.zext(W+1);
993   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
994   MultiplyFactor = MultiplyFactor.trunc(W);
995 
996   // Calculate the product, at width T+W
997   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
998                                                       CalculationBits);
999   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1000   for (unsigned i = 1; i != K; ++i) {
1001     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1002     Dividend = SE.getMulExpr(Dividend,
1003                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1004   }
1005 
1006   // Divide by 2^T
1007   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1008 
1009   // Truncate the result, and divide by K! / 2^T.
1010 
1011   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1012                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1013 }
1014 
1015 /// Return the value of this chain of recurrences at the specified iteration
1016 /// number.  We can evaluate this recurrence by multiplying each element in the
1017 /// chain by the binomial coefficient corresponding to it.  In other words, we
1018 /// can evaluate {A,+,B,+,C,+,D} as:
1019 ///
1020 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1021 ///
1022 /// where BC(It, k) stands for binomial coefficient.
1023 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1024                                                 ScalarEvolution &SE) const {
1025   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1026 }
1027 
1028 const SCEV *
1029 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1030                                     const SCEV *It, ScalarEvolution &SE) {
1031   assert(Operands.size() > 0);
1032   const SCEV *Result = Operands[0];
1033   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1034     // The computation is correct in the face of overflow provided that the
1035     // multiplication is performed _after_ the evaluation of the binomial
1036     // coefficient.
1037     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1038     if (isa<SCEVCouldNotCompute>(Coeff))
1039       return Coeff;
1040 
1041     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1042   }
1043   return Result;
1044 }
1045 
1046 //===----------------------------------------------------------------------===//
1047 //                    SCEV Expression folder implementations
1048 //===----------------------------------------------------------------------===//
1049 
1050 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1051                                                      unsigned Depth) {
1052   assert(Depth <= 1 &&
1053          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1054 
1055   // We could be called with an integer-typed operands during SCEV rewrites.
1056   // Since the operand is an integer already, just perform zext/trunc/self cast.
1057   if (!Op->getType()->isPointerTy())
1058     return Op;
1059 
1060   // What would be an ID for such a SCEV cast expression?
1061   FoldingSetNodeID ID;
1062   ID.AddInteger(scPtrToInt);
1063   ID.AddPointer(Op);
1064 
1065   void *IP = nullptr;
1066 
1067   // Is there already an expression for such a cast?
1068   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1069     return S;
1070 
1071   // It isn't legal for optimizations to construct new ptrtoint expressions
1072   // for non-integral pointers.
1073   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1074     return getCouldNotCompute();
1075 
1076   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1077 
1078   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1079   // is sufficiently wide to represent all possible pointer values.
1080   // We could theoretically teach SCEV to truncate wider pointers, but
1081   // that isn't implemented for now.
1082   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1083       getDataLayout().getTypeSizeInBits(IntPtrTy))
1084     return getCouldNotCompute();
1085 
1086   // If not, is this expression something we can't reduce any further?
1087   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1088     // Perform some basic constant folding. If the operand of the ptr2int cast
1089     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1090     // left as-is), but produce a zero constant.
1091     // NOTE: We could handle a more general case, but lack motivational cases.
1092     if (isa<ConstantPointerNull>(U->getValue()))
1093       return getZero(IntPtrTy);
1094 
1095     // Create an explicit cast node.
1096     // We can reuse the existing insert position since if we get here,
1097     // we won't have made any changes which would invalidate it.
1098     SCEV *S = new (SCEVAllocator)
1099         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1100     UniqueSCEVs.InsertNode(S, IP);
1101     registerUser(S, Op);
1102     return S;
1103   }
1104 
1105   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1106                        "non-SCEVUnknown's.");
1107 
1108   // Otherwise, we've got some expression that is more complex than just a
1109   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1110   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1111   // only, and the expressions must otherwise be integer-typed.
1112   // So sink the cast down to the SCEVUnknown's.
1113 
1114   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1115   /// which computes a pointer-typed value, and rewrites the whole expression
1116   /// tree so that *all* the computations are done on integers, and the only
1117   /// pointer-typed operands in the expression are SCEVUnknown.
1118   class SCEVPtrToIntSinkingRewriter
1119       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1120     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1121 
1122   public:
1123     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1124 
1125     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1126       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1127       return Rewriter.visit(Scev);
1128     }
1129 
1130     const SCEV *visit(const SCEV *S) {
1131       Type *STy = S->getType();
1132       // If the expression is not pointer-typed, just keep it as-is.
1133       if (!STy->isPointerTy())
1134         return S;
1135       // Else, recursively sink the cast down into it.
1136       return Base::visit(S);
1137     }
1138 
1139     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1140       SmallVector<const SCEV *, 2> Operands;
1141       bool Changed = false;
1142       for (auto *Op : Expr->operands()) {
1143         Operands.push_back(visit(Op));
1144         Changed |= Op != Operands.back();
1145       }
1146       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1147     }
1148 
1149     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1150       SmallVector<const SCEV *, 2> Operands;
1151       bool Changed = false;
1152       for (auto *Op : Expr->operands()) {
1153         Operands.push_back(visit(Op));
1154         Changed |= Op != Operands.back();
1155       }
1156       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1157     }
1158 
1159     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1160       assert(Expr->getType()->isPointerTy() &&
1161              "Should only reach pointer-typed SCEVUnknown's.");
1162       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1163     }
1164   };
1165 
1166   // And actually perform the cast sinking.
1167   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1168   assert(IntOp->getType()->isIntegerTy() &&
1169          "We must have succeeded in sinking the cast, "
1170          "and ending up with an integer-typed expression!");
1171   return IntOp;
1172 }
1173 
1174 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1175   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1176 
1177   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1178   if (isa<SCEVCouldNotCompute>(IntOp))
1179     return IntOp;
1180 
1181   return getTruncateOrZeroExtend(IntOp, Ty);
1182 }
1183 
1184 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1185                                              unsigned Depth) {
1186   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1187          "This is not a truncating conversion!");
1188   assert(isSCEVable(Ty) &&
1189          "This is not a conversion to a SCEVable type!");
1190   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1191   Ty = getEffectiveSCEVType(Ty);
1192 
1193   FoldingSetNodeID ID;
1194   ID.AddInteger(scTruncate);
1195   ID.AddPointer(Op);
1196   ID.AddPointer(Ty);
1197   void *IP = nullptr;
1198   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1199 
1200   // Fold if the operand is constant.
1201   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1202     return getConstant(
1203       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1204 
1205   // trunc(trunc(x)) --> trunc(x)
1206   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1207     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1208 
1209   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1210   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1211     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1212 
1213   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1214   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1215     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1216 
1217   if (Depth > MaxCastDepth) {
1218     SCEV *S =
1219         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1220     UniqueSCEVs.InsertNode(S, IP);
1221     registerUser(S, Op);
1222     return S;
1223   }
1224 
1225   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1226   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1227   // if after transforming we have at most one truncate, not counting truncates
1228   // that replace other casts.
1229   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1230     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1231     SmallVector<const SCEV *, 4> Operands;
1232     unsigned numTruncs = 0;
1233     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1234          ++i) {
1235       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1236       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1237           isa<SCEVTruncateExpr>(S))
1238         numTruncs++;
1239       Operands.push_back(S);
1240     }
1241     if (numTruncs < 2) {
1242       if (isa<SCEVAddExpr>(Op))
1243         return getAddExpr(Operands);
1244       else if (isa<SCEVMulExpr>(Op))
1245         return getMulExpr(Operands);
1246       else
1247         llvm_unreachable("Unexpected SCEV type for Op.");
1248     }
1249     // Although we checked in the beginning that ID is not in the cache, it is
1250     // possible that during recursion and different modification ID was inserted
1251     // into the cache. So if we find it, just return it.
1252     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1253       return S;
1254   }
1255 
1256   // If the input value is a chrec scev, truncate the chrec's operands.
1257   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1258     SmallVector<const SCEV *, 4> Operands;
1259     for (const SCEV *Op : AddRec->operands())
1260       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1261     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1262   }
1263 
1264   // Return zero if truncating to known zeros.
1265   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1266   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1267     return getZero(Ty);
1268 
1269   // The cast wasn't folded; create an explicit cast node. We can reuse
1270   // the existing insert position since if we get here, we won't have
1271   // made any changes which would invalidate it.
1272   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1273                                                  Op, Ty);
1274   UniqueSCEVs.InsertNode(S, IP);
1275   registerUser(S, Op);
1276   return S;
1277 }
1278 
1279 // Get the limit of a recurrence such that incrementing by Step cannot cause
1280 // signed overflow as long as the value of the recurrence within the
1281 // loop does not exceed this limit before incrementing.
1282 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1283                                                  ICmpInst::Predicate *Pred,
1284                                                  ScalarEvolution *SE) {
1285   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1286   if (SE->isKnownPositive(Step)) {
1287     *Pred = ICmpInst::ICMP_SLT;
1288     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1289                            SE->getSignedRangeMax(Step));
1290   }
1291   if (SE->isKnownNegative(Step)) {
1292     *Pred = ICmpInst::ICMP_SGT;
1293     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1294                            SE->getSignedRangeMin(Step));
1295   }
1296   return nullptr;
1297 }
1298 
1299 // Get the limit of a recurrence such that incrementing by Step cannot cause
1300 // unsigned overflow as long as the value of the recurrence within the loop does
1301 // not exceed this limit before incrementing.
1302 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1303                                                    ICmpInst::Predicate *Pred,
1304                                                    ScalarEvolution *SE) {
1305   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1306   *Pred = ICmpInst::ICMP_ULT;
1307 
1308   return SE->getConstant(APInt::getMinValue(BitWidth) -
1309                          SE->getUnsignedRangeMax(Step));
1310 }
1311 
1312 namespace {
1313 
1314 struct ExtendOpTraitsBase {
1315   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1316                                                           unsigned);
1317 };
1318 
1319 // Used to make code generic over signed and unsigned overflow.
1320 template <typename ExtendOp> struct ExtendOpTraits {
1321   // Members present:
1322   //
1323   // static const SCEV::NoWrapFlags WrapType;
1324   //
1325   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1326   //
1327   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1328   //                                           ICmpInst::Predicate *Pred,
1329   //                                           ScalarEvolution *SE);
1330 };
1331 
1332 template <>
1333 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1334   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1335 
1336   static const GetExtendExprTy GetExtendExpr;
1337 
1338   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1339                                              ICmpInst::Predicate *Pred,
1340                                              ScalarEvolution *SE) {
1341     return getSignedOverflowLimitForStep(Step, Pred, SE);
1342   }
1343 };
1344 
1345 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1346     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1347 
1348 template <>
1349 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1350   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1351 
1352   static const GetExtendExprTy GetExtendExpr;
1353 
1354   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1355                                              ICmpInst::Predicate *Pred,
1356                                              ScalarEvolution *SE) {
1357     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1358   }
1359 };
1360 
1361 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1362     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1363 
1364 } // end anonymous namespace
1365 
1366 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1367 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1368 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1369 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1370 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1371 // expression "Step + sext/zext(PreIncAR)" is congruent with
1372 // "sext/zext(PostIncAR)"
1373 template <typename ExtendOpTy>
1374 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1375                                         ScalarEvolution *SE, unsigned Depth) {
1376   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1377   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1378 
1379   const Loop *L = AR->getLoop();
1380   const SCEV *Start = AR->getStart();
1381   const SCEV *Step = AR->getStepRecurrence(*SE);
1382 
1383   // Check for a simple looking step prior to loop entry.
1384   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1385   if (!SA)
1386     return nullptr;
1387 
1388   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1389   // subtraction is expensive. For this purpose, perform a quick and dirty
1390   // difference, by checking for Step in the operand list.
1391   SmallVector<const SCEV *, 4> DiffOps;
1392   for (const SCEV *Op : SA->operands())
1393     if (Op != Step)
1394       DiffOps.push_back(Op);
1395 
1396   if (DiffOps.size() == SA->getNumOperands())
1397     return nullptr;
1398 
1399   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1400   // `Step`:
1401 
1402   // 1. NSW/NUW flags on the step increment.
1403   auto PreStartFlags =
1404     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1405   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1406   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1407       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1408 
1409   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1410   // "S+X does not sign/unsign-overflow".
1411   //
1412 
1413   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1414   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1415       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1416     return PreStart;
1417 
1418   // 2. Direct overflow check on the step operation's expression.
1419   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1420   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1421   const SCEV *OperandExtendedStart =
1422       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1423                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1424   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1425     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1426       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1427       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1428       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1429       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1430     }
1431     return PreStart;
1432   }
1433 
1434   // 3. Loop precondition.
1435   ICmpInst::Predicate Pred;
1436   const SCEV *OverflowLimit =
1437       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1438 
1439   if (OverflowLimit &&
1440       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1441     return PreStart;
1442 
1443   return nullptr;
1444 }
1445 
1446 // Get the normalized zero or sign extended expression for this AddRec's Start.
1447 template <typename ExtendOpTy>
1448 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1449                                         ScalarEvolution *SE,
1450                                         unsigned Depth) {
1451   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1452 
1453   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1454   if (!PreStart)
1455     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1456 
1457   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1458                                              Depth),
1459                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1460 }
1461 
1462 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1463 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1464 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1465 //
1466 // Formally:
1467 //
1468 //     {S,+,X} == {S-T,+,X} + T
1469 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1470 //
1471 // If ({S-T,+,X} + T) does not overflow  ... (1)
1472 //
1473 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1474 //
1475 // If {S-T,+,X} does not overflow  ... (2)
1476 //
1477 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1478 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1479 //
1480 // If (S-T)+T does not overflow  ... (3)
1481 //
1482 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1483 //      == {Ext(S),+,Ext(X)} == LHS
1484 //
1485 // Thus, if (1), (2) and (3) are true for some T, then
1486 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1487 //
1488 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1489 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1490 // to check for (1) and (2).
1491 //
1492 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1493 // is `Delta` (defined below).
1494 template <typename ExtendOpTy>
1495 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1496                                                 const SCEV *Step,
1497                                                 const Loop *L) {
1498   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1499 
1500   // We restrict `Start` to a constant to prevent SCEV from spending too much
1501   // time here.  It is correct (but more expensive) to continue with a
1502   // non-constant `Start` and do a general SCEV subtraction to compute
1503   // `PreStart` below.
1504   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1505   if (!StartC)
1506     return false;
1507 
1508   APInt StartAI = StartC->getAPInt();
1509 
1510   for (unsigned Delta : {-2, -1, 1, 2}) {
1511     const SCEV *PreStart = getConstant(StartAI - Delta);
1512 
1513     FoldingSetNodeID ID;
1514     ID.AddInteger(scAddRecExpr);
1515     ID.AddPointer(PreStart);
1516     ID.AddPointer(Step);
1517     ID.AddPointer(L);
1518     void *IP = nullptr;
1519     const auto *PreAR =
1520       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1521 
1522     // Give up if we don't already have the add recurrence we need because
1523     // actually constructing an add recurrence is relatively expensive.
1524     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1525       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1526       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1527       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1528           DeltaS, &Pred, this);
1529       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1530         return true;
1531     }
1532   }
1533 
1534   return false;
1535 }
1536 
1537 // Finds an integer D for an expression (C + x + y + ...) such that the top
1538 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1539 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1540 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1541 // the (C + x + y + ...) expression is \p WholeAddExpr.
1542 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1543                                             const SCEVConstant *ConstantTerm,
1544                                             const SCEVAddExpr *WholeAddExpr) {
1545   const APInt &C = ConstantTerm->getAPInt();
1546   const unsigned BitWidth = C.getBitWidth();
1547   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1548   uint32_t TZ = BitWidth;
1549   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1550     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1551   if (TZ) {
1552     // Set D to be as many least significant bits of C as possible while still
1553     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1554     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1555   }
1556   return APInt(BitWidth, 0);
1557 }
1558 
1559 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1560 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1561 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1562 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1563 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1564                                             const APInt &ConstantStart,
1565                                             const SCEV *Step) {
1566   const unsigned BitWidth = ConstantStart.getBitWidth();
1567   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1568   if (TZ)
1569     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1570                          : ConstantStart;
1571   return APInt(BitWidth, 0);
1572 }
1573 
1574 const SCEV *
1575 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1576   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1577          "This is not an extending conversion!");
1578   assert(isSCEVable(Ty) &&
1579          "This is not a conversion to a SCEVable type!");
1580   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1581   Ty = getEffectiveSCEVType(Ty);
1582 
1583   // Fold if the operand is constant.
1584   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1585     return getConstant(
1586       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1587 
1588   // zext(zext(x)) --> zext(x)
1589   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1590     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1591 
1592   // Before doing any expensive analysis, check to see if we've already
1593   // computed a SCEV for this Op and Ty.
1594   FoldingSetNodeID ID;
1595   ID.AddInteger(scZeroExtend);
1596   ID.AddPointer(Op);
1597   ID.AddPointer(Ty);
1598   void *IP = nullptr;
1599   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1600   if (Depth > MaxCastDepth) {
1601     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1602                                                      Op, Ty);
1603     UniqueSCEVs.InsertNode(S, IP);
1604     registerUser(S, Op);
1605     return S;
1606   }
1607 
1608   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1609   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1610     // It's possible the bits taken off by the truncate were all zero bits. If
1611     // so, we should be able to simplify this further.
1612     const SCEV *X = ST->getOperand();
1613     ConstantRange CR = getUnsignedRange(X);
1614     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1615     unsigned NewBits = getTypeSizeInBits(Ty);
1616     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1617             CR.zextOrTrunc(NewBits)))
1618       return getTruncateOrZeroExtend(X, Ty, Depth);
1619   }
1620 
1621   // If the input value is a chrec scev, and we can prove that the value
1622   // did not overflow the old, smaller, value, we can zero extend all of the
1623   // operands (often constants).  This allows analysis of something like
1624   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1625   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1626     if (AR->isAffine()) {
1627       const SCEV *Start = AR->getStart();
1628       const SCEV *Step = AR->getStepRecurrence(*this);
1629       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1630       const Loop *L = AR->getLoop();
1631 
1632       if (!AR->hasNoUnsignedWrap()) {
1633         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1634         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1635       }
1636 
1637       // If we have special knowledge that this addrec won't overflow,
1638       // we don't need to do any further analysis.
1639       if (AR->hasNoUnsignedWrap())
1640         return getAddRecExpr(
1641             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1642             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1643 
1644       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1645       // Note that this serves two purposes: It filters out loops that are
1646       // simply not analyzable, and it covers the case where this code is
1647       // being called from within backedge-taken count analysis, such that
1648       // attempting to ask for the backedge-taken count would likely result
1649       // in infinite recursion. In the later case, the analysis code will
1650       // cope with a conservative value, and it will take care to purge
1651       // that value once it has finished.
1652       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1653       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1654         // Manually compute the final value for AR, checking for overflow.
1655 
1656         // Check whether the backedge-taken count can be losslessly casted to
1657         // the addrec's type. The count is always unsigned.
1658         const SCEV *CastedMaxBECount =
1659             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1660         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1661             CastedMaxBECount, MaxBECount->getType(), Depth);
1662         if (MaxBECount == RecastedMaxBECount) {
1663           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1664           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1665           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1666                                         SCEV::FlagAnyWrap, Depth + 1);
1667           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1668                                                           SCEV::FlagAnyWrap,
1669                                                           Depth + 1),
1670                                                WideTy, Depth + 1);
1671           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1672           const SCEV *WideMaxBECount =
1673             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1674           const SCEV *OperandExtendedAdd =
1675             getAddExpr(WideStart,
1676                        getMulExpr(WideMaxBECount,
1677                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1678                                   SCEV::FlagAnyWrap, Depth + 1),
1679                        SCEV::FlagAnyWrap, Depth + 1);
1680           if (ZAdd == OperandExtendedAdd) {
1681             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1682             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1683             // Return the expression with the addrec on the outside.
1684             return getAddRecExpr(
1685                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1686                                                          Depth + 1),
1687                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1688                 AR->getNoWrapFlags());
1689           }
1690           // Similar to above, only this time treat the step value as signed.
1691           // This covers loops that count down.
1692           OperandExtendedAdd =
1693             getAddExpr(WideStart,
1694                        getMulExpr(WideMaxBECount,
1695                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1696                                   SCEV::FlagAnyWrap, Depth + 1),
1697                        SCEV::FlagAnyWrap, Depth + 1);
1698           if (ZAdd == OperandExtendedAdd) {
1699             // Cache knowledge of AR NW, which is propagated to this AddRec.
1700             // Negative step causes unsigned wrap, but it still can't self-wrap.
1701             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1702             // Return the expression with the addrec on the outside.
1703             return getAddRecExpr(
1704                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1705                                                          Depth + 1),
1706                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1707                 AR->getNoWrapFlags());
1708           }
1709         }
1710       }
1711 
1712       // Normally, in the cases we can prove no-overflow via a
1713       // backedge guarding condition, we can also compute a backedge
1714       // taken count for the loop.  The exceptions are assumptions and
1715       // guards present in the loop -- SCEV is not great at exploiting
1716       // these to compute max backedge taken counts, but can still use
1717       // these to prove lack of overflow.  Use this fact to avoid
1718       // doing extra work that may not pay off.
1719       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1720           !AC.assumptions().empty()) {
1721 
1722         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1723         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1724         if (AR->hasNoUnsignedWrap()) {
1725           // Same as nuw case above - duplicated here to avoid a compile time
1726           // issue.  It's not clear that the order of checks does matter, but
1727           // it's one of two issue possible causes for a change which was
1728           // reverted.  Be conservative for the moment.
1729           return getAddRecExpr(
1730                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1731                                                          Depth + 1),
1732                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1733                 AR->getNoWrapFlags());
1734         }
1735 
1736         // For a negative step, we can extend the operands iff doing so only
1737         // traverses values in the range zext([0,UINT_MAX]).
1738         if (isKnownNegative(Step)) {
1739           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1740                                       getSignedRangeMin(Step));
1741           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1742               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1743             // Cache knowledge of AR NW, which is propagated to this
1744             // AddRec.  Negative step causes unsigned wrap, but it
1745             // still can't self-wrap.
1746             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1747             // Return the expression with the addrec on the outside.
1748             return getAddRecExpr(
1749                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1750                                                          Depth + 1),
1751                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1752                 AR->getNoWrapFlags());
1753           }
1754         }
1755       }
1756 
1757       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1758       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1759       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1760       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1761         const APInt &C = SC->getAPInt();
1762         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1763         if (D != 0) {
1764           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1765           const SCEV *SResidual =
1766               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1767           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1768           return getAddExpr(SZExtD, SZExtR,
1769                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1770                             Depth + 1);
1771         }
1772       }
1773 
1774       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1775         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1776         return getAddRecExpr(
1777             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1778             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1779       }
1780     }
1781 
1782   // zext(A % B) --> zext(A) % zext(B)
1783   {
1784     const SCEV *LHS;
1785     const SCEV *RHS;
1786     if (matchURem(Op, LHS, RHS))
1787       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1788                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1789   }
1790 
1791   // zext(A / B) --> zext(A) / zext(B).
1792   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1793     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1794                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1795 
1796   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1797     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1798     if (SA->hasNoUnsignedWrap()) {
1799       // If the addition does not unsign overflow then we can, by definition,
1800       // commute the zero extension with the addition operation.
1801       SmallVector<const SCEV *, 4> Ops;
1802       for (const auto *Op : SA->operands())
1803         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1804       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1805     }
1806 
1807     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1808     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1809     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1810     //
1811     // Often address arithmetics contain expressions like
1812     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1813     // This transformation is useful while proving that such expressions are
1814     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1815     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1816       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1817       if (D != 0) {
1818         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1819         const SCEV *SResidual =
1820             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1821         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1822         return getAddExpr(SZExtD, SZExtR,
1823                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1824                           Depth + 1);
1825       }
1826     }
1827   }
1828 
1829   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1830     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1831     if (SM->hasNoUnsignedWrap()) {
1832       // If the multiply does not unsign overflow then we can, by definition,
1833       // commute the zero extension with the multiply operation.
1834       SmallVector<const SCEV *, 4> Ops;
1835       for (const auto *Op : SM->operands())
1836         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1837       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1838     }
1839 
1840     // zext(2^K * (trunc X to iN)) to iM ->
1841     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1842     //
1843     // Proof:
1844     //
1845     //     zext(2^K * (trunc X to iN)) to iM
1846     //   = zext((trunc X to iN) << K) to iM
1847     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1848     //     (because shl removes the top K bits)
1849     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1850     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1851     //
1852     if (SM->getNumOperands() == 2)
1853       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1854         if (MulLHS->getAPInt().isPowerOf2())
1855           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1856             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1857                                MulLHS->getAPInt().logBase2();
1858             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1859             return getMulExpr(
1860                 getZeroExtendExpr(MulLHS, Ty),
1861                 getZeroExtendExpr(
1862                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1863                 SCEV::FlagNUW, Depth + 1);
1864           }
1865   }
1866 
1867   // The cast wasn't folded; create an explicit cast node.
1868   // Recompute the insert position, as it may have been invalidated.
1869   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1870   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1871                                                    Op, Ty);
1872   UniqueSCEVs.InsertNode(S, IP);
1873   registerUser(S, Op);
1874   return S;
1875 }
1876 
1877 const SCEV *
1878 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1879   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1880          "This is not an extending conversion!");
1881   assert(isSCEVable(Ty) &&
1882          "This is not a conversion to a SCEVable type!");
1883   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1884   Ty = getEffectiveSCEVType(Ty);
1885 
1886   // Fold if the operand is constant.
1887   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1888     return getConstant(
1889       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1890 
1891   // sext(sext(x)) --> sext(x)
1892   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1893     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1894 
1895   // sext(zext(x)) --> zext(x)
1896   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1897     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1898 
1899   // Before doing any expensive analysis, check to see if we've already
1900   // computed a SCEV for this Op and Ty.
1901   FoldingSetNodeID ID;
1902   ID.AddInteger(scSignExtend);
1903   ID.AddPointer(Op);
1904   ID.AddPointer(Ty);
1905   void *IP = nullptr;
1906   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1907   // Limit recursion depth.
1908   if (Depth > MaxCastDepth) {
1909     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1910                                                      Op, Ty);
1911     UniqueSCEVs.InsertNode(S, IP);
1912     registerUser(S, Op);
1913     return S;
1914   }
1915 
1916   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1917   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1918     // It's possible the bits taken off by the truncate were all sign bits. If
1919     // so, we should be able to simplify this further.
1920     const SCEV *X = ST->getOperand();
1921     ConstantRange CR = getSignedRange(X);
1922     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1923     unsigned NewBits = getTypeSizeInBits(Ty);
1924     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1925             CR.sextOrTrunc(NewBits)))
1926       return getTruncateOrSignExtend(X, Ty, Depth);
1927   }
1928 
1929   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1930     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1931     if (SA->hasNoSignedWrap()) {
1932       // If the addition does not sign overflow then we can, by definition,
1933       // commute the sign extension with the addition operation.
1934       SmallVector<const SCEV *, 4> Ops;
1935       for (const auto *Op : SA->operands())
1936         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1937       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1938     }
1939 
1940     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1941     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1942     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1943     //
1944     // For instance, this will bring two seemingly different expressions:
1945     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1946     //         sext(6 + 20 * %x + 24 * %y)
1947     // to the same form:
1948     //     2 + sext(4 + 20 * %x + 24 * %y)
1949     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1950       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1951       if (D != 0) {
1952         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1953         const SCEV *SResidual =
1954             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1955         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1956         return getAddExpr(SSExtD, SSExtR,
1957                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1958                           Depth + 1);
1959       }
1960     }
1961   }
1962   // If the input value is a chrec scev, and we can prove that the value
1963   // did not overflow the old, smaller, value, we can sign extend all of the
1964   // operands (often constants).  This allows analysis of something like
1965   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1966   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1967     if (AR->isAffine()) {
1968       const SCEV *Start = AR->getStart();
1969       const SCEV *Step = AR->getStepRecurrence(*this);
1970       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1971       const Loop *L = AR->getLoop();
1972 
1973       if (!AR->hasNoSignedWrap()) {
1974         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1975         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1976       }
1977 
1978       // If we have special knowledge that this addrec won't overflow,
1979       // we don't need to do any further analysis.
1980       if (AR->hasNoSignedWrap())
1981         return getAddRecExpr(
1982             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1983             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1984 
1985       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1986       // Note that this serves two purposes: It filters out loops that are
1987       // simply not analyzable, and it covers the case where this code is
1988       // being called from within backedge-taken count analysis, such that
1989       // attempting to ask for the backedge-taken count would likely result
1990       // in infinite recursion. In the later case, the analysis code will
1991       // cope with a conservative value, and it will take care to purge
1992       // that value once it has finished.
1993       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1994       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1995         // Manually compute the final value for AR, checking for
1996         // overflow.
1997 
1998         // Check whether the backedge-taken count can be losslessly casted to
1999         // the addrec's type. The count is always unsigned.
2000         const SCEV *CastedMaxBECount =
2001             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2002         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2003             CastedMaxBECount, MaxBECount->getType(), Depth);
2004         if (MaxBECount == RecastedMaxBECount) {
2005           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2006           // Check whether Start+Step*MaxBECount has no signed overflow.
2007           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2008                                         SCEV::FlagAnyWrap, Depth + 1);
2009           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2010                                                           SCEV::FlagAnyWrap,
2011                                                           Depth + 1),
2012                                                WideTy, Depth + 1);
2013           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2014           const SCEV *WideMaxBECount =
2015             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2016           const SCEV *OperandExtendedAdd =
2017             getAddExpr(WideStart,
2018                        getMulExpr(WideMaxBECount,
2019                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2020                                   SCEV::FlagAnyWrap, Depth + 1),
2021                        SCEV::FlagAnyWrap, Depth + 1);
2022           if (SAdd == OperandExtendedAdd) {
2023             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2024             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2025             // Return the expression with the addrec on the outside.
2026             return getAddRecExpr(
2027                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2028                                                          Depth + 1),
2029                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2030                 AR->getNoWrapFlags());
2031           }
2032           // Similar to above, only this time treat the step value as unsigned.
2033           // This covers loops that count up with an unsigned step.
2034           OperandExtendedAdd =
2035             getAddExpr(WideStart,
2036                        getMulExpr(WideMaxBECount,
2037                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2038                                   SCEV::FlagAnyWrap, Depth + 1),
2039                        SCEV::FlagAnyWrap, Depth + 1);
2040           if (SAdd == OperandExtendedAdd) {
2041             // If AR wraps around then
2042             //
2043             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2044             // => SAdd != OperandExtendedAdd
2045             //
2046             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2047             // (SAdd == OperandExtendedAdd => AR is NW)
2048 
2049             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2050 
2051             // Return the expression with the addrec on the outside.
2052             return getAddRecExpr(
2053                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2054                                                          Depth + 1),
2055                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2056                 AR->getNoWrapFlags());
2057           }
2058         }
2059       }
2060 
2061       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2062       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2063       if (AR->hasNoSignedWrap()) {
2064         // Same as nsw case above - duplicated here to avoid a compile time
2065         // issue.  It's not clear that the order of checks does matter, but
2066         // it's one of two issue possible causes for a change which was
2067         // reverted.  Be conservative for the moment.
2068         return getAddRecExpr(
2069             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2070             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2071       }
2072 
2073       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2074       // if D + (C - D + Step * n) could be proven to not signed wrap
2075       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2076       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2077         const APInt &C = SC->getAPInt();
2078         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2079         if (D != 0) {
2080           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2081           const SCEV *SResidual =
2082               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2083           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2084           return getAddExpr(SSExtD, SSExtR,
2085                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2086                             Depth + 1);
2087         }
2088       }
2089 
2090       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2091         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2092         return getAddRecExpr(
2093             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2094             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2095       }
2096     }
2097 
2098   // If the input value is provably positive and we could not simplify
2099   // away the sext build a zext instead.
2100   if (isKnownNonNegative(Op))
2101     return getZeroExtendExpr(Op, Ty, Depth + 1);
2102 
2103   // The cast wasn't folded; create an explicit cast node.
2104   // Recompute the insert position, as it may have been invalidated.
2105   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2106   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2107                                                    Op, Ty);
2108   UniqueSCEVs.InsertNode(S, IP);
2109   registerUser(S, { Op });
2110   return S;
2111 }
2112 
2113 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2114 /// unspecified bits out to the given type.
2115 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2116                                               Type *Ty) {
2117   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2118          "This is not an extending conversion!");
2119   assert(isSCEVable(Ty) &&
2120          "This is not a conversion to a SCEVable type!");
2121   Ty = getEffectiveSCEVType(Ty);
2122 
2123   // Sign-extend negative constants.
2124   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2125     if (SC->getAPInt().isNegative())
2126       return getSignExtendExpr(Op, Ty);
2127 
2128   // Peel off a truncate cast.
2129   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2130     const SCEV *NewOp = T->getOperand();
2131     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2132       return getAnyExtendExpr(NewOp, Ty);
2133     return getTruncateOrNoop(NewOp, Ty);
2134   }
2135 
2136   // Next try a zext cast. If the cast is folded, use it.
2137   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2138   if (!isa<SCEVZeroExtendExpr>(ZExt))
2139     return ZExt;
2140 
2141   // Next try a sext cast. If the cast is folded, use it.
2142   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2143   if (!isa<SCEVSignExtendExpr>(SExt))
2144     return SExt;
2145 
2146   // Force the cast to be folded into the operands of an addrec.
2147   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2148     SmallVector<const SCEV *, 4> Ops;
2149     for (const SCEV *Op : AR->operands())
2150       Ops.push_back(getAnyExtendExpr(Op, Ty));
2151     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2152   }
2153 
2154   // If the expression is obviously signed, use the sext cast value.
2155   if (isa<SCEVSMaxExpr>(Op))
2156     return SExt;
2157 
2158   // Absent any other information, use the zext cast value.
2159   return ZExt;
2160 }
2161 
2162 /// Process the given Ops list, which is a list of operands to be added under
2163 /// the given scale, update the given map. This is a helper function for
2164 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2165 /// that would form an add expression like this:
2166 ///
2167 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2168 ///
2169 /// where A and B are constants, update the map with these values:
2170 ///
2171 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2172 ///
2173 /// and add 13 + A*B*29 to AccumulatedConstant.
2174 /// This will allow getAddRecExpr to produce this:
2175 ///
2176 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2177 ///
2178 /// This form often exposes folding opportunities that are hidden in
2179 /// the original operand list.
2180 ///
2181 /// Return true iff it appears that any interesting folding opportunities
2182 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2183 /// the common case where no interesting opportunities are present, and
2184 /// is also used as a check to avoid infinite recursion.
2185 static bool
2186 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2187                              SmallVectorImpl<const SCEV *> &NewOps,
2188                              APInt &AccumulatedConstant,
2189                              const SCEV *const *Ops, size_t NumOperands,
2190                              const APInt &Scale,
2191                              ScalarEvolution &SE) {
2192   bool Interesting = false;
2193 
2194   // Iterate over the add operands. They are sorted, with constants first.
2195   unsigned i = 0;
2196   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2197     ++i;
2198     // Pull a buried constant out to the outside.
2199     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2200       Interesting = true;
2201     AccumulatedConstant += Scale * C->getAPInt();
2202   }
2203 
2204   // Next comes everything else. We're especially interested in multiplies
2205   // here, but they're in the middle, so just visit the rest with one loop.
2206   for (; i != NumOperands; ++i) {
2207     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2208     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2209       APInt NewScale =
2210           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2211       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2212         // A multiplication of a constant with another add; recurse.
2213         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2214         Interesting |=
2215           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2216                                        Add->op_begin(), Add->getNumOperands(),
2217                                        NewScale, SE);
2218       } else {
2219         // A multiplication of a constant with some other value. Update
2220         // the map.
2221         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2222         const SCEV *Key = SE.getMulExpr(MulOps);
2223         auto Pair = M.insert({Key, NewScale});
2224         if (Pair.second) {
2225           NewOps.push_back(Pair.first->first);
2226         } else {
2227           Pair.first->second += NewScale;
2228           // The map already had an entry for this value, which may indicate
2229           // a folding opportunity.
2230           Interesting = true;
2231         }
2232       }
2233     } else {
2234       // An ordinary operand. Update the map.
2235       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2236           M.insert({Ops[i], Scale});
2237       if (Pair.second) {
2238         NewOps.push_back(Pair.first->first);
2239       } else {
2240         Pair.first->second += Scale;
2241         // The map already had an entry for this value, which may indicate
2242         // a folding opportunity.
2243         Interesting = true;
2244       }
2245     }
2246   }
2247 
2248   return Interesting;
2249 }
2250 
2251 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2252                                       const SCEV *LHS, const SCEV *RHS) {
2253   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2254                                             SCEV::NoWrapFlags, unsigned);
2255   switch (BinOp) {
2256   default:
2257     llvm_unreachable("Unsupported binary op");
2258   case Instruction::Add:
2259     Operation = &ScalarEvolution::getAddExpr;
2260     break;
2261   case Instruction::Sub:
2262     Operation = &ScalarEvolution::getMinusSCEV;
2263     break;
2264   case Instruction::Mul:
2265     Operation = &ScalarEvolution::getMulExpr;
2266     break;
2267   }
2268 
2269   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2270       Signed ? &ScalarEvolution::getSignExtendExpr
2271              : &ScalarEvolution::getZeroExtendExpr;
2272 
2273   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2274   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2275   auto *WideTy =
2276       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2277 
2278   const SCEV *A = (this->*Extension)(
2279       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2280   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2281                                      (this->*Extension)(RHS, WideTy, 0),
2282                                      SCEV::FlagAnyWrap, 0);
2283   return A == B;
2284 }
2285 
2286 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2287 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2288     const OverflowingBinaryOperator *OBO) {
2289   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2290 
2291   if (OBO->hasNoUnsignedWrap())
2292     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2293   if (OBO->hasNoSignedWrap())
2294     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2295 
2296   bool Deduced = false;
2297 
2298   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2299     return {Flags, Deduced};
2300 
2301   if (OBO->getOpcode() != Instruction::Add &&
2302       OBO->getOpcode() != Instruction::Sub &&
2303       OBO->getOpcode() != Instruction::Mul)
2304     return {Flags, Deduced};
2305 
2306   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2307   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2308 
2309   if (!OBO->hasNoUnsignedWrap() &&
2310       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2311                       /* Signed */ false, LHS, RHS)) {
2312     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2313     Deduced = true;
2314   }
2315 
2316   if (!OBO->hasNoSignedWrap() &&
2317       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2318                       /* Signed */ true, LHS, RHS)) {
2319     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2320     Deduced = true;
2321   }
2322 
2323   return {Flags, Deduced};
2324 }
2325 
2326 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2327 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2328 // can't-overflow flags for the operation if possible.
2329 static SCEV::NoWrapFlags
2330 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2331                       const ArrayRef<const SCEV *> Ops,
2332                       SCEV::NoWrapFlags Flags) {
2333   using namespace std::placeholders;
2334 
2335   using OBO = OverflowingBinaryOperator;
2336 
2337   bool CanAnalyze =
2338       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2339   (void)CanAnalyze;
2340   assert(CanAnalyze && "don't call from other places!");
2341 
2342   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2343   SCEV::NoWrapFlags SignOrUnsignWrap =
2344       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2345 
2346   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2347   auto IsKnownNonNegative = [&](const SCEV *S) {
2348     return SE->isKnownNonNegative(S);
2349   };
2350 
2351   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2352     Flags =
2353         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2354 
2355   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2356 
2357   if (SignOrUnsignWrap != SignOrUnsignMask &&
2358       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2359       isa<SCEVConstant>(Ops[0])) {
2360 
2361     auto Opcode = [&] {
2362       switch (Type) {
2363       case scAddExpr:
2364         return Instruction::Add;
2365       case scMulExpr:
2366         return Instruction::Mul;
2367       default:
2368         llvm_unreachable("Unexpected SCEV op.");
2369       }
2370     }();
2371 
2372     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2373 
2374     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2375     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2376       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2377           Opcode, C, OBO::NoSignedWrap);
2378       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2379         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2380     }
2381 
2382     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2383     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2384       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2385           Opcode, C, OBO::NoUnsignedWrap);
2386       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2387         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2388     }
2389   }
2390 
2391   // <0,+,nonnegative><nw> is also nuw
2392   // TODO: Add corresponding nsw case
2393   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2394       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2395       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2396     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2397 
2398   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2399   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2400       Ops.size() == 2) {
2401     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2402       if (UDiv->getOperand(1) == Ops[1])
2403         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2404     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2405       if (UDiv->getOperand(1) == Ops[0])
2406         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2407   }
2408 
2409   return Flags;
2410 }
2411 
2412 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2413   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2414 }
2415 
2416 /// Get a canonical add expression, or something simpler if possible.
2417 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2418                                         SCEV::NoWrapFlags OrigFlags,
2419                                         unsigned Depth) {
2420   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2421          "only nuw or nsw allowed");
2422   assert(!Ops.empty() && "Cannot get empty add!");
2423   if (Ops.size() == 1) return Ops[0];
2424 #ifndef NDEBUG
2425   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2426   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2427     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2428            "SCEVAddExpr operand types don't match!");
2429   unsigned NumPtrs = count_if(
2430       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2431   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2432 #endif
2433 
2434   // Sort by complexity, this groups all similar expression types together.
2435   GroupByComplexity(Ops, &LI, DT);
2436 
2437   // If there are any constants, fold them together.
2438   unsigned Idx = 0;
2439   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2440     ++Idx;
2441     assert(Idx < Ops.size());
2442     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2443       // We found two constants, fold them together!
2444       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2445       if (Ops.size() == 2) return Ops[0];
2446       Ops.erase(Ops.begin()+1);  // Erase the folded element
2447       LHSC = cast<SCEVConstant>(Ops[0]);
2448     }
2449 
2450     // If we are left with a constant zero being added, strip it off.
2451     if (LHSC->getValue()->isZero()) {
2452       Ops.erase(Ops.begin());
2453       --Idx;
2454     }
2455 
2456     if (Ops.size() == 1) return Ops[0];
2457   }
2458 
2459   // Delay expensive flag strengthening until necessary.
2460   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2461     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2462   };
2463 
2464   // Limit recursion calls depth.
2465   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2466     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2467 
2468   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2469     // Don't strengthen flags if we have no new information.
2470     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2471     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2472       Add->setNoWrapFlags(ComputeFlags(Ops));
2473     return S;
2474   }
2475 
2476   // Okay, check to see if the same value occurs in the operand list more than
2477   // once.  If so, merge them together into an multiply expression.  Since we
2478   // sorted the list, these values are required to be adjacent.
2479   Type *Ty = Ops[0]->getType();
2480   bool FoundMatch = false;
2481   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2482     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2483       // Scan ahead to count how many equal operands there are.
2484       unsigned Count = 2;
2485       while (i+Count != e && Ops[i+Count] == Ops[i])
2486         ++Count;
2487       // Merge the values into a multiply.
2488       const SCEV *Scale = getConstant(Ty, Count);
2489       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2490       if (Ops.size() == Count)
2491         return Mul;
2492       Ops[i] = Mul;
2493       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2494       --i; e -= Count - 1;
2495       FoundMatch = true;
2496     }
2497   if (FoundMatch)
2498     return getAddExpr(Ops, OrigFlags, Depth + 1);
2499 
2500   // Check for truncates. If all the operands are truncated from the same
2501   // type, see if factoring out the truncate would permit the result to be
2502   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2503   // if the contents of the resulting outer trunc fold to something simple.
2504   auto FindTruncSrcType = [&]() -> Type * {
2505     // We're ultimately looking to fold an addrec of truncs and muls of only
2506     // constants and truncs, so if we find any other types of SCEV
2507     // as operands of the addrec then we bail and return nullptr here.
2508     // Otherwise, we return the type of the operand of a trunc that we find.
2509     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2510       return T->getOperand()->getType();
2511     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2512       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2513       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2514         return T->getOperand()->getType();
2515     }
2516     return nullptr;
2517   };
2518   if (auto *SrcType = FindTruncSrcType()) {
2519     SmallVector<const SCEV *, 8> LargeOps;
2520     bool Ok = true;
2521     // Check all the operands to see if they can be represented in the
2522     // source type of the truncate.
2523     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2524       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2525         if (T->getOperand()->getType() != SrcType) {
2526           Ok = false;
2527           break;
2528         }
2529         LargeOps.push_back(T->getOperand());
2530       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2531         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2532       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2533         SmallVector<const SCEV *, 8> LargeMulOps;
2534         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2535           if (const SCEVTruncateExpr *T =
2536                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2537             if (T->getOperand()->getType() != SrcType) {
2538               Ok = false;
2539               break;
2540             }
2541             LargeMulOps.push_back(T->getOperand());
2542           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2543             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2544           } else {
2545             Ok = false;
2546             break;
2547           }
2548         }
2549         if (Ok)
2550           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2551       } else {
2552         Ok = false;
2553         break;
2554       }
2555     }
2556     if (Ok) {
2557       // Evaluate the expression in the larger type.
2558       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2559       // If it folds to something simple, use it. Otherwise, don't.
2560       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2561         return getTruncateExpr(Fold, Ty);
2562     }
2563   }
2564 
2565   if (Ops.size() == 2) {
2566     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2567     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2568     // C1).
2569     const SCEV *A = Ops[0];
2570     const SCEV *B = Ops[1];
2571     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2572     auto *C = dyn_cast<SCEVConstant>(A);
2573     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2574       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2575       auto C2 = C->getAPInt();
2576       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2577 
2578       APInt ConstAdd = C1 + C2;
2579       auto AddFlags = AddExpr->getNoWrapFlags();
2580       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2581       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2582           ConstAdd.ule(C1)) {
2583         PreservedFlags =
2584             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2585       }
2586 
2587       // Adding a constant with the same sign and small magnitude is NSW, if the
2588       // original AddExpr was NSW.
2589       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2590           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2591           ConstAdd.abs().ule(C1.abs())) {
2592         PreservedFlags =
2593             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2594       }
2595 
2596       if (PreservedFlags != SCEV::FlagAnyWrap) {
2597         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2598         NewOps[0] = getConstant(ConstAdd);
2599         return getAddExpr(NewOps, PreservedFlags);
2600       }
2601     }
2602   }
2603 
2604   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2605   if (Ops.size() == 2) {
2606     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2607     if (Mul && Mul->getNumOperands() == 2 &&
2608         Mul->getOperand(0)->isAllOnesValue()) {
2609       const SCEV *X;
2610       const SCEV *Y;
2611       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2612         return getMulExpr(Y, getUDivExpr(X, Y));
2613       }
2614     }
2615   }
2616 
2617   // Skip past any other cast SCEVs.
2618   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2619     ++Idx;
2620 
2621   // If there are add operands they would be next.
2622   if (Idx < Ops.size()) {
2623     bool DeletedAdd = false;
2624     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2625     // common NUW flag for expression after inlining. Other flags cannot be
2626     // preserved, because they may depend on the original order of operations.
2627     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2628     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2629       if (Ops.size() > AddOpsInlineThreshold ||
2630           Add->getNumOperands() > AddOpsInlineThreshold)
2631         break;
2632       // If we have an add, expand the add operands onto the end of the operands
2633       // list.
2634       Ops.erase(Ops.begin()+Idx);
2635       Ops.append(Add->op_begin(), Add->op_end());
2636       DeletedAdd = true;
2637       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2638     }
2639 
2640     // If we deleted at least one add, we added operands to the end of the list,
2641     // and they are not necessarily sorted.  Recurse to resort and resimplify
2642     // any operands we just acquired.
2643     if (DeletedAdd)
2644       return getAddExpr(Ops, CommonFlags, Depth + 1);
2645   }
2646 
2647   // Skip over the add expression until we get to a multiply.
2648   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2649     ++Idx;
2650 
2651   // Check to see if there are any folding opportunities present with
2652   // operands multiplied by constant values.
2653   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2654     uint64_t BitWidth = getTypeSizeInBits(Ty);
2655     DenseMap<const SCEV *, APInt> M;
2656     SmallVector<const SCEV *, 8> NewOps;
2657     APInt AccumulatedConstant(BitWidth, 0);
2658     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2659                                      Ops.data(), Ops.size(),
2660                                      APInt(BitWidth, 1), *this)) {
2661       struct APIntCompare {
2662         bool operator()(const APInt &LHS, const APInt &RHS) const {
2663           return LHS.ult(RHS);
2664         }
2665       };
2666 
2667       // Some interesting folding opportunity is present, so its worthwhile to
2668       // re-generate the operands list. Group the operands by constant scale,
2669       // to avoid multiplying by the same constant scale multiple times.
2670       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2671       for (const SCEV *NewOp : NewOps)
2672         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2673       // Re-generate the operands list.
2674       Ops.clear();
2675       if (AccumulatedConstant != 0)
2676         Ops.push_back(getConstant(AccumulatedConstant));
2677       for (auto &MulOp : MulOpLists) {
2678         if (MulOp.first == 1) {
2679           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2680         } else if (MulOp.first != 0) {
2681           Ops.push_back(getMulExpr(
2682               getConstant(MulOp.first),
2683               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2684               SCEV::FlagAnyWrap, Depth + 1));
2685         }
2686       }
2687       if (Ops.empty())
2688         return getZero(Ty);
2689       if (Ops.size() == 1)
2690         return Ops[0];
2691       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2692     }
2693   }
2694 
2695   // If we are adding something to a multiply expression, make sure the
2696   // something is not already an operand of the multiply.  If so, merge it into
2697   // the multiply.
2698   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2699     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2700     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2701       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2702       if (isa<SCEVConstant>(MulOpSCEV))
2703         continue;
2704       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2705         if (MulOpSCEV == Ops[AddOp]) {
2706           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2707           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2708           if (Mul->getNumOperands() != 2) {
2709             // If the multiply has more than two operands, we must get the
2710             // Y*Z term.
2711             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2712                                                 Mul->op_begin()+MulOp);
2713             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2714             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2715           }
2716           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2717           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2718           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2719                                             SCEV::FlagAnyWrap, Depth + 1);
2720           if (Ops.size() == 2) return OuterMul;
2721           if (AddOp < Idx) {
2722             Ops.erase(Ops.begin()+AddOp);
2723             Ops.erase(Ops.begin()+Idx-1);
2724           } else {
2725             Ops.erase(Ops.begin()+Idx);
2726             Ops.erase(Ops.begin()+AddOp-1);
2727           }
2728           Ops.push_back(OuterMul);
2729           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2730         }
2731 
2732       // Check this multiply against other multiplies being added together.
2733       for (unsigned OtherMulIdx = Idx+1;
2734            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2735            ++OtherMulIdx) {
2736         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2737         // If MulOp occurs in OtherMul, we can fold the two multiplies
2738         // together.
2739         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2740              OMulOp != e; ++OMulOp)
2741           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2742             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2743             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2744             if (Mul->getNumOperands() != 2) {
2745               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2746                                                   Mul->op_begin()+MulOp);
2747               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2748               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2749             }
2750             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2751             if (OtherMul->getNumOperands() != 2) {
2752               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2753                                                   OtherMul->op_begin()+OMulOp);
2754               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2755               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2756             }
2757             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2758             const SCEV *InnerMulSum =
2759                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2760             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2761                                               SCEV::FlagAnyWrap, Depth + 1);
2762             if (Ops.size() == 2) return OuterMul;
2763             Ops.erase(Ops.begin()+Idx);
2764             Ops.erase(Ops.begin()+OtherMulIdx-1);
2765             Ops.push_back(OuterMul);
2766             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2767           }
2768       }
2769     }
2770   }
2771 
2772   // If there are any add recurrences in the operands list, see if any other
2773   // added values are loop invariant.  If so, we can fold them into the
2774   // recurrence.
2775   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2776     ++Idx;
2777 
2778   // Scan over all recurrences, trying to fold loop invariants into them.
2779   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2780     // Scan all of the other operands to this add and add them to the vector if
2781     // they are loop invariant w.r.t. the recurrence.
2782     SmallVector<const SCEV *, 8> LIOps;
2783     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2784     const Loop *AddRecLoop = AddRec->getLoop();
2785     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2786       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2787         LIOps.push_back(Ops[i]);
2788         Ops.erase(Ops.begin()+i);
2789         --i; --e;
2790       }
2791 
2792     // If we found some loop invariants, fold them into the recurrence.
2793     if (!LIOps.empty()) {
2794       // Compute nowrap flags for the addition of the loop-invariant ops and
2795       // the addrec. Temporarily push it as an operand for that purpose. These
2796       // flags are valid in the scope of the addrec only.
2797       LIOps.push_back(AddRec);
2798       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2799       LIOps.pop_back();
2800 
2801       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2802       LIOps.push_back(AddRec->getStart());
2803 
2804       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2805 
2806       // It is not in general safe to propagate flags valid on an add within
2807       // the addrec scope to one outside it.  We must prove that the inner
2808       // scope is guaranteed to execute if the outer one does to be able to
2809       // safely propagate.  We know the program is undefined if poison is
2810       // produced on the inner scoped addrec.  We also know that *for this use*
2811       // the outer scoped add can't overflow (because of the flags we just
2812       // computed for the inner scoped add) without the program being undefined.
2813       // Proving that entry to the outer scope neccesitates entry to the inner
2814       // scope, thus proves the program undefined if the flags would be violated
2815       // in the outer scope.
2816       SCEV::NoWrapFlags AddFlags = Flags;
2817       if (AddFlags != SCEV::FlagAnyWrap) {
2818         auto *DefI = getDefiningScopeBound(LIOps);
2819         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2820         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2821           AddFlags = SCEV::FlagAnyWrap;
2822       }
2823       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2824 
2825       // Build the new addrec. Propagate the NUW and NSW flags if both the
2826       // outer add and the inner addrec are guaranteed to have no overflow.
2827       // Always propagate NW.
2828       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2829       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2830 
2831       // If all of the other operands were loop invariant, we are done.
2832       if (Ops.size() == 1) return NewRec;
2833 
2834       // Otherwise, add the folded AddRec by the non-invariant parts.
2835       for (unsigned i = 0;; ++i)
2836         if (Ops[i] == AddRec) {
2837           Ops[i] = NewRec;
2838           break;
2839         }
2840       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2841     }
2842 
2843     // Okay, if there weren't any loop invariants to be folded, check to see if
2844     // there are multiple AddRec's with the same loop induction variable being
2845     // added together.  If so, we can fold them.
2846     for (unsigned OtherIdx = Idx+1;
2847          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2848          ++OtherIdx) {
2849       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2850       // so that the 1st found AddRecExpr is dominated by all others.
2851       assert(DT.dominates(
2852            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2853            AddRec->getLoop()->getHeader()) &&
2854         "AddRecExprs are not sorted in reverse dominance order?");
2855       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2856         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2857         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2858         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2859              ++OtherIdx) {
2860           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2861           if (OtherAddRec->getLoop() == AddRecLoop) {
2862             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2863                  i != e; ++i) {
2864               if (i >= AddRecOps.size()) {
2865                 AddRecOps.append(OtherAddRec->op_begin()+i,
2866                                  OtherAddRec->op_end());
2867                 break;
2868               }
2869               SmallVector<const SCEV *, 2> TwoOps = {
2870                   AddRecOps[i], OtherAddRec->getOperand(i)};
2871               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2872             }
2873             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2874           }
2875         }
2876         // Step size has changed, so we cannot guarantee no self-wraparound.
2877         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2878         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2879       }
2880     }
2881 
2882     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2883     // next one.
2884   }
2885 
2886   // Okay, it looks like we really DO need an add expr.  Check to see if we
2887   // already have one, otherwise create a new one.
2888   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2889 }
2890 
2891 const SCEV *
2892 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2893                                     SCEV::NoWrapFlags Flags) {
2894   FoldingSetNodeID ID;
2895   ID.AddInteger(scAddExpr);
2896   for (const SCEV *Op : Ops)
2897     ID.AddPointer(Op);
2898   void *IP = nullptr;
2899   SCEVAddExpr *S =
2900       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2901   if (!S) {
2902     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2903     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2904     S = new (SCEVAllocator)
2905         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2906     UniqueSCEVs.InsertNode(S, IP);
2907     registerUser(S, Ops);
2908   }
2909   S->setNoWrapFlags(Flags);
2910   return S;
2911 }
2912 
2913 const SCEV *
2914 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2915                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2916   FoldingSetNodeID ID;
2917   ID.AddInteger(scAddRecExpr);
2918   for (const SCEV *Op : Ops)
2919     ID.AddPointer(Op);
2920   ID.AddPointer(L);
2921   void *IP = nullptr;
2922   SCEVAddRecExpr *S =
2923       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2924   if (!S) {
2925     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2926     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2927     S = new (SCEVAllocator)
2928         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2929     UniqueSCEVs.InsertNode(S, IP);
2930     LoopUsers[L].push_back(S);
2931     registerUser(S, Ops);
2932   }
2933   setNoWrapFlags(S, Flags);
2934   return S;
2935 }
2936 
2937 const SCEV *
2938 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2939                                     SCEV::NoWrapFlags Flags) {
2940   FoldingSetNodeID ID;
2941   ID.AddInteger(scMulExpr);
2942   for (const SCEV *Op : Ops)
2943     ID.AddPointer(Op);
2944   void *IP = nullptr;
2945   SCEVMulExpr *S =
2946     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2947   if (!S) {
2948     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2949     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2950     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2951                                         O, Ops.size());
2952     UniqueSCEVs.InsertNode(S, IP);
2953     registerUser(S, Ops);
2954   }
2955   S->setNoWrapFlags(Flags);
2956   return S;
2957 }
2958 
2959 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2960   uint64_t k = i*j;
2961   if (j > 1 && k / j != i) Overflow = true;
2962   return k;
2963 }
2964 
2965 /// Compute the result of "n choose k", the binomial coefficient.  If an
2966 /// intermediate computation overflows, Overflow will be set and the return will
2967 /// be garbage. Overflow is not cleared on absence of overflow.
2968 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2969   // We use the multiplicative formula:
2970   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2971   // At each iteration, we take the n-th term of the numeral and divide by the
2972   // (k-n)th term of the denominator.  This division will always produce an
2973   // integral result, and helps reduce the chance of overflow in the
2974   // intermediate computations. However, we can still overflow even when the
2975   // final result would fit.
2976 
2977   if (n == 0 || n == k) return 1;
2978   if (k > n) return 0;
2979 
2980   if (k > n/2)
2981     k = n-k;
2982 
2983   uint64_t r = 1;
2984   for (uint64_t i = 1; i <= k; ++i) {
2985     r = umul_ov(r, n-(i-1), Overflow);
2986     r /= i;
2987   }
2988   return r;
2989 }
2990 
2991 /// Determine if any of the operands in this SCEV are a constant or if
2992 /// any of the add or multiply expressions in this SCEV contain a constant.
2993 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2994   struct FindConstantInAddMulChain {
2995     bool FoundConstant = false;
2996 
2997     bool follow(const SCEV *S) {
2998       FoundConstant |= isa<SCEVConstant>(S);
2999       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3000     }
3001 
3002     bool isDone() const {
3003       return FoundConstant;
3004     }
3005   };
3006 
3007   FindConstantInAddMulChain F;
3008   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3009   ST.visitAll(StartExpr);
3010   return F.FoundConstant;
3011 }
3012 
3013 /// Get a canonical multiply expression, or something simpler if possible.
3014 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3015                                         SCEV::NoWrapFlags OrigFlags,
3016                                         unsigned Depth) {
3017   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3018          "only nuw or nsw allowed");
3019   assert(!Ops.empty() && "Cannot get empty mul!");
3020   if (Ops.size() == 1) return Ops[0];
3021 #ifndef NDEBUG
3022   Type *ETy = Ops[0]->getType();
3023   assert(!ETy->isPointerTy());
3024   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3025     assert(Ops[i]->getType() == ETy &&
3026            "SCEVMulExpr operand types don't match!");
3027 #endif
3028 
3029   // Sort by complexity, this groups all similar expression types together.
3030   GroupByComplexity(Ops, &LI, DT);
3031 
3032   // If there are any constants, fold them together.
3033   unsigned Idx = 0;
3034   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3035     ++Idx;
3036     assert(Idx < Ops.size());
3037     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3038       // We found two constants, fold them together!
3039       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3040       if (Ops.size() == 2) return Ops[0];
3041       Ops.erase(Ops.begin()+1);  // Erase the folded element
3042       LHSC = cast<SCEVConstant>(Ops[0]);
3043     }
3044 
3045     // If we have a multiply of zero, it will always be zero.
3046     if (LHSC->getValue()->isZero())
3047       return LHSC;
3048 
3049     // If we are left with a constant one being multiplied, strip it off.
3050     if (LHSC->getValue()->isOne()) {
3051       Ops.erase(Ops.begin());
3052       --Idx;
3053     }
3054 
3055     if (Ops.size() == 1)
3056       return Ops[0];
3057   }
3058 
3059   // Delay expensive flag strengthening until necessary.
3060   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3061     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3062   };
3063 
3064   // Limit recursion calls depth.
3065   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3066     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3067 
3068   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3069     // Don't strengthen flags if we have no new information.
3070     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3071     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3072       Mul->setNoWrapFlags(ComputeFlags(Ops));
3073     return S;
3074   }
3075 
3076   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3077     if (Ops.size() == 2) {
3078       // C1*(C2+V) -> C1*C2 + C1*V
3079       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3080         // If any of Add's ops are Adds or Muls with a constant, apply this
3081         // transformation as well.
3082         //
3083         // TODO: There are some cases where this transformation is not
3084         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3085         // this transformation should be narrowed down.
3086         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
3087           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
3088                                        SCEV::FlagAnyWrap, Depth + 1),
3089                             getMulExpr(LHSC, Add->getOperand(1),
3090                                        SCEV::FlagAnyWrap, Depth + 1),
3091                             SCEV::FlagAnyWrap, Depth + 1);
3092 
3093       if (Ops[0]->isAllOnesValue()) {
3094         // If we have a mul by -1 of an add, try distributing the -1 among the
3095         // add operands.
3096         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3097           SmallVector<const SCEV *, 4> NewOps;
3098           bool AnyFolded = false;
3099           for (const SCEV *AddOp : Add->operands()) {
3100             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3101                                          Depth + 1);
3102             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3103             NewOps.push_back(Mul);
3104           }
3105           if (AnyFolded)
3106             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3107         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3108           // Negation preserves a recurrence's no self-wrap property.
3109           SmallVector<const SCEV *, 4> Operands;
3110           for (const SCEV *AddRecOp : AddRec->operands())
3111             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3112                                           Depth + 1));
3113 
3114           return getAddRecExpr(Operands, AddRec->getLoop(),
3115                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3116         }
3117       }
3118     }
3119   }
3120 
3121   // Skip over the add expression until we get to a multiply.
3122   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3123     ++Idx;
3124 
3125   // If there are mul operands inline them all into this expression.
3126   if (Idx < Ops.size()) {
3127     bool DeletedMul = false;
3128     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3129       if (Ops.size() > MulOpsInlineThreshold)
3130         break;
3131       // If we have an mul, expand the mul operands onto the end of the
3132       // operands list.
3133       Ops.erase(Ops.begin()+Idx);
3134       Ops.append(Mul->op_begin(), Mul->op_end());
3135       DeletedMul = true;
3136     }
3137 
3138     // If we deleted at least one mul, we added operands to the end of the
3139     // list, and they are not necessarily sorted.  Recurse to resort and
3140     // resimplify any operands we just acquired.
3141     if (DeletedMul)
3142       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3143   }
3144 
3145   // If there are any add recurrences in the operands list, see if any other
3146   // added values are loop invariant.  If so, we can fold them into the
3147   // recurrence.
3148   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3149     ++Idx;
3150 
3151   // Scan over all recurrences, trying to fold loop invariants into them.
3152   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3153     // Scan all of the other operands to this mul and add them to the vector
3154     // if they are loop invariant w.r.t. the recurrence.
3155     SmallVector<const SCEV *, 8> LIOps;
3156     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3157     const Loop *AddRecLoop = AddRec->getLoop();
3158     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3159       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3160         LIOps.push_back(Ops[i]);
3161         Ops.erase(Ops.begin()+i);
3162         --i; --e;
3163       }
3164 
3165     // If we found some loop invariants, fold them into the recurrence.
3166     if (!LIOps.empty()) {
3167       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3168       SmallVector<const SCEV *, 4> NewOps;
3169       NewOps.reserve(AddRec->getNumOperands());
3170       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3171       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3172         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3173                                     SCEV::FlagAnyWrap, Depth + 1));
3174 
3175       // Build the new addrec. Propagate the NUW and NSW flags if both the
3176       // outer mul and the inner addrec are guaranteed to have no overflow.
3177       //
3178       // No self-wrap cannot be guaranteed after changing the step size, but
3179       // will be inferred if either NUW or NSW is true.
3180       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3181       const SCEV *NewRec = getAddRecExpr(
3182           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3183 
3184       // If all of the other operands were loop invariant, we are done.
3185       if (Ops.size() == 1) return NewRec;
3186 
3187       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3188       for (unsigned i = 0;; ++i)
3189         if (Ops[i] == AddRec) {
3190           Ops[i] = NewRec;
3191           break;
3192         }
3193       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3194     }
3195 
3196     // Okay, if there weren't any loop invariants to be folded, check to see
3197     // if there are multiple AddRec's with the same loop induction variable
3198     // being multiplied together.  If so, we can fold them.
3199 
3200     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3201     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3202     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3203     //   ]]],+,...up to x=2n}.
3204     // Note that the arguments to choose() are always integers with values
3205     // known at compile time, never SCEV objects.
3206     //
3207     // The implementation avoids pointless extra computations when the two
3208     // addrec's are of different length (mathematically, it's equivalent to
3209     // an infinite stream of zeros on the right).
3210     bool OpsModified = false;
3211     for (unsigned OtherIdx = Idx+1;
3212          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3213          ++OtherIdx) {
3214       const SCEVAddRecExpr *OtherAddRec =
3215         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3216       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3217         continue;
3218 
3219       // Limit max number of arguments to avoid creation of unreasonably big
3220       // SCEVAddRecs with very complex operands.
3221       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3222           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3223         continue;
3224 
3225       bool Overflow = false;
3226       Type *Ty = AddRec->getType();
3227       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3228       SmallVector<const SCEV*, 7> AddRecOps;
3229       for (int x = 0, xe = AddRec->getNumOperands() +
3230              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3231         SmallVector <const SCEV *, 7> SumOps;
3232         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3233           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3234           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3235                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3236                z < ze && !Overflow; ++z) {
3237             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3238             uint64_t Coeff;
3239             if (LargerThan64Bits)
3240               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3241             else
3242               Coeff = Coeff1*Coeff2;
3243             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3244             const SCEV *Term1 = AddRec->getOperand(y-z);
3245             const SCEV *Term2 = OtherAddRec->getOperand(z);
3246             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3247                                         SCEV::FlagAnyWrap, Depth + 1));
3248           }
3249         }
3250         if (SumOps.empty())
3251           SumOps.push_back(getZero(Ty));
3252         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3253       }
3254       if (!Overflow) {
3255         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3256                                               SCEV::FlagAnyWrap);
3257         if (Ops.size() == 2) return NewAddRec;
3258         Ops[Idx] = NewAddRec;
3259         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3260         OpsModified = true;
3261         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3262         if (!AddRec)
3263           break;
3264       }
3265     }
3266     if (OpsModified)
3267       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3268 
3269     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3270     // next one.
3271   }
3272 
3273   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3274   // already have one, otherwise create a new one.
3275   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3276 }
3277 
3278 /// Represents an unsigned remainder expression based on unsigned division.
3279 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3280                                          const SCEV *RHS) {
3281   assert(getEffectiveSCEVType(LHS->getType()) ==
3282          getEffectiveSCEVType(RHS->getType()) &&
3283          "SCEVURemExpr operand types don't match!");
3284 
3285   // Short-circuit easy cases
3286   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3287     // If constant is one, the result is trivial
3288     if (RHSC->getValue()->isOne())
3289       return getZero(LHS->getType()); // X urem 1 --> 0
3290 
3291     // If constant is a power of two, fold into a zext(trunc(LHS)).
3292     if (RHSC->getAPInt().isPowerOf2()) {
3293       Type *FullTy = LHS->getType();
3294       Type *TruncTy =
3295           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3296       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3297     }
3298   }
3299 
3300   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3301   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3302   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3303   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3304 }
3305 
3306 /// Get a canonical unsigned division expression, or something simpler if
3307 /// possible.
3308 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3309                                          const SCEV *RHS) {
3310   assert(!LHS->getType()->isPointerTy() &&
3311          "SCEVUDivExpr operand can't be pointer!");
3312   assert(LHS->getType() == RHS->getType() &&
3313          "SCEVUDivExpr operand types don't match!");
3314 
3315   FoldingSetNodeID ID;
3316   ID.AddInteger(scUDivExpr);
3317   ID.AddPointer(LHS);
3318   ID.AddPointer(RHS);
3319   void *IP = nullptr;
3320   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3321     return S;
3322 
3323   // 0 udiv Y == 0
3324   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3325     if (LHSC->getValue()->isZero())
3326       return LHS;
3327 
3328   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3329     if (RHSC->getValue()->isOne())
3330       return LHS;                               // X udiv 1 --> x
3331     // If the denominator is zero, the result of the udiv is undefined. Don't
3332     // try to analyze it, because the resolution chosen here may differ from
3333     // the resolution chosen in other parts of the compiler.
3334     if (!RHSC->getValue()->isZero()) {
3335       // Determine if the division can be folded into the operands of
3336       // its operands.
3337       // TODO: Generalize this to non-constants by using known-bits information.
3338       Type *Ty = LHS->getType();
3339       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3340       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3341       // For non-power-of-two values, effectively round the value up to the
3342       // nearest power of two.
3343       if (!RHSC->getAPInt().isPowerOf2())
3344         ++MaxShiftAmt;
3345       IntegerType *ExtTy =
3346         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3347       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3348         if (const SCEVConstant *Step =
3349             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3350           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3351           const APInt &StepInt = Step->getAPInt();
3352           const APInt &DivInt = RHSC->getAPInt();
3353           if (!StepInt.urem(DivInt) &&
3354               getZeroExtendExpr(AR, ExtTy) ==
3355               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3356                             getZeroExtendExpr(Step, ExtTy),
3357                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3358             SmallVector<const SCEV *, 4> Operands;
3359             for (const SCEV *Op : AR->operands())
3360               Operands.push_back(getUDivExpr(Op, RHS));
3361             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3362           }
3363           /// Get a canonical UDivExpr for a recurrence.
3364           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3365           // We can currently only fold X%N if X is constant.
3366           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3367           if (StartC && !DivInt.urem(StepInt) &&
3368               getZeroExtendExpr(AR, ExtTy) ==
3369               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3370                             getZeroExtendExpr(Step, ExtTy),
3371                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3372             const APInt &StartInt = StartC->getAPInt();
3373             const APInt &StartRem = StartInt.urem(StepInt);
3374             if (StartRem != 0) {
3375               const SCEV *NewLHS =
3376                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3377                                 AR->getLoop(), SCEV::FlagNW);
3378               if (LHS != NewLHS) {
3379                 LHS = NewLHS;
3380 
3381                 // Reset the ID to include the new LHS, and check if it is
3382                 // already cached.
3383                 ID.clear();
3384                 ID.AddInteger(scUDivExpr);
3385                 ID.AddPointer(LHS);
3386                 ID.AddPointer(RHS);
3387                 IP = nullptr;
3388                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3389                   return S;
3390               }
3391             }
3392           }
3393         }
3394       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3395       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3396         SmallVector<const SCEV *, 4> Operands;
3397         for (const SCEV *Op : M->operands())
3398           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3399         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3400           // Find an operand that's safely divisible.
3401           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3402             const SCEV *Op = M->getOperand(i);
3403             const SCEV *Div = getUDivExpr(Op, RHSC);
3404             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3405               Operands = SmallVector<const SCEV *, 4>(M->operands());
3406               Operands[i] = Div;
3407               return getMulExpr(Operands);
3408             }
3409           }
3410       }
3411 
3412       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3413       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3414         if (auto *DivisorConstant =
3415                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3416           bool Overflow = false;
3417           APInt NewRHS =
3418               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3419           if (Overflow) {
3420             return getConstant(RHSC->getType(), 0, false);
3421           }
3422           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3423         }
3424       }
3425 
3426       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3427       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3428         SmallVector<const SCEV *, 4> Operands;
3429         for (const SCEV *Op : A->operands())
3430           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3431         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3432           Operands.clear();
3433           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3434             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3435             if (isa<SCEVUDivExpr>(Op) ||
3436                 getMulExpr(Op, RHS) != A->getOperand(i))
3437               break;
3438             Operands.push_back(Op);
3439           }
3440           if (Operands.size() == A->getNumOperands())
3441             return getAddExpr(Operands);
3442         }
3443       }
3444 
3445       // Fold if both operands are constant.
3446       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3447         Constant *LHSCV = LHSC->getValue();
3448         Constant *RHSCV = RHSC->getValue();
3449         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3450                                                                    RHSCV)));
3451       }
3452     }
3453   }
3454 
3455   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3456   // changes). Make sure we get a new one.
3457   IP = nullptr;
3458   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3459   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3460                                              LHS, RHS);
3461   UniqueSCEVs.InsertNode(S, IP);
3462   registerUser(S, {LHS, RHS});
3463   return S;
3464 }
3465 
3466 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3467   APInt A = C1->getAPInt().abs();
3468   APInt B = C2->getAPInt().abs();
3469   uint32_t ABW = A.getBitWidth();
3470   uint32_t BBW = B.getBitWidth();
3471 
3472   if (ABW > BBW)
3473     B = B.zext(ABW);
3474   else if (ABW < BBW)
3475     A = A.zext(BBW);
3476 
3477   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3478 }
3479 
3480 /// Get a canonical unsigned division expression, or something simpler if
3481 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3482 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3483 /// it's not exact because the udiv may be clearing bits.
3484 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3485                                               const SCEV *RHS) {
3486   // TODO: we could try to find factors in all sorts of things, but for now we
3487   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3488   // end of this file for inspiration.
3489 
3490   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3491   if (!Mul || !Mul->hasNoUnsignedWrap())
3492     return getUDivExpr(LHS, RHS);
3493 
3494   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3495     // If the mulexpr multiplies by a constant, then that constant must be the
3496     // first element of the mulexpr.
3497     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3498       if (LHSCst == RHSCst) {
3499         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3500         return getMulExpr(Operands);
3501       }
3502 
3503       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3504       // that there's a factor provided by one of the other terms. We need to
3505       // check.
3506       APInt Factor = gcd(LHSCst, RHSCst);
3507       if (!Factor.isIntN(1)) {
3508         LHSCst =
3509             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3510         RHSCst =
3511             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3512         SmallVector<const SCEV *, 2> Operands;
3513         Operands.push_back(LHSCst);
3514         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3515         LHS = getMulExpr(Operands);
3516         RHS = RHSCst;
3517         Mul = dyn_cast<SCEVMulExpr>(LHS);
3518         if (!Mul)
3519           return getUDivExactExpr(LHS, RHS);
3520       }
3521     }
3522   }
3523 
3524   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3525     if (Mul->getOperand(i) == RHS) {
3526       SmallVector<const SCEV *, 2> Operands;
3527       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3528       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3529       return getMulExpr(Operands);
3530     }
3531   }
3532 
3533   return getUDivExpr(LHS, RHS);
3534 }
3535 
3536 /// Get an add recurrence expression for the specified loop.  Simplify the
3537 /// expression as much as possible.
3538 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3539                                            const Loop *L,
3540                                            SCEV::NoWrapFlags Flags) {
3541   SmallVector<const SCEV *, 4> Operands;
3542   Operands.push_back(Start);
3543   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3544     if (StepChrec->getLoop() == L) {
3545       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3546       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3547     }
3548 
3549   Operands.push_back(Step);
3550   return getAddRecExpr(Operands, L, Flags);
3551 }
3552 
3553 /// Get an add recurrence expression for the specified loop.  Simplify the
3554 /// expression as much as possible.
3555 const SCEV *
3556 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3557                                const Loop *L, SCEV::NoWrapFlags Flags) {
3558   if (Operands.size() == 1) return Operands[0];
3559 #ifndef NDEBUG
3560   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3561   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3562     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3563            "SCEVAddRecExpr operand types don't match!");
3564     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3565   }
3566   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3567     assert(isLoopInvariant(Operands[i], L) &&
3568            "SCEVAddRecExpr operand is not loop-invariant!");
3569 #endif
3570 
3571   if (Operands.back()->isZero()) {
3572     Operands.pop_back();
3573     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3574   }
3575 
3576   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3577   // use that information to infer NUW and NSW flags. However, computing a
3578   // BE count requires calling getAddRecExpr, so we may not yet have a
3579   // meaningful BE count at this point (and if we don't, we'd be stuck
3580   // with a SCEVCouldNotCompute as the cached BE count).
3581 
3582   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3583 
3584   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3585   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3586     const Loop *NestedLoop = NestedAR->getLoop();
3587     if (L->contains(NestedLoop)
3588             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3589             : (!NestedLoop->contains(L) &&
3590                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3591       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3592       Operands[0] = NestedAR->getStart();
3593       // AddRecs require their operands be loop-invariant with respect to their
3594       // loops. Don't perform this transformation if it would break this
3595       // requirement.
3596       bool AllInvariant = all_of(
3597           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3598 
3599       if (AllInvariant) {
3600         // Create a recurrence for the outer loop with the same step size.
3601         //
3602         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3603         // inner recurrence has the same property.
3604         SCEV::NoWrapFlags OuterFlags =
3605           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3606 
3607         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3608         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3609           return isLoopInvariant(Op, NestedLoop);
3610         });
3611 
3612         if (AllInvariant) {
3613           // Ok, both add recurrences are valid after the transformation.
3614           //
3615           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3616           // the outer recurrence has the same property.
3617           SCEV::NoWrapFlags InnerFlags =
3618             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3619           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3620         }
3621       }
3622       // Reset Operands to its original state.
3623       Operands[0] = NestedAR;
3624     }
3625   }
3626 
3627   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3628   // already have one, otherwise create a new one.
3629   return getOrCreateAddRecExpr(Operands, L, Flags);
3630 }
3631 
3632 const SCEV *
3633 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3634                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3635   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3636   // getSCEV(Base)->getType() has the same address space as Base->getType()
3637   // because SCEV::getType() preserves the address space.
3638   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3639   const bool AssumeInBoundsFlags = [&]() {
3640     if (!GEP->isInBounds())
3641       return false;
3642 
3643     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3644     // but to do that, we have to ensure that said flag is valid in the entire
3645     // defined scope of the SCEV.
3646     auto *GEPI = dyn_cast<Instruction>(GEP);
3647     // TODO: non-instructions have global scope.  We might be able to prove
3648     // some global scope cases
3649     return GEPI && isSCEVExprNeverPoison(GEPI);
3650   }();
3651 
3652   SCEV::NoWrapFlags OffsetWrap =
3653     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3654 
3655   Type *CurTy = GEP->getType();
3656   bool FirstIter = true;
3657   SmallVector<const SCEV *, 4> Offsets;
3658   for (const SCEV *IndexExpr : IndexExprs) {
3659     // Compute the (potentially symbolic) offset in bytes for this index.
3660     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3661       // For a struct, add the member offset.
3662       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3663       unsigned FieldNo = Index->getZExtValue();
3664       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3665       Offsets.push_back(FieldOffset);
3666 
3667       // Update CurTy to the type of the field at Index.
3668       CurTy = STy->getTypeAtIndex(Index);
3669     } else {
3670       // Update CurTy to its element type.
3671       if (FirstIter) {
3672         assert(isa<PointerType>(CurTy) &&
3673                "The first index of a GEP indexes a pointer");
3674         CurTy = GEP->getSourceElementType();
3675         FirstIter = false;
3676       } else {
3677         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3678       }
3679       // For an array, add the element offset, explicitly scaled.
3680       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3681       // Getelementptr indices are signed.
3682       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3683 
3684       // Multiply the index by the element size to compute the element offset.
3685       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3686       Offsets.push_back(LocalOffset);
3687     }
3688   }
3689 
3690   // Handle degenerate case of GEP without offsets.
3691   if (Offsets.empty())
3692     return BaseExpr;
3693 
3694   // Add the offsets together, assuming nsw if inbounds.
3695   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3696   // Add the base address and the offset. We cannot use the nsw flag, as the
3697   // base address is unsigned. However, if we know that the offset is
3698   // non-negative, we can use nuw.
3699   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3700                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3701   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3702   assert(BaseExpr->getType() == GEPExpr->getType() &&
3703          "GEP should not change type mid-flight.");
3704   return GEPExpr;
3705 }
3706 
3707 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3708                                                ArrayRef<const SCEV *> Ops) {
3709   FoldingSetNodeID ID;
3710   ID.AddInteger(SCEVType);
3711   for (const SCEV *Op : Ops)
3712     ID.AddPointer(Op);
3713   void *IP = nullptr;
3714   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3715 }
3716 
3717 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3718   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3719   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3720 }
3721 
3722 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3723                                            SmallVectorImpl<const SCEV *> &Ops) {
3724   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3725   if (Ops.size() == 1) return Ops[0];
3726 #ifndef NDEBUG
3727   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3728   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3729     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3730            "Operand types don't match!");
3731     assert(Ops[0]->getType()->isPointerTy() ==
3732                Ops[i]->getType()->isPointerTy() &&
3733            "min/max should be consistently pointerish");
3734   }
3735 #endif
3736 
3737   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3738   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3739 
3740   // Sort by complexity, this groups all similar expression types together.
3741   GroupByComplexity(Ops, &LI, DT);
3742 
3743   // Check if we have created the same expression before.
3744   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3745     return S;
3746   }
3747 
3748   // If there are any constants, fold them together.
3749   unsigned Idx = 0;
3750   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3751     ++Idx;
3752     assert(Idx < Ops.size());
3753     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3754       if (Kind == scSMaxExpr)
3755         return APIntOps::smax(LHS, RHS);
3756       else if (Kind == scSMinExpr)
3757         return APIntOps::smin(LHS, RHS);
3758       else if (Kind == scUMaxExpr)
3759         return APIntOps::umax(LHS, RHS);
3760       else if (Kind == scUMinExpr)
3761         return APIntOps::umin(LHS, RHS);
3762       llvm_unreachable("Unknown SCEV min/max opcode");
3763     };
3764 
3765     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3766       // We found two constants, fold them together!
3767       ConstantInt *Fold = ConstantInt::get(
3768           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3769       Ops[0] = getConstant(Fold);
3770       Ops.erase(Ops.begin()+1);  // Erase the folded element
3771       if (Ops.size() == 1) return Ops[0];
3772       LHSC = cast<SCEVConstant>(Ops[0]);
3773     }
3774 
3775     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3776     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3777 
3778     if (IsMax ? IsMinV : IsMaxV) {
3779       // If we are left with a constant minimum(/maximum)-int, strip it off.
3780       Ops.erase(Ops.begin());
3781       --Idx;
3782     } else if (IsMax ? IsMaxV : IsMinV) {
3783       // If we have a max(/min) with a constant maximum(/minimum)-int,
3784       // it will always be the extremum.
3785       return LHSC;
3786     }
3787 
3788     if (Ops.size() == 1) return Ops[0];
3789   }
3790 
3791   // Find the first operation of the same kind
3792   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3793     ++Idx;
3794 
3795   // Check to see if one of the operands is of the same kind. If so, expand its
3796   // operands onto our operand list, and recurse to simplify.
3797   if (Idx < Ops.size()) {
3798     bool DeletedAny = false;
3799     while (Ops[Idx]->getSCEVType() == Kind) {
3800       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3801       Ops.erase(Ops.begin()+Idx);
3802       Ops.append(SMME->op_begin(), SMME->op_end());
3803       DeletedAny = true;
3804     }
3805 
3806     if (DeletedAny)
3807       return getMinMaxExpr(Kind, Ops);
3808   }
3809 
3810   // Okay, check to see if the same value occurs in the operand list twice.  If
3811   // so, delete one.  Since we sorted the list, these values are required to
3812   // be adjacent.
3813   llvm::CmpInst::Predicate GEPred =
3814       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3815   llvm::CmpInst::Predicate LEPred =
3816       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3817   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3818   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3819   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3820     if (Ops[i] == Ops[i + 1] ||
3821         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3822       //  X op Y op Y  -->  X op Y
3823       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3824       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3825       --i;
3826       --e;
3827     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3828                                                Ops[i + 1])) {
3829       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3830       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3831       --i;
3832       --e;
3833     }
3834   }
3835 
3836   if (Ops.size() == 1) return Ops[0];
3837 
3838   assert(!Ops.empty() && "Reduced smax down to nothing!");
3839 
3840   // Okay, it looks like we really DO need an expr.  Check to see if we
3841   // already have one, otherwise create a new one.
3842   FoldingSetNodeID ID;
3843   ID.AddInteger(Kind);
3844   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3845     ID.AddPointer(Ops[i]);
3846   void *IP = nullptr;
3847   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3848   if (ExistingSCEV)
3849     return ExistingSCEV;
3850   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3851   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3852   SCEV *S = new (SCEVAllocator)
3853       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3854 
3855   UniqueSCEVs.InsertNode(S, IP);
3856   registerUser(S, Ops);
3857   return S;
3858 }
3859 
3860 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3861   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3862   return getSMaxExpr(Ops);
3863 }
3864 
3865 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3866   return getMinMaxExpr(scSMaxExpr, Ops);
3867 }
3868 
3869 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3870   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3871   return getUMaxExpr(Ops);
3872 }
3873 
3874 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3875   return getMinMaxExpr(scUMaxExpr, Ops);
3876 }
3877 
3878 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3879                                          const SCEV *RHS) {
3880   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3881   return getSMinExpr(Ops);
3882 }
3883 
3884 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3885   return getMinMaxExpr(scSMinExpr, Ops);
3886 }
3887 
3888 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3889                                          const SCEV *RHS) {
3890   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3891   return getUMinExpr(Ops);
3892 }
3893 
3894 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3895   return getMinMaxExpr(scUMinExpr, Ops);
3896 }
3897 
3898 const SCEV *
3899 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3900                                              ScalableVectorType *ScalableTy) {
3901   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3902   Constant *One = ConstantInt::get(IntTy, 1);
3903   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3904   // Note that the expression we created is the final expression, we don't
3905   // want to simplify it any further Also, if we call a normal getSCEV(),
3906   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3907   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3908 }
3909 
3910 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3911   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3912     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3913   // We can bypass creating a target-independent constant expression and then
3914   // folding it back into a ConstantInt. This is just a compile-time
3915   // optimization.
3916   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3917 }
3918 
3919 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3920   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3921     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3922   // We can bypass creating a target-independent constant expression and then
3923   // folding it back into a ConstantInt. This is just a compile-time
3924   // optimization.
3925   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3926 }
3927 
3928 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3929                                              StructType *STy,
3930                                              unsigned FieldNo) {
3931   // We can bypass creating a target-independent constant expression and then
3932   // folding it back into a ConstantInt. This is just a compile-time
3933   // optimization.
3934   return getConstant(
3935       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3936 }
3937 
3938 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3939   // Don't attempt to do anything other than create a SCEVUnknown object
3940   // here.  createSCEV only calls getUnknown after checking for all other
3941   // interesting possibilities, and any other code that calls getUnknown
3942   // is doing so in order to hide a value from SCEV canonicalization.
3943 
3944   FoldingSetNodeID ID;
3945   ID.AddInteger(scUnknown);
3946   ID.AddPointer(V);
3947   void *IP = nullptr;
3948   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3949     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3950            "Stale SCEVUnknown in uniquing map!");
3951     return S;
3952   }
3953   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3954                                             FirstUnknown);
3955   FirstUnknown = cast<SCEVUnknown>(S);
3956   UniqueSCEVs.InsertNode(S, IP);
3957   return S;
3958 }
3959 
3960 //===----------------------------------------------------------------------===//
3961 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3962 //
3963 
3964 /// Test if values of the given type are analyzable within the SCEV
3965 /// framework. This primarily includes integer types, and it can optionally
3966 /// include pointer types if the ScalarEvolution class has access to
3967 /// target-specific information.
3968 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3969   // Integers and pointers are always SCEVable.
3970   return Ty->isIntOrPtrTy();
3971 }
3972 
3973 /// Return the size in bits of the specified type, for which isSCEVable must
3974 /// return true.
3975 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3976   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3977   if (Ty->isPointerTy())
3978     return getDataLayout().getIndexTypeSizeInBits(Ty);
3979   return getDataLayout().getTypeSizeInBits(Ty);
3980 }
3981 
3982 /// Return a type with the same bitwidth as the given type and which represents
3983 /// how SCEV will treat the given type, for which isSCEVable must return
3984 /// true. For pointer types, this is the pointer index sized integer type.
3985 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3986   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3987 
3988   if (Ty->isIntegerTy())
3989     return Ty;
3990 
3991   // The only other support type is pointer.
3992   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3993   return getDataLayout().getIndexType(Ty);
3994 }
3995 
3996 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3997   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3998 }
3999 
4000 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4001                                                          const SCEV *B) {
4002   /// For a valid use point to exist, the defining scope of one operand
4003   /// must dominate the other.
4004   bool PreciseA, PreciseB;
4005   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4006   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4007   if (!PreciseA || !PreciseB)
4008     // Can't tell.
4009     return false;
4010   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4011     DT.dominates(ScopeB, ScopeA);
4012 }
4013 
4014 
4015 const SCEV *ScalarEvolution::getCouldNotCompute() {
4016   return CouldNotCompute.get();
4017 }
4018 
4019 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4020   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4021     auto *SU = dyn_cast<SCEVUnknown>(S);
4022     return SU && SU->getValue() == nullptr;
4023   });
4024 
4025   return !ContainsNulls;
4026 }
4027 
4028 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4029   HasRecMapType::iterator I = HasRecMap.find(S);
4030   if (I != HasRecMap.end())
4031     return I->second;
4032 
4033   bool FoundAddRec =
4034       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4035   HasRecMap.insert({S, FoundAddRec});
4036   return FoundAddRec;
4037 }
4038 
4039 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
4040 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
4041 /// offset I, then return {S', I}, else return {\p S, nullptr}.
4042 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
4043   const auto *Add = dyn_cast<SCEVAddExpr>(S);
4044   if (!Add)
4045     return {S, nullptr};
4046 
4047   if (Add->getNumOperands() != 2)
4048     return {S, nullptr};
4049 
4050   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
4051   if (!ConstOp)
4052     return {S, nullptr};
4053 
4054   return {Add->getOperand(1), ConstOp->getValue()};
4055 }
4056 
4057 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4058 /// by the value and offset from any ValueOffsetPair in the set.
4059 ScalarEvolution::ValueOffsetPairSetVector *
4060 ScalarEvolution::getSCEVValues(const SCEV *S) {
4061   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4062   if (SI == ExprValueMap.end())
4063     return nullptr;
4064 #ifndef NDEBUG
4065   if (VerifySCEVMap) {
4066     // Check there is no dangling Value in the set returned.
4067     for (const auto &VE : SI->second)
4068       assert(ValueExprMap.count(VE.first));
4069   }
4070 #endif
4071   return &SI->second;
4072 }
4073 
4074 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4075 /// cannot be used separately. eraseValueFromMap should be used to remove
4076 /// V from ValueExprMap and ExprValueMap at the same time.
4077 void ScalarEvolution::eraseValueFromMap(Value *V) {
4078   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4079   if (I != ValueExprMap.end()) {
4080     const SCEV *S = I->second;
4081     // Remove {V, 0} from the set of ExprValueMap[S]
4082     if (auto *SV = getSCEVValues(S))
4083       SV->remove({V, nullptr});
4084 
4085     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
4086     const SCEV *Stripped;
4087     ConstantInt *Offset;
4088     std::tie(Stripped, Offset) = splitAddExpr(S);
4089     if (Offset != nullptr) {
4090       if (auto *SV = getSCEVValues(Stripped))
4091         SV->remove({V, Offset});
4092     }
4093     ValueExprMap.erase(V);
4094   }
4095 }
4096 
4097 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4098   auto It = ValueExprMap.find_as(V);
4099   if (It == ValueExprMap.end()) {
4100     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4101     ExprValueMap[S].insert({V, nullptr});
4102   } else {
4103     // A recursive query may have already computed the SCEV. It should have
4104     // arrived at the same value.
4105     assert(It->second == S);
4106   }
4107 }
4108 
4109 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4110 /// create a new one.
4111 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4112   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4113 
4114   const SCEV *S = getExistingSCEV(V);
4115   if (S == nullptr) {
4116     S = createSCEV(V);
4117     // During PHI resolution, it is possible to create two SCEVs for the same
4118     // V, so it is needed to double check whether V->S is inserted into
4119     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4120     std::pair<ValueExprMapType::iterator, bool> Pair =
4121         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4122     if (Pair.second) {
4123       ExprValueMap[S].insert({V, nullptr});
4124 
4125       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
4126       // ExprValueMap.
4127       const SCEV *Stripped = S;
4128       ConstantInt *Offset = nullptr;
4129       std::tie(Stripped, Offset) = splitAddExpr(S);
4130       // If stripped is SCEVUnknown, don't bother to save
4131       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
4132       // increase the complexity of the expansion code.
4133       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
4134       // because it may generate add/sub instead of GEP in SCEV expansion.
4135       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
4136           !isa<GetElementPtrInst>(V))
4137         ExprValueMap[Stripped].insert({V, Offset});
4138     }
4139   }
4140   return S;
4141 }
4142 
4143 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4144   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4145 
4146   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4147   if (I != ValueExprMap.end()) {
4148     const SCEV *S = I->second;
4149     assert(checkValidity(S) &&
4150            "existing SCEV has not been properly invalidated");
4151     return S;
4152   }
4153   return nullptr;
4154 }
4155 
4156 /// Return a SCEV corresponding to -V = -1*V
4157 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4158                                              SCEV::NoWrapFlags Flags) {
4159   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4160     return getConstant(
4161                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4162 
4163   Type *Ty = V->getType();
4164   Ty = getEffectiveSCEVType(Ty);
4165   return getMulExpr(V, getMinusOne(Ty), Flags);
4166 }
4167 
4168 /// If Expr computes ~A, return A else return nullptr
4169 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4170   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4171   if (!Add || Add->getNumOperands() != 2 ||
4172       !Add->getOperand(0)->isAllOnesValue())
4173     return nullptr;
4174 
4175   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4176   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4177       !AddRHS->getOperand(0)->isAllOnesValue())
4178     return nullptr;
4179 
4180   return AddRHS->getOperand(1);
4181 }
4182 
4183 /// Return a SCEV corresponding to ~V = -1-V
4184 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4185   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4186 
4187   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4188     return getConstant(
4189                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4190 
4191   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4192   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4193     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4194       SmallVector<const SCEV *, 2> MatchedOperands;
4195       for (const SCEV *Operand : MME->operands()) {
4196         const SCEV *Matched = MatchNotExpr(Operand);
4197         if (!Matched)
4198           return (const SCEV *)nullptr;
4199         MatchedOperands.push_back(Matched);
4200       }
4201       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4202                            MatchedOperands);
4203     };
4204     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4205       return Replaced;
4206   }
4207 
4208   Type *Ty = V->getType();
4209   Ty = getEffectiveSCEVType(Ty);
4210   return getMinusSCEV(getMinusOne(Ty), V);
4211 }
4212 
4213 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4214   assert(P->getType()->isPointerTy());
4215 
4216   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4217     // The base of an AddRec is the first operand.
4218     SmallVector<const SCEV *> Ops{AddRec->operands()};
4219     Ops[0] = removePointerBase(Ops[0]);
4220     // Don't try to transfer nowrap flags for now. We could in some cases
4221     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4222     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4223   }
4224   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4225     // The base of an Add is the pointer operand.
4226     SmallVector<const SCEV *> Ops{Add->operands()};
4227     const SCEV **PtrOp = nullptr;
4228     for (const SCEV *&AddOp : Ops) {
4229       if (AddOp->getType()->isPointerTy()) {
4230         assert(!PtrOp && "Cannot have multiple pointer ops");
4231         PtrOp = &AddOp;
4232       }
4233     }
4234     *PtrOp = removePointerBase(*PtrOp);
4235     // Don't try to transfer nowrap flags for now. We could in some cases
4236     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4237     return getAddExpr(Ops);
4238   }
4239   // Any other expression must be a pointer base.
4240   return getZero(P->getType());
4241 }
4242 
4243 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4244                                           SCEV::NoWrapFlags Flags,
4245                                           unsigned Depth) {
4246   // Fast path: X - X --> 0.
4247   if (LHS == RHS)
4248     return getZero(LHS->getType());
4249 
4250   // If we subtract two pointers with different pointer bases, bail.
4251   // Eventually, we're going to add an assertion to getMulExpr that we
4252   // can't multiply by a pointer.
4253   if (RHS->getType()->isPointerTy()) {
4254     if (!LHS->getType()->isPointerTy() ||
4255         getPointerBase(LHS) != getPointerBase(RHS))
4256       return getCouldNotCompute();
4257     LHS = removePointerBase(LHS);
4258     RHS = removePointerBase(RHS);
4259   }
4260 
4261   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4262   // makes it so that we cannot make much use of NUW.
4263   auto AddFlags = SCEV::FlagAnyWrap;
4264   const bool RHSIsNotMinSigned =
4265       !getSignedRangeMin(RHS).isMinSignedValue();
4266   if (hasFlags(Flags, SCEV::FlagNSW)) {
4267     // Let M be the minimum representable signed value. Then (-1)*RHS
4268     // signed-wraps if and only if RHS is M. That can happen even for
4269     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4270     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4271     // (-1)*RHS, we need to prove that RHS != M.
4272     //
4273     // If LHS is non-negative and we know that LHS - RHS does not
4274     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4275     // either by proving that RHS > M or that LHS >= 0.
4276     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4277       AddFlags = SCEV::FlagNSW;
4278     }
4279   }
4280 
4281   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4282   // RHS is NSW and LHS >= 0.
4283   //
4284   // The difficulty here is that the NSW flag may have been proven
4285   // relative to a loop that is to be found in a recurrence in LHS and
4286   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4287   // larger scope than intended.
4288   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4289 
4290   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4291 }
4292 
4293 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4294                                                      unsigned Depth) {
4295   Type *SrcTy = V->getType();
4296   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4297          "Cannot truncate or zero extend with non-integer arguments!");
4298   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4299     return V;  // No conversion
4300   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4301     return getTruncateExpr(V, Ty, Depth);
4302   return getZeroExtendExpr(V, Ty, Depth);
4303 }
4304 
4305 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4306                                                      unsigned Depth) {
4307   Type *SrcTy = V->getType();
4308   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4309          "Cannot truncate or zero extend with non-integer arguments!");
4310   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4311     return V;  // No conversion
4312   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4313     return getTruncateExpr(V, Ty, Depth);
4314   return getSignExtendExpr(V, Ty, Depth);
4315 }
4316 
4317 const SCEV *
4318 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4319   Type *SrcTy = V->getType();
4320   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4321          "Cannot noop or zero extend with non-integer arguments!");
4322   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4323          "getNoopOrZeroExtend cannot truncate!");
4324   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4325     return V;  // No conversion
4326   return getZeroExtendExpr(V, Ty);
4327 }
4328 
4329 const SCEV *
4330 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4331   Type *SrcTy = V->getType();
4332   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4333          "Cannot noop or sign extend with non-integer arguments!");
4334   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4335          "getNoopOrSignExtend cannot truncate!");
4336   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4337     return V;  // No conversion
4338   return getSignExtendExpr(V, Ty);
4339 }
4340 
4341 const SCEV *
4342 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4343   Type *SrcTy = V->getType();
4344   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4345          "Cannot noop or any extend with non-integer arguments!");
4346   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4347          "getNoopOrAnyExtend cannot truncate!");
4348   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4349     return V;  // No conversion
4350   return getAnyExtendExpr(V, Ty);
4351 }
4352 
4353 const SCEV *
4354 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4355   Type *SrcTy = V->getType();
4356   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4357          "Cannot truncate or noop with non-integer arguments!");
4358   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4359          "getTruncateOrNoop cannot extend!");
4360   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4361     return V;  // No conversion
4362   return getTruncateExpr(V, Ty);
4363 }
4364 
4365 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4366                                                         const SCEV *RHS) {
4367   const SCEV *PromotedLHS = LHS;
4368   const SCEV *PromotedRHS = RHS;
4369 
4370   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4371     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4372   else
4373     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4374 
4375   return getUMaxExpr(PromotedLHS, PromotedRHS);
4376 }
4377 
4378 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4379                                                         const SCEV *RHS) {
4380   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4381   return getUMinFromMismatchedTypes(Ops);
4382 }
4383 
4384 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4385     SmallVectorImpl<const SCEV *> &Ops) {
4386   assert(!Ops.empty() && "At least one operand must be!");
4387   // Trivial case.
4388   if (Ops.size() == 1)
4389     return Ops[0];
4390 
4391   // Find the max type first.
4392   Type *MaxType = nullptr;
4393   for (auto *S : Ops)
4394     if (MaxType)
4395       MaxType = getWiderType(MaxType, S->getType());
4396     else
4397       MaxType = S->getType();
4398   assert(MaxType && "Failed to find maximum type!");
4399 
4400   // Extend all ops to max type.
4401   SmallVector<const SCEV *, 2> PromotedOps;
4402   for (auto *S : Ops)
4403     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4404 
4405   // Generate umin.
4406   return getUMinExpr(PromotedOps);
4407 }
4408 
4409 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4410   // A pointer operand may evaluate to a nonpointer expression, such as null.
4411   if (!V->getType()->isPointerTy())
4412     return V;
4413 
4414   while (true) {
4415     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4416       V = AddRec->getStart();
4417     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4418       const SCEV *PtrOp = nullptr;
4419       for (const SCEV *AddOp : Add->operands()) {
4420         if (AddOp->getType()->isPointerTy()) {
4421           assert(!PtrOp && "Cannot have multiple pointer ops");
4422           PtrOp = AddOp;
4423         }
4424       }
4425       assert(PtrOp && "Must have pointer op");
4426       V = PtrOp;
4427     } else // Not something we can look further into.
4428       return V;
4429   }
4430 }
4431 
4432 /// Push users of the given Instruction onto the given Worklist.
4433 static void PushDefUseChildren(Instruction *I,
4434                                SmallVectorImpl<Instruction *> &Worklist,
4435                                SmallPtrSetImpl<Instruction *> &Visited) {
4436   // Push the def-use children onto the Worklist stack.
4437   for (User *U : I->users()) {
4438     auto *UserInsn = cast<Instruction>(U);
4439     if (Visited.insert(UserInsn).second)
4440       Worklist.push_back(UserInsn);
4441   }
4442 }
4443 
4444 namespace {
4445 
4446 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4447 /// expression in case its Loop is L. If it is not L then
4448 /// if IgnoreOtherLoops is true then use AddRec itself
4449 /// otherwise rewrite cannot be done.
4450 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4451 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4452 public:
4453   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4454                              bool IgnoreOtherLoops = true) {
4455     SCEVInitRewriter Rewriter(L, SE);
4456     const SCEV *Result = Rewriter.visit(S);
4457     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4458       return SE.getCouldNotCompute();
4459     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4460                ? SE.getCouldNotCompute()
4461                : Result;
4462   }
4463 
4464   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4465     if (!SE.isLoopInvariant(Expr, L))
4466       SeenLoopVariantSCEVUnknown = true;
4467     return Expr;
4468   }
4469 
4470   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4471     // Only re-write AddRecExprs for this loop.
4472     if (Expr->getLoop() == L)
4473       return Expr->getStart();
4474     SeenOtherLoops = true;
4475     return Expr;
4476   }
4477 
4478   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4479 
4480   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4481 
4482 private:
4483   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4484       : SCEVRewriteVisitor(SE), L(L) {}
4485 
4486   const Loop *L;
4487   bool SeenLoopVariantSCEVUnknown = false;
4488   bool SeenOtherLoops = false;
4489 };
4490 
4491 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4492 /// increment expression in case its Loop is L. If it is not L then
4493 /// use AddRec itself.
4494 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4495 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4496 public:
4497   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4498     SCEVPostIncRewriter Rewriter(L, SE);
4499     const SCEV *Result = Rewriter.visit(S);
4500     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4501         ? SE.getCouldNotCompute()
4502         : Result;
4503   }
4504 
4505   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4506     if (!SE.isLoopInvariant(Expr, L))
4507       SeenLoopVariantSCEVUnknown = true;
4508     return Expr;
4509   }
4510 
4511   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4512     // Only re-write AddRecExprs for this loop.
4513     if (Expr->getLoop() == L)
4514       return Expr->getPostIncExpr(SE);
4515     SeenOtherLoops = true;
4516     return Expr;
4517   }
4518 
4519   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4520 
4521   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4522 
4523 private:
4524   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4525       : SCEVRewriteVisitor(SE), L(L) {}
4526 
4527   const Loop *L;
4528   bool SeenLoopVariantSCEVUnknown = false;
4529   bool SeenOtherLoops = false;
4530 };
4531 
4532 /// This class evaluates the compare condition by matching it against the
4533 /// condition of loop latch. If there is a match we assume a true value
4534 /// for the condition while building SCEV nodes.
4535 class SCEVBackedgeConditionFolder
4536     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4537 public:
4538   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4539                              ScalarEvolution &SE) {
4540     bool IsPosBECond = false;
4541     Value *BECond = nullptr;
4542     if (BasicBlock *Latch = L->getLoopLatch()) {
4543       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4544       if (BI && BI->isConditional()) {
4545         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4546                "Both outgoing branches should not target same header!");
4547         BECond = BI->getCondition();
4548         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4549       } else {
4550         return S;
4551       }
4552     }
4553     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4554     return Rewriter.visit(S);
4555   }
4556 
4557   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4558     const SCEV *Result = Expr;
4559     bool InvariantF = SE.isLoopInvariant(Expr, L);
4560 
4561     if (!InvariantF) {
4562       Instruction *I = cast<Instruction>(Expr->getValue());
4563       switch (I->getOpcode()) {
4564       case Instruction::Select: {
4565         SelectInst *SI = cast<SelectInst>(I);
4566         Optional<const SCEV *> Res =
4567             compareWithBackedgeCondition(SI->getCondition());
4568         if (Res.hasValue()) {
4569           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4570           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4571         }
4572         break;
4573       }
4574       default: {
4575         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4576         if (Res.hasValue())
4577           Result = Res.getValue();
4578         break;
4579       }
4580       }
4581     }
4582     return Result;
4583   }
4584 
4585 private:
4586   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4587                                        bool IsPosBECond, ScalarEvolution &SE)
4588       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4589         IsPositiveBECond(IsPosBECond) {}
4590 
4591   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4592 
4593   const Loop *L;
4594   /// Loop back condition.
4595   Value *BackedgeCond = nullptr;
4596   /// Set to true if loop back is on positive branch condition.
4597   bool IsPositiveBECond;
4598 };
4599 
4600 Optional<const SCEV *>
4601 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4602 
4603   // If value matches the backedge condition for loop latch,
4604   // then return a constant evolution node based on loopback
4605   // branch taken.
4606   if (BackedgeCond == IC)
4607     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4608                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4609   return None;
4610 }
4611 
4612 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4613 public:
4614   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4615                              ScalarEvolution &SE) {
4616     SCEVShiftRewriter Rewriter(L, SE);
4617     const SCEV *Result = Rewriter.visit(S);
4618     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4619   }
4620 
4621   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4622     // Only allow AddRecExprs for this loop.
4623     if (!SE.isLoopInvariant(Expr, L))
4624       Valid = false;
4625     return Expr;
4626   }
4627 
4628   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4629     if (Expr->getLoop() == L && Expr->isAffine())
4630       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4631     Valid = false;
4632     return Expr;
4633   }
4634 
4635   bool isValid() { return Valid; }
4636 
4637 private:
4638   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4639       : SCEVRewriteVisitor(SE), L(L) {}
4640 
4641   const Loop *L;
4642   bool Valid = true;
4643 };
4644 
4645 } // end anonymous namespace
4646 
4647 SCEV::NoWrapFlags
4648 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4649   if (!AR->isAffine())
4650     return SCEV::FlagAnyWrap;
4651 
4652   using OBO = OverflowingBinaryOperator;
4653 
4654   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4655 
4656   if (!AR->hasNoSignedWrap()) {
4657     ConstantRange AddRecRange = getSignedRange(AR);
4658     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4659 
4660     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4661         Instruction::Add, IncRange, OBO::NoSignedWrap);
4662     if (NSWRegion.contains(AddRecRange))
4663       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4664   }
4665 
4666   if (!AR->hasNoUnsignedWrap()) {
4667     ConstantRange AddRecRange = getUnsignedRange(AR);
4668     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4669 
4670     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4671         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4672     if (NUWRegion.contains(AddRecRange))
4673       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4674   }
4675 
4676   return Result;
4677 }
4678 
4679 SCEV::NoWrapFlags
4680 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4681   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4682 
4683   if (AR->hasNoSignedWrap())
4684     return Result;
4685 
4686   if (!AR->isAffine())
4687     return Result;
4688 
4689   const SCEV *Step = AR->getStepRecurrence(*this);
4690   const Loop *L = AR->getLoop();
4691 
4692   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4693   // Note that this serves two purposes: It filters out loops that are
4694   // simply not analyzable, and it covers the case where this code is
4695   // being called from within backedge-taken count analysis, such that
4696   // attempting to ask for the backedge-taken count would likely result
4697   // in infinite recursion. In the later case, the analysis code will
4698   // cope with a conservative value, and it will take care to purge
4699   // that value once it has finished.
4700   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4701 
4702   // Normally, in the cases we can prove no-overflow via a
4703   // backedge guarding condition, we can also compute a backedge
4704   // taken count for the loop.  The exceptions are assumptions and
4705   // guards present in the loop -- SCEV is not great at exploiting
4706   // these to compute max backedge taken counts, but can still use
4707   // these to prove lack of overflow.  Use this fact to avoid
4708   // doing extra work that may not pay off.
4709 
4710   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4711       AC.assumptions().empty())
4712     return Result;
4713 
4714   // If the backedge is guarded by a comparison with the pre-inc  value the
4715   // addrec is safe. Also, if the entry is guarded by a comparison with the
4716   // start value and the backedge is guarded by a comparison with the post-inc
4717   // value, the addrec is safe.
4718   ICmpInst::Predicate Pred;
4719   const SCEV *OverflowLimit =
4720     getSignedOverflowLimitForStep(Step, &Pred, this);
4721   if (OverflowLimit &&
4722       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4723        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4724     Result = setFlags(Result, SCEV::FlagNSW);
4725   }
4726   return Result;
4727 }
4728 SCEV::NoWrapFlags
4729 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4730   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4731 
4732   if (AR->hasNoUnsignedWrap())
4733     return Result;
4734 
4735   if (!AR->isAffine())
4736     return Result;
4737 
4738   const SCEV *Step = AR->getStepRecurrence(*this);
4739   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4740   const Loop *L = AR->getLoop();
4741 
4742   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4743   // Note that this serves two purposes: It filters out loops that are
4744   // simply not analyzable, and it covers the case where this code is
4745   // being called from within backedge-taken count analysis, such that
4746   // attempting to ask for the backedge-taken count would likely result
4747   // in infinite recursion. In the later case, the analysis code will
4748   // cope with a conservative value, and it will take care to purge
4749   // that value once it has finished.
4750   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4751 
4752   // Normally, in the cases we can prove no-overflow via a
4753   // backedge guarding condition, we can also compute a backedge
4754   // taken count for the loop.  The exceptions are assumptions and
4755   // guards present in the loop -- SCEV is not great at exploiting
4756   // these to compute max backedge taken counts, but can still use
4757   // these to prove lack of overflow.  Use this fact to avoid
4758   // doing extra work that may not pay off.
4759 
4760   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4761       AC.assumptions().empty())
4762     return Result;
4763 
4764   // If the backedge is guarded by a comparison with the pre-inc  value the
4765   // addrec is safe. Also, if the entry is guarded by a comparison with the
4766   // start value and the backedge is guarded by a comparison with the post-inc
4767   // value, the addrec is safe.
4768   if (isKnownPositive(Step)) {
4769     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4770                                 getUnsignedRangeMax(Step));
4771     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4772         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4773       Result = setFlags(Result, SCEV::FlagNUW);
4774     }
4775   }
4776 
4777   return Result;
4778 }
4779 
4780 namespace {
4781 
4782 /// Represents an abstract binary operation.  This may exist as a
4783 /// normal instruction or constant expression, or may have been
4784 /// derived from an expression tree.
4785 struct BinaryOp {
4786   unsigned Opcode;
4787   Value *LHS;
4788   Value *RHS;
4789   bool IsNSW = false;
4790   bool IsNUW = false;
4791 
4792   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4793   /// constant expression.
4794   Operator *Op = nullptr;
4795 
4796   explicit BinaryOp(Operator *Op)
4797       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4798         Op(Op) {
4799     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4800       IsNSW = OBO->hasNoSignedWrap();
4801       IsNUW = OBO->hasNoUnsignedWrap();
4802     }
4803   }
4804 
4805   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4806                     bool IsNUW = false)
4807       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4808 };
4809 
4810 } // end anonymous namespace
4811 
4812 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4813 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4814   auto *Op = dyn_cast<Operator>(V);
4815   if (!Op)
4816     return None;
4817 
4818   // Implementation detail: all the cleverness here should happen without
4819   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4820   // SCEV expressions when possible, and we should not break that.
4821 
4822   switch (Op->getOpcode()) {
4823   case Instruction::Add:
4824   case Instruction::Sub:
4825   case Instruction::Mul:
4826   case Instruction::UDiv:
4827   case Instruction::URem:
4828   case Instruction::And:
4829   case Instruction::Or:
4830   case Instruction::AShr:
4831   case Instruction::Shl:
4832     return BinaryOp(Op);
4833 
4834   case Instruction::Xor:
4835     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4836       // If the RHS of the xor is a signmask, then this is just an add.
4837       // Instcombine turns add of signmask into xor as a strength reduction step.
4838       if (RHSC->getValue().isSignMask())
4839         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4840     return BinaryOp(Op);
4841 
4842   case Instruction::LShr:
4843     // Turn logical shift right of a constant into a unsigned divide.
4844     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4845       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4846 
4847       // If the shift count is not less than the bitwidth, the result of
4848       // the shift is undefined. Don't try to analyze it, because the
4849       // resolution chosen here may differ from the resolution chosen in
4850       // other parts of the compiler.
4851       if (SA->getValue().ult(BitWidth)) {
4852         Constant *X =
4853             ConstantInt::get(SA->getContext(),
4854                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4855         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4856       }
4857     }
4858     return BinaryOp(Op);
4859 
4860   case Instruction::ExtractValue: {
4861     auto *EVI = cast<ExtractValueInst>(Op);
4862     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4863       break;
4864 
4865     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4866     if (!WO)
4867       break;
4868 
4869     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4870     bool Signed = WO->isSigned();
4871     // TODO: Should add nuw/nsw flags for mul as well.
4872     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4873       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4874 
4875     // Now that we know that all uses of the arithmetic-result component of
4876     // CI are guarded by the overflow check, we can go ahead and pretend
4877     // that the arithmetic is non-overflowing.
4878     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4879                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4880   }
4881 
4882   default:
4883     break;
4884   }
4885 
4886   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4887   // semantics as a Sub, return a binary sub expression.
4888   if (auto *II = dyn_cast<IntrinsicInst>(V))
4889     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4890       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4891 
4892   return None;
4893 }
4894 
4895 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4896 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4897 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4898 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4899 /// follows one of the following patterns:
4900 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4901 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4902 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4903 /// we return the type of the truncation operation, and indicate whether the
4904 /// truncated type should be treated as signed/unsigned by setting
4905 /// \p Signed to true/false, respectively.
4906 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4907                                bool &Signed, ScalarEvolution &SE) {
4908   // The case where Op == SymbolicPHI (that is, with no type conversions on
4909   // the way) is handled by the regular add recurrence creating logic and
4910   // would have already been triggered in createAddRecForPHI. Reaching it here
4911   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4912   // because one of the other operands of the SCEVAddExpr updating this PHI is
4913   // not invariant).
4914   //
4915   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4916   // this case predicates that allow us to prove that Op == SymbolicPHI will
4917   // be added.
4918   if (Op == SymbolicPHI)
4919     return nullptr;
4920 
4921   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4922   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4923   if (SourceBits != NewBits)
4924     return nullptr;
4925 
4926   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4927   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4928   if (!SExt && !ZExt)
4929     return nullptr;
4930   const SCEVTruncateExpr *Trunc =
4931       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4932            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4933   if (!Trunc)
4934     return nullptr;
4935   const SCEV *X = Trunc->getOperand();
4936   if (X != SymbolicPHI)
4937     return nullptr;
4938   Signed = SExt != nullptr;
4939   return Trunc->getType();
4940 }
4941 
4942 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4943   if (!PN->getType()->isIntegerTy())
4944     return nullptr;
4945   const Loop *L = LI.getLoopFor(PN->getParent());
4946   if (!L || L->getHeader() != PN->getParent())
4947     return nullptr;
4948   return L;
4949 }
4950 
4951 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4952 // computation that updates the phi follows the following pattern:
4953 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4954 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4955 // If so, try to see if it can be rewritten as an AddRecExpr under some
4956 // Predicates. If successful, return them as a pair. Also cache the results
4957 // of the analysis.
4958 //
4959 // Example usage scenario:
4960 //    Say the Rewriter is called for the following SCEV:
4961 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4962 //    where:
4963 //         %X = phi i64 (%Start, %BEValue)
4964 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4965 //    and call this function with %SymbolicPHI = %X.
4966 //
4967 //    The analysis will find that the value coming around the backedge has
4968 //    the following SCEV:
4969 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4970 //    Upon concluding that this matches the desired pattern, the function
4971 //    will return the pair {NewAddRec, SmallPredsVec} where:
4972 //         NewAddRec = {%Start,+,%Step}
4973 //         SmallPredsVec = {P1, P2, P3} as follows:
4974 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4975 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4976 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4977 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4978 //    under the predicates {P1,P2,P3}.
4979 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4980 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4981 //
4982 // TODO's:
4983 //
4984 // 1) Extend the Induction descriptor to also support inductions that involve
4985 //    casts: When needed (namely, when we are called in the context of the
4986 //    vectorizer induction analysis), a Set of cast instructions will be
4987 //    populated by this method, and provided back to isInductionPHI. This is
4988 //    needed to allow the vectorizer to properly record them to be ignored by
4989 //    the cost model and to avoid vectorizing them (otherwise these casts,
4990 //    which are redundant under the runtime overflow checks, will be
4991 //    vectorized, which can be costly).
4992 //
4993 // 2) Support additional induction/PHISCEV patterns: We also want to support
4994 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4995 //    after the induction update operation (the induction increment):
4996 //
4997 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4998 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4999 //
5000 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5001 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5002 //
5003 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5004 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5005 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5006   SmallVector<const SCEVPredicate *, 3> Predicates;
5007 
5008   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5009   // return an AddRec expression under some predicate.
5010 
5011   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5012   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5013   assert(L && "Expecting an integer loop header phi");
5014 
5015   // The loop may have multiple entrances or multiple exits; we can analyze
5016   // this phi as an addrec if it has a unique entry value and a unique
5017   // backedge value.
5018   Value *BEValueV = nullptr, *StartValueV = nullptr;
5019   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5020     Value *V = PN->getIncomingValue(i);
5021     if (L->contains(PN->getIncomingBlock(i))) {
5022       if (!BEValueV) {
5023         BEValueV = V;
5024       } else if (BEValueV != V) {
5025         BEValueV = nullptr;
5026         break;
5027       }
5028     } else if (!StartValueV) {
5029       StartValueV = V;
5030     } else if (StartValueV != V) {
5031       StartValueV = nullptr;
5032       break;
5033     }
5034   }
5035   if (!BEValueV || !StartValueV)
5036     return None;
5037 
5038   const SCEV *BEValue = getSCEV(BEValueV);
5039 
5040   // If the value coming around the backedge is an add with the symbolic
5041   // value we just inserted, possibly with casts that we can ignore under
5042   // an appropriate runtime guard, then we found a simple induction variable!
5043   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5044   if (!Add)
5045     return None;
5046 
5047   // If there is a single occurrence of the symbolic value, possibly
5048   // casted, replace it with a recurrence.
5049   unsigned FoundIndex = Add->getNumOperands();
5050   Type *TruncTy = nullptr;
5051   bool Signed;
5052   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5053     if ((TruncTy =
5054              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5055       if (FoundIndex == e) {
5056         FoundIndex = i;
5057         break;
5058       }
5059 
5060   if (FoundIndex == Add->getNumOperands())
5061     return None;
5062 
5063   // Create an add with everything but the specified operand.
5064   SmallVector<const SCEV *, 8> Ops;
5065   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5066     if (i != FoundIndex)
5067       Ops.push_back(Add->getOperand(i));
5068   const SCEV *Accum = getAddExpr(Ops);
5069 
5070   // The runtime checks will not be valid if the step amount is
5071   // varying inside the loop.
5072   if (!isLoopInvariant(Accum, L))
5073     return None;
5074 
5075   // *** Part2: Create the predicates
5076 
5077   // Analysis was successful: we have a phi-with-cast pattern for which we
5078   // can return an AddRec expression under the following predicates:
5079   //
5080   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5081   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5082   // P2: An Equal predicate that guarantees that
5083   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5084   // P3: An Equal predicate that guarantees that
5085   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5086   //
5087   // As we next prove, the above predicates guarantee that:
5088   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5089   //
5090   //
5091   // More formally, we want to prove that:
5092   //     Expr(i+1) = Start + (i+1) * Accum
5093   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5094   //
5095   // Given that:
5096   // 1) Expr(0) = Start
5097   // 2) Expr(1) = Start + Accum
5098   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5099   // 3) Induction hypothesis (step i):
5100   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5101   //
5102   // Proof:
5103   //  Expr(i+1) =
5104   //   = Start + (i+1)*Accum
5105   //   = (Start + i*Accum) + Accum
5106   //   = Expr(i) + Accum
5107   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5108   //                                                             :: from step i
5109   //
5110   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5111   //
5112   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5113   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5114   //     + Accum                                                     :: from P3
5115   //
5116   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5117   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5118   //
5119   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5120   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5121   //
5122   // By induction, the same applies to all iterations 1<=i<n:
5123   //
5124 
5125   // Create a truncated addrec for which we will add a no overflow check (P1).
5126   const SCEV *StartVal = getSCEV(StartValueV);
5127   const SCEV *PHISCEV =
5128       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5129                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5130 
5131   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5132   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5133   // will be constant.
5134   //
5135   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5136   // add P1.
5137   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5138     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5139         Signed ? SCEVWrapPredicate::IncrementNSSW
5140                : SCEVWrapPredicate::IncrementNUSW;
5141     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5142     Predicates.push_back(AddRecPred);
5143   }
5144 
5145   // Create the Equal Predicates P2,P3:
5146 
5147   // It is possible that the predicates P2 and/or P3 are computable at
5148   // compile time due to StartVal and/or Accum being constants.
5149   // If either one is, then we can check that now and escape if either P2
5150   // or P3 is false.
5151 
5152   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5153   // for each of StartVal and Accum
5154   auto getExtendedExpr = [&](const SCEV *Expr,
5155                              bool CreateSignExtend) -> const SCEV * {
5156     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5157     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5158     const SCEV *ExtendedExpr =
5159         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5160                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5161     return ExtendedExpr;
5162   };
5163 
5164   // Given:
5165   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5166   //               = getExtendedExpr(Expr)
5167   // Determine whether the predicate P: Expr == ExtendedExpr
5168   // is known to be false at compile time
5169   auto PredIsKnownFalse = [&](const SCEV *Expr,
5170                               const SCEV *ExtendedExpr) -> bool {
5171     return Expr != ExtendedExpr &&
5172            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5173   };
5174 
5175   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5176   if (PredIsKnownFalse(StartVal, StartExtended)) {
5177     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5178     return None;
5179   }
5180 
5181   // The Step is always Signed (because the overflow checks are either
5182   // NSSW or NUSW)
5183   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5184   if (PredIsKnownFalse(Accum, AccumExtended)) {
5185     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5186     return None;
5187   }
5188 
5189   auto AppendPredicate = [&](const SCEV *Expr,
5190                              const SCEV *ExtendedExpr) -> void {
5191     if (Expr != ExtendedExpr &&
5192         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5193       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5194       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5195       Predicates.push_back(Pred);
5196     }
5197   };
5198 
5199   AppendPredicate(StartVal, StartExtended);
5200   AppendPredicate(Accum, AccumExtended);
5201 
5202   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5203   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5204   // into NewAR if it will also add the runtime overflow checks specified in
5205   // Predicates.
5206   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5207 
5208   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5209       std::make_pair(NewAR, Predicates);
5210   // Remember the result of the analysis for this SCEV at this locayyytion.
5211   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5212   return PredRewrite;
5213 }
5214 
5215 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5216 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5217   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5218   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5219   if (!L)
5220     return None;
5221 
5222   // Check to see if we already analyzed this PHI.
5223   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5224   if (I != PredicatedSCEVRewrites.end()) {
5225     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5226         I->second;
5227     // Analysis was done before and failed to create an AddRec:
5228     if (Rewrite.first == SymbolicPHI)
5229       return None;
5230     // Analysis was done before and succeeded to create an AddRec under
5231     // a predicate:
5232     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5233     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5234     return Rewrite;
5235   }
5236 
5237   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5238     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5239 
5240   // Record in the cache that the analysis failed
5241   if (!Rewrite) {
5242     SmallVector<const SCEVPredicate *, 3> Predicates;
5243     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5244     return None;
5245   }
5246 
5247   return Rewrite;
5248 }
5249 
5250 // FIXME: This utility is currently required because the Rewriter currently
5251 // does not rewrite this expression:
5252 // {0, +, (sext ix (trunc iy to ix) to iy)}
5253 // into {0, +, %step},
5254 // even when the following Equal predicate exists:
5255 // "%step == (sext ix (trunc iy to ix) to iy)".
5256 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5257     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5258   if (AR1 == AR2)
5259     return true;
5260 
5261   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5262     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5263         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5264       return false;
5265     return true;
5266   };
5267 
5268   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5269       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5270     return false;
5271   return true;
5272 }
5273 
5274 /// A helper function for createAddRecFromPHI to handle simple cases.
5275 ///
5276 /// This function tries to find an AddRec expression for the simplest (yet most
5277 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5278 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5279 /// technique for finding the AddRec expression.
5280 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5281                                                       Value *BEValueV,
5282                                                       Value *StartValueV) {
5283   const Loop *L = LI.getLoopFor(PN->getParent());
5284   assert(L && L->getHeader() == PN->getParent());
5285   assert(BEValueV && StartValueV);
5286 
5287   auto BO = MatchBinaryOp(BEValueV, DT);
5288   if (!BO)
5289     return nullptr;
5290 
5291   if (BO->Opcode != Instruction::Add)
5292     return nullptr;
5293 
5294   const SCEV *Accum = nullptr;
5295   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5296     Accum = getSCEV(BO->RHS);
5297   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5298     Accum = getSCEV(BO->LHS);
5299 
5300   if (!Accum)
5301     return nullptr;
5302 
5303   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5304   if (BO->IsNUW)
5305     Flags = setFlags(Flags, SCEV::FlagNUW);
5306   if (BO->IsNSW)
5307     Flags = setFlags(Flags, SCEV::FlagNSW);
5308 
5309   const SCEV *StartVal = getSCEV(StartValueV);
5310   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5311   insertValueToMap(PN, PHISCEV);
5312 
5313   // We can add Flags to the post-inc expression only if we
5314   // know that it is *undefined behavior* for BEValueV to
5315   // overflow.
5316   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5317     assert(isLoopInvariant(Accum, L) &&
5318            "Accum is defined outside L, but is not invariant?");
5319     if (isAddRecNeverPoison(BEInst, L))
5320       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5321   }
5322 
5323   return PHISCEV;
5324 }
5325 
5326 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5327   const Loop *L = LI.getLoopFor(PN->getParent());
5328   if (!L || L->getHeader() != PN->getParent())
5329     return nullptr;
5330 
5331   // The loop may have multiple entrances or multiple exits; we can analyze
5332   // this phi as an addrec if it has a unique entry value and a unique
5333   // backedge value.
5334   Value *BEValueV = nullptr, *StartValueV = nullptr;
5335   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5336     Value *V = PN->getIncomingValue(i);
5337     if (L->contains(PN->getIncomingBlock(i))) {
5338       if (!BEValueV) {
5339         BEValueV = V;
5340       } else if (BEValueV != V) {
5341         BEValueV = nullptr;
5342         break;
5343       }
5344     } else if (!StartValueV) {
5345       StartValueV = V;
5346     } else if (StartValueV != V) {
5347       StartValueV = nullptr;
5348       break;
5349     }
5350   }
5351   if (!BEValueV || !StartValueV)
5352     return nullptr;
5353 
5354   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5355          "PHI node already processed?");
5356 
5357   // First, try to find AddRec expression without creating a fictituos symbolic
5358   // value for PN.
5359   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5360     return S;
5361 
5362   // Handle PHI node value symbolically.
5363   const SCEV *SymbolicName = getUnknown(PN);
5364   insertValueToMap(PN, SymbolicName);
5365 
5366   // Using this symbolic name for the PHI, analyze the value coming around
5367   // the back-edge.
5368   const SCEV *BEValue = getSCEV(BEValueV);
5369 
5370   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5371   // has a special value for the first iteration of the loop.
5372 
5373   // If the value coming around the backedge is an add with the symbolic
5374   // value we just inserted, then we found a simple induction variable!
5375   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5376     // If there is a single occurrence of the symbolic value, replace it
5377     // with a recurrence.
5378     unsigned FoundIndex = Add->getNumOperands();
5379     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5380       if (Add->getOperand(i) == SymbolicName)
5381         if (FoundIndex == e) {
5382           FoundIndex = i;
5383           break;
5384         }
5385 
5386     if (FoundIndex != Add->getNumOperands()) {
5387       // Create an add with everything but the specified operand.
5388       SmallVector<const SCEV *, 8> Ops;
5389       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5390         if (i != FoundIndex)
5391           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5392                                                              L, *this));
5393       const SCEV *Accum = getAddExpr(Ops);
5394 
5395       // This is not a valid addrec if the step amount is varying each
5396       // loop iteration, but is not itself an addrec in this loop.
5397       if (isLoopInvariant(Accum, L) ||
5398           (isa<SCEVAddRecExpr>(Accum) &&
5399            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5400         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5401 
5402         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5403           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5404             if (BO->IsNUW)
5405               Flags = setFlags(Flags, SCEV::FlagNUW);
5406             if (BO->IsNSW)
5407               Flags = setFlags(Flags, SCEV::FlagNSW);
5408           }
5409         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5410           // If the increment is an inbounds GEP, then we know the address
5411           // space cannot be wrapped around. We cannot make any guarantee
5412           // about signed or unsigned overflow because pointers are
5413           // unsigned but we may have a negative index from the base
5414           // pointer. We can guarantee that no unsigned wrap occurs if the
5415           // indices form a positive value.
5416           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5417             Flags = setFlags(Flags, SCEV::FlagNW);
5418 
5419             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5420             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5421               Flags = setFlags(Flags, SCEV::FlagNUW);
5422           }
5423 
5424           // We cannot transfer nuw and nsw flags from subtraction
5425           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5426           // for instance.
5427         }
5428 
5429         const SCEV *StartVal = getSCEV(StartValueV);
5430         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5431 
5432         // Okay, for the entire analysis of this edge we assumed the PHI
5433         // to be symbolic.  We now need to go back and purge all of the
5434         // entries for the scalars that use the symbolic expression.
5435         forgetMemoizedResults(SymbolicName);
5436         insertValueToMap(PN, PHISCEV);
5437 
5438         // We can add Flags to the post-inc expression only if we
5439         // know that it is *undefined behavior* for BEValueV to
5440         // overflow.
5441         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5442           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5443             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5444 
5445         return PHISCEV;
5446       }
5447     }
5448   } else {
5449     // Otherwise, this could be a loop like this:
5450     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5451     // In this case, j = {1,+,1}  and BEValue is j.
5452     // Because the other in-value of i (0) fits the evolution of BEValue
5453     // i really is an addrec evolution.
5454     //
5455     // We can generalize this saying that i is the shifted value of BEValue
5456     // by one iteration:
5457     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5458     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5459     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5460     if (Shifted != getCouldNotCompute() &&
5461         Start != getCouldNotCompute()) {
5462       const SCEV *StartVal = getSCEV(StartValueV);
5463       if (Start == StartVal) {
5464         // Okay, for the entire analysis of this edge we assumed the PHI
5465         // to be symbolic.  We now need to go back and purge all of the
5466         // entries for the scalars that use the symbolic expression.
5467         forgetMemoizedResults(SymbolicName);
5468         insertValueToMap(PN, Shifted);
5469         return Shifted;
5470       }
5471     }
5472   }
5473 
5474   // Remove the temporary PHI node SCEV that has been inserted while intending
5475   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5476   // as it will prevent later (possibly simpler) SCEV expressions to be added
5477   // to the ValueExprMap.
5478   eraseValueFromMap(PN);
5479 
5480   return nullptr;
5481 }
5482 
5483 // Checks if the SCEV S is available at BB.  S is considered available at BB
5484 // if S can be materialized at BB without introducing a fault.
5485 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5486                                BasicBlock *BB) {
5487   struct CheckAvailable {
5488     bool TraversalDone = false;
5489     bool Available = true;
5490 
5491     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5492     BasicBlock *BB = nullptr;
5493     DominatorTree &DT;
5494 
5495     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5496       : L(L), BB(BB), DT(DT) {}
5497 
5498     bool setUnavailable() {
5499       TraversalDone = true;
5500       Available = false;
5501       return false;
5502     }
5503 
5504     bool follow(const SCEV *S) {
5505       switch (S->getSCEVType()) {
5506       case scConstant:
5507       case scPtrToInt:
5508       case scTruncate:
5509       case scZeroExtend:
5510       case scSignExtend:
5511       case scAddExpr:
5512       case scMulExpr:
5513       case scUMaxExpr:
5514       case scSMaxExpr:
5515       case scUMinExpr:
5516       case scSMinExpr:
5517         // These expressions are available if their operand(s) is/are.
5518         return true;
5519 
5520       case scAddRecExpr: {
5521         // We allow add recurrences that are on the loop BB is in, or some
5522         // outer loop.  This guarantees availability because the value of the
5523         // add recurrence at BB is simply the "current" value of the induction
5524         // variable.  We can relax this in the future; for instance an add
5525         // recurrence on a sibling dominating loop is also available at BB.
5526         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5527         if (L && (ARLoop == L || ARLoop->contains(L)))
5528           return true;
5529 
5530         return setUnavailable();
5531       }
5532 
5533       case scUnknown: {
5534         // For SCEVUnknown, we check for simple dominance.
5535         const auto *SU = cast<SCEVUnknown>(S);
5536         Value *V = SU->getValue();
5537 
5538         if (isa<Argument>(V))
5539           return false;
5540 
5541         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5542           return false;
5543 
5544         return setUnavailable();
5545       }
5546 
5547       case scUDivExpr:
5548       case scCouldNotCompute:
5549         // We do not try to smart about these at all.
5550         return setUnavailable();
5551       }
5552       llvm_unreachable("Unknown SCEV kind!");
5553     }
5554 
5555     bool isDone() { return TraversalDone; }
5556   };
5557 
5558   CheckAvailable CA(L, BB, DT);
5559   SCEVTraversal<CheckAvailable> ST(CA);
5560 
5561   ST.visitAll(S);
5562   return CA.Available;
5563 }
5564 
5565 // Try to match a control flow sequence that branches out at BI and merges back
5566 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5567 // match.
5568 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5569                           Value *&C, Value *&LHS, Value *&RHS) {
5570   C = BI->getCondition();
5571 
5572   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5573   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5574 
5575   if (!LeftEdge.isSingleEdge())
5576     return false;
5577 
5578   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5579 
5580   Use &LeftUse = Merge->getOperandUse(0);
5581   Use &RightUse = Merge->getOperandUse(1);
5582 
5583   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5584     LHS = LeftUse;
5585     RHS = RightUse;
5586     return true;
5587   }
5588 
5589   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5590     LHS = RightUse;
5591     RHS = LeftUse;
5592     return true;
5593   }
5594 
5595   return false;
5596 }
5597 
5598 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5599   auto IsReachable =
5600       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5601   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5602     const Loop *L = LI.getLoopFor(PN->getParent());
5603 
5604     // We don't want to break LCSSA, even in a SCEV expression tree.
5605     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5606       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5607         return nullptr;
5608 
5609     // Try to match
5610     //
5611     //  br %cond, label %left, label %right
5612     // left:
5613     //  br label %merge
5614     // right:
5615     //  br label %merge
5616     // merge:
5617     //  V = phi [ %x, %left ], [ %y, %right ]
5618     //
5619     // as "select %cond, %x, %y"
5620 
5621     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5622     assert(IDom && "At least the entry block should dominate PN");
5623 
5624     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5625     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5626 
5627     if (BI && BI->isConditional() &&
5628         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5629         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5630         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5631       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5632   }
5633 
5634   return nullptr;
5635 }
5636 
5637 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5638   if (const SCEV *S = createAddRecFromPHI(PN))
5639     return S;
5640 
5641   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5642     return S;
5643 
5644   // If the PHI has a single incoming value, follow that value, unless the
5645   // PHI's incoming blocks are in a different loop, in which case doing so
5646   // risks breaking LCSSA form. Instcombine would normally zap these, but
5647   // it doesn't have DominatorTree information, so it may miss cases.
5648   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5649     if (LI.replacementPreservesLCSSAForm(PN, V))
5650       return getSCEV(V);
5651 
5652   // If it's not a loop phi, we can't handle it yet.
5653   return getUnknown(PN);
5654 }
5655 
5656 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5657                                                       Value *Cond,
5658                                                       Value *TrueVal,
5659                                                       Value *FalseVal) {
5660   // Handle "constant" branch or select. This can occur for instance when a
5661   // loop pass transforms an inner loop and moves on to process the outer loop.
5662   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5663     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5664 
5665   // Try to match some simple smax or umax patterns.
5666   auto *ICI = dyn_cast<ICmpInst>(Cond);
5667   if (!ICI)
5668     return getUnknown(I);
5669 
5670   Value *LHS = ICI->getOperand(0);
5671   Value *RHS = ICI->getOperand(1);
5672 
5673   switch (ICI->getPredicate()) {
5674   case ICmpInst::ICMP_SLT:
5675   case ICmpInst::ICMP_SLE:
5676   case ICmpInst::ICMP_ULT:
5677   case ICmpInst::ICMP_ULE:
5678     std::swap(LHS, RHS);
5679     LLVM_FALLTHROUGH;
5680   case ICmpInst::ICMP_SGT:
5681   case ICmpInst::ICMP_SGE:
5682   case ICmpInst::ICMP_UGT:
5683   case ICmpInst::ICMP_UGE:
5684     // a > b ? a+x : b+x  ->  max(a, b)+x
5685     // a > b ? b+x : a+x  ->  min(a, b)+x
5686     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5687       bool Signed = ICI->isSigned();
5688       const SCEV *LA = getSCEV(TrueVal);
5689       const SCEV *RA = getSCEV(FalseVal);
5690       const SCEV *LS = getSCEV(LHS);
5691       const SCEV *RS = getSCEV(RHS);
5692       if (LA->getType()->isPointerTy()) {
5693         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5694         // Need to make sure we can't produce weird expressions involving
5695         // negated pointers.
5696         if (LA == LS && RA == RS)
5697           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5698         if (LA == RS && RA == LS)
5699           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5700       }
5701       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5702         if (Op->getType()->isPointerTy()) {
5703           Op = getLosslessPtrToIntExpr(Op);
5704           if (isa<SCEVCouldNotCompute>(Op))
5705             return Op;
5706         }
5707         if (Signed)
5708           Op = getNoopOrSignExtend(Op, I->getType());
5709         else
5710           Op = getNoopOrZeroExtend(Op, I->getType());
5711         return Op;
5712       };
5713       LS = CoerceOperand(LS);
5714       RS = CoerceOperand(RS);
5715       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
5716         break;
5717       const SCEV *LDiff = getMinusSCEV(LA, LS);
5718       const SCEV *RDiff = getMinusSCEV(RA, RS);
5719       if (LDiff == RDiff)
5720         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
5721                           LDiff);
5722       LDiff = getMinusSCEV(LA, RS);
5723       RDiff = getMinusSCEV(RA, LS);
5724       if (LDiff == RDiff)
5725         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
5726                           LDiff);
5727     }
5728     break;
5729   case ICmpInst::ICMP_NE:
5730     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5731     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5732         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5733       const SCEV *One = getOne(I->getType());
5734       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5735       const SCEV *LA = getSCEV(TrueVal);
5736       const SCEV *RA = getSCEV(FalseVal);
5737       const SCEV *LDiff = getMinusSCEV(LA, LS);
5738       const SCEV *RDiff = getMinusSCEV(RA, One);
5739       if (LDiff == RDiff)
5740         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5741     }
5742     break;
5743   case ICmpInst::ICMP_EQ:
5744     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5745     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5746         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5747       const SCEV *One = getOne(I->getType());
5748       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5749       const SCEV *LA = getSCEV(TrueVal);
5750       const SCEV *RA = getSCEV(FalseVal);
5751       const SCEV *LDiff = getMinusSCEV(LA, One);
5752       const SCEV *RDiff = getMinusSCEV(RA, LS);
5753       if (LDiff == RDiff)
5754         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5755     }
5756     break;
5757   default:
5758     break;
5759   }
5760 
5761   return getUnknown(I);
5762 }
5763 
5764 /// Expand GEP instructions into add and multiply operations. This allows them
5765 /// to be analyzed by regular SCEV code.
5766 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5767   // Don't attempt to analyze GEPs over unsized objects.
5768   if (!GEP->getSourceElementType()->isSized())
5769     return getUnknown(GEP);
5770 
5771   SmallVector<const SCEV *, 4> IndexExprs;
5772   for (Value *Index : GEP->indices())
5773     IndexExprs.push_back(getSCEV(Index));
5774   return getGEPExpr(GEP, IndexExprs);
5775 }
5776 
5777 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5778   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5779     return C->getAPInt().countTrailingZeros();
5780 
5781   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5782     return GetMinTrailingZeros(I->getOperand());
5783 
5784   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5785     return std::min(GetMinTrailingZeros(T->getOperand()),
5786                     (uint32_t)getTypeSizeInBits(T->getType()));
5787 
5788   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5789     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5790     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5791                ? getTypeSizeInBits(E->getType())
5792                : OpRes;
5793   }
5794 
5795   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5796     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5797     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5798                ? getTypeSizeInBits(E->getType())
5799                : OpRes;
5800   }
5801 
5802   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5803     // The result is the min of all operands results.
5804     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5805     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5806       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5807     return MinOpRes;
5808   }
5809 
5810   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5811     // The result is the sum of all operands results.
5812     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5813     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5814     for (unsigned i = 1, e = M->getNumOperands();
5815          SumOpRes != BitWidth && i != e; ++i)
5816       SumOpRes =
5817           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5818     return SumOpRes;
5819   }
5820 
5821   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5822     // The result is the min of all operands results.
5823     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5824     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5825       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5826     return MinOpRes;
5827   }
5828 
5829   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5830     // The result is the min of all operands results.
5831     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5832     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5833       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5834     return MinOpRes;
5835   }
5836 
5837   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5838     // The result is the min of all operands results.
5839     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5840     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5841       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5842     return MinOpRes;
5843   }
5844 
5845   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5846     // For a SCEVUnknown, ask ValueTracking.
5847     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5848     return Known.countMinTrailingZeros();
5849   }
5850 
5851   // SCEVUDivExpr
5852   return 0;
5853 }
5854 
5855 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5856   auto I = MinTrailingZerosCache.find(S);
5857   if (I != MinTrailingZerosCache.end())
5858     return I->second;
5859 
5860   uint32_t Result = GetMinTrailingZerosImpl(S);
5861   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5862   assert(InsertPair.second && "Should insert a new key");
5863   return InsertPair.first->second;
5864 }
5865 
5866 /// Helper method to assign a range to V from metadata present in the IR.
5867 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5868   if (Instruction *I = dyn_cast<Instruction>(V))
5869     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5870       return getConstantRangeFromMetadata(*MD);
5871 
5872   return None;
5873 }
5874 
5875 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5876                                      SCEV::NoWrapFlags Flags) {
5877   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5878     AddRec->setNoWrapFlags(Flags);
5879     UnsignedRanges.erase(AddRec);
5880     SignedRanges.erase(AddRec);
5881   }
5882 }
5883 
5884 ConstantRange ScalarEvolution::
5885 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5886   const DataLayout &DL = getDataLayout();
5887 
5888   unsigned BitWidth = getTypeSizeInBits(U->getType());
5889   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
5890 
5891   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5892   // use information about the trip count to improve our available range.  Note
5893   // that the trip count independent cases are already handled by known bits.
5894   // WARNING: The definition of recurrence used here is subtly different than
5895   // the one used by AddRec (and thus most of this file).  Step is allowed to
5896   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5897   // and other addrecs in the same loop (for non-affine addrecs).  The code
5898   // below intentionally handles the case where step is not loop invariant.
5899   auto *P = dyn_cast<PHINode>(U->getValue());
5900   if (!P)
5901     return FullSet;
5902 
5903   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5904   // even the values that are not available in these blocks may come from them,
5905   // and this leads to false-positive recurrence test.
5906   for (auto *Pred : predecessors(P->getParent()))
5907     if (!DT.isReachableFromEntry(Pred))
5908       return FullSet;
5909 
5910   BinaryOperator *BO;
5911   Value *Start, *Step;
5912   if (!matchSimpleRecurrence(P, BO, Start, Step))
5913     return FullSet;
5914 
5915   // If we found a recurrence in reachable code, we must be in a loop. Note
5916   // that BO might be in some subloop of L, and that's completely okay.
5917   auto *L = LI.getLoopFor(P->getParent());
5918   assert(L && L->getHeader() == P->getParent());
5919   if (!L->contains(BO->getParent()))
5920     // NOTE: This bailout should be an assert instead.  However, asserting
5921     // the condition here exposes a case where LoopFusion is querying SCEV
5922     // with malformed loop information during the midst of the transform.
5923     // There doesn't appear to be an obvious fix, so for the moment bailout
5924     // until the caller issue can be fixed.  PR49566 tracks the bug.
5925     return FullSet;
5926 
5927   // TODO: Extend to other opcodes such as mul, and div
5928   switch (BO->getOpcode()) {
5929   default:
5930     return FullSet;
5931   case Instruction::AShr:
5932   case Instruction::LShr:
5933   case Instruction::Shl:
5934     break;
5935   };
5936 
5937   if (BO->getOperand(0) != P)
5938     // TODO: Handle the power function forms some day.
5939     return FullSet;
5940 
5941   unsigned TC = getSmallConstantMaxTripCount(L);
5942   if (!TC || TC >= BitWidth)
5943     return FullSet;
5944 
5945   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5946   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5947   assert(KnownStart.getBitWidth() == BitWidth &&
5948          KnownStep.getBitWidth() == BitWidth);
5949 
5950   // Compute total shift amount, being careful of overflow and bitwidths.
5951   auto MaxShiftAmt = KnownStep.getMaxValue();
5952   APInt TCAP(BitWidth, TC-1);
5953   bool Overflow = false;
5954   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5955   if (Overflow)
5956     return FullSet;
5957 
5958   switch (BO->getOpcode()) {
5959   default:
5960     llvm_unreachable("filtered out above");
5961   case Instruction::AShr: {
5962     // For each ashr, three cases:
5963     //   shift = 0 => unchanged value
5964     //   saturation => 0 or -1
5965     //   other => a value closer to zero (of the same sign)
5966     // Thus, the end value is closer to zero than the start.
5967     auto KnownEnd = KnownBits::ashr(KnownStart,
5968                                     KnownBits::makeConstant(TotalShift));
5969     if (KnownStart.isNonNegative())
5970       // Analogous to lshr (simply not yet canonicalized)
5971       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5972                                         KnownStart.getMaxValue() + 1);
5973     if (KnownStart.isNegative())
5974       // End >=u Start && End <=s Start
5975       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
5976                                         KnownEnd.getMaxValue() + 1);
5977     break;
5978   }
5979   case Instruction::LShr: {
5980     // For each lshr, three cases:
5981     //   shift = 0 => unchanged value
5982     //   saturation => 0
5983     //   other => a smaller positive number
5984     // Thus, the low end of the unsigned range is the last value produced.
5985     auto KnownEnd = KnownBits::lshr(KnownStart,
5986                                     KnownBits::makeConstant(TotalShift));
5987     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5988                                       KnownStart.getMaxValue() + 1);
5989   }
5990   case Instruction::Shl: {
5991     // Iff no bits are shifted out, value increases on every shift.
5992     auto KnownEnd = KnownBits::shl(KnownStart,
5993                                    KnownBits::makeConstant(TotalShift));
5994     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5995       return ConstantRange(KnownStart.getMinValue(),
5996                            KnownEnd.getMaxValue() + 1);
5997     break;
5998   }
5999   };
6000   return FullSet;
6001 }
6002 
6003 /// Determine the range for a particular SCEV.  If SignHint is
6004 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6005 /// with a "cleaner" unsigned (resp. signed) representation.
6006 const ConstantRange &
6007 ScalarEvolution::getRangeRef(const SCEV *S,
6008                              ScalarEvolution::RangeSignHint SignHint) {
6009   DenseMap<const SCEV *, ConstantRange> &Cache =
6010       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6011                                                        : SignedRanges;
6012   ConstantRange::PreferredRangeType RangeType =
6013       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
6014           ? ConstantRange::Unsigned : ConstantRange::Signed;
6015 
6016   // See if we've computed this range already.
6017   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6018   if (I != Cache.end())
6019     return I->second;
6020 
6021   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6022     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6023 
6024   unsigned BitWidth = getTypeSizeInBits(S->getType());
6025   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6026   using OBO = OverflowingBinaryOperator;
6027 
6028   // If the value has known zeros, the maximum value will have those known zeros
6029   // as well.
6030   uint32_t TZ = GetMinTrailingZeros(S);
6031   if (TZ != 0) {
6032     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6033       ConservativeResult =
6034           ConstantRange(APInt::getMinValue(BitWidth),
6035                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6036     else
6037       ConservativeResult = ConstantRange(
6038           APInt::getSignedMinValue(BitWidth),
6039           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6040   }
6041 
6042   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6043     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6044     unsigned WrapType = OBO::AnyWrap;
6045     if (Add->hasNoSignedWrap())
6046       WrapType |= OBO::NoSignedWrap;
6047     if (Add->hasNoUnsignedWrap())
6048       WrapType |= OBO::NoUnsignedWrap;
6049     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6050       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6051                           WrapType, RangeType);
6052     return setRange(Add, SignHint,
6053                     ConservativeResult.intersectWith(X, RangeType));
6054   }
6055 
6056   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6057     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6058     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6059       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6060     return setRange(Mul, SignHint,
6061                     ConservativeResult.intersectWith(X, RangeType));
6062   }
6063 
6064   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
6065     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
6066     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
6067       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
6068     return setRange(SMax, SignHint,
6069                     ConservativeResult.intersectWith(X, RangeType));
6070   }
6071 
6072   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
6073     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
6074     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
6075       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
6076     return setRange(UMax, SignHint,
6077                     ConservativeResult.intersectWith(X, RangeType));
6078   }
6079 
6080   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
6081     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
6082     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
6083       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
6084     return setRange(SMin, SignHint,
6085                     ConservativeResult.intersectWith(X, RangeType));
6086   }
6087 
6088   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
6089     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
6090     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
6091       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
6092     return setRange(UMin, SignHint,
6093                     ConservativeResult.intersectWith(X, RangeType));
6094   }
6095 
6096   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6097     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6098     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6099     return setRange(UDiv, SignHint,
6100                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6101   }
6102 
6103   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6104     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6105     return setRange(ZExt, SignHint,
6106                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6107                                                      RangeType));
6108   }
6109 
6110   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6111     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6112     return setRange(SExt, SignHint,
6113                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6114                                                      RangeType));
6115   }
6116 
6117   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6118     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6119     return setRange(PtrToInt, SignHint, X);
6120   }
6121 
6122   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6123     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6124     return setRange(Trunc, SignHint,
6125                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6126                                                      RangeType));
6127   }
6128 
6129   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6130     // If there's no unsigned wrap, the value will never be less than its
6131     // initial value.
6132     if (AddRec->hasNoUnsignedWrap()) {
6133       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6134       if (!UnsignedMinValue.isZero())
6135         ConservativeResult = ConservativeResult.intersectWith(
6136             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6137     }
6138 
6139     // If there's no signed wrap, and all the operands except initial value have
6140     // the same sign or zero, the value won't ever be:
6141     // 1: smaller than initial value if operands are non negative,
6142     // 2: bigger than initial value if operands are non positive.
6143     // For both cases, value can not cross signed min/max boundary.
6144     if (AddRec->hasNoSignedWrap()) {
6145       bool AllNonNeg = true;
6146       bool AllNonPos = true;
6147       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6148         if (!isKnownNonNegative(AddRec->getOperand(i)))
6149           AllNonNeg = false;
6150         if (!isKnownNonPositive(AddRec->getOperand(i)))
6151           AllNonPos = false;
6152       }
6153       if (AllNonNeg)
6154         ConservativeResult = ConservativeResult.intersectWith(
6155             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6156                                        APInt::getSignedMinValue(BitWidth)),
6157             RangeType);
6158       else if (AllNonPos)
6159         ConservativeResult = ConservativeResult.intersectWith(
6160             ConstantRange::getNonEmpty(
6161                 APInt::getSignedMinValue(BitWidth),
6162                 getSignedRangeMax(AddRec->getStart()) + 1),
6163             RangeType);
6164     }
6165 
6166     // TODO: non-affine addrec
6167     if (AddRec->isAffine()) {
6168       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6169       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6170           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6171         auto RangeFromAffine = getRangeForAffineAR(
6172             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6173             BitWidth);
6174         ConservativeResult =
6175             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6176 
6177         auto RangeFromFactoring = getRangeViaFactoring(
6178             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6179             BitWidth);
6180         ConservativeResult =
6181             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6182       }
6183 
6184       // Now try symbolic BE count and more powerful methods.
6185       if (UseExpensiveRangeSharpening) {
6186         const SCEV *SymbolicMaxBECount =
6187             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6188         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6189             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6190             AddRec->hasNoSelfWrap()) {
6191           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6192               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6193           ConservativeResult =
6194               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6195         }
6196       }
6197     }
6198 
6199     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6200   }
6201 
6202   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6203 
6204     // Check if the IR explicitly contains !range metadata.
6205     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6206     if (MDRange.hasValue())
6207       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6208                                                             RangeType);
6209 
6210     // Use facts about recurrences in the underlying IR.  Note that add
6211     // recurrences are AddRecExprs and thus don't hit this path.  This
6212     // primarily handles shift recurrences.
6213     auto CR = getRangeForUnknownRecurrence(U);
6214     ConservativeResult = ConservativeResult.intersectWith(CR);
6215 
6216     // See if ValueTracking can give us a useful range.
6217     const DataLayout &DL = getDataLayout();
6218     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6219     if (Known.getBitWidth() != BitWidth)
6220       Known = Known.zextOrTrunc(BitWidth);
6221 
6222     // ValueTracking may be able to compute a tighter result for the number of
6223     // sign bits than for the value of those sign bits.
6224     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6225     if (U->getType()->isPointerTy()) {
6226       // If the pointer size is larger than the index size type, this can cause
6227       // NS to be larger than BitWidth. So compensate for this.
6228       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6229       int ptrIdxDiff = ptrSize - BitWidth;
6230       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6231         NS -= ptrIdxDiff;
6232     }
6233 
6234     if (NS > 1) {
6235       // If we know any of the sign bits, we know all of the sign bits.
6236       if (!Known.Zero.getHiBits(NS).isZero())
6237         Known.Zero.setHighBits(NS);
6238       if (!Known.One.getHiBits(NS).isZero())
6239         Known.One.setHighBits(NS);
6240     }
6241 
6242     if (Known.getMinValue() != Known.getMaxValue() + 1)
6243       ConservativeResult = ConservativeResult.intersectWith(
6244           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6245           RangeType);
6246     if (NS > 1)
6247       ConservativeResult = ConservativeResult.intersectWith(
6248           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6249                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6250           RangeType);
6251 
6252     // A range of Phi is a subset of union of all ranges of its input.
6253     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6254       // Make sure that we do not run over cycled Phis.
6255       if (PendingPhiRanges.insert(Phi).second) {
6256         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6257         for (auto &Op : Phi->operands()) {
6258           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6259           RangeFromOps = RangeFromOps.unionWith(OpRange);
6260           // No point to continue if we already have a full set.
6261           if (RangeFromOps.isFullSet())
6262             break;
6263         }
6264         ConservativeResult =
6265             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6266         bool Erased = PendingPhiRanges.erase(Phi);
6267         assert(Erased && "Failed to erase Phi properly?");
6268         (void) Erased;
6269       }
6270     }
6271 
6272     return setRange(U, SignHint, std::move(ConservativeResult));
6273   }
6274 
6275   return setRange(S, SignHint, std::move(ConservativeResult));
6276 }
6277 
6278 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6279 // values that the expression can take. Initially, the expression has a value
6280 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6281 // argument defines if we treat Step as signed or unsigned.
6282 static ConstantRange getRangeForAffineARHelper(APInt Step,
6283                                                const ConstantRange &StartRange,
6284                                                const APInt &MaxBECount,
6285                                                unsigned BitWidth, bool Signed) {
6286   // If either Step or MaxBECount is 0, then the expression won't change, and we
6287   // just need to return the initial range.
6288   if (Step == 0 || MaxBECount == 0)
6289     return StartRange;
6290 
6291   // If we don't know anything about the initial value (i.e. StartRange is
6292   // FullRange), then we don't know anything about the final range either.
6293   // Return FullRange.
6294   if (StartRange.isFullSet())
6295     return ConstantRange::getFull(BitWidth);
6296 
6297   // If Step is signed and negative, then we use its absolute value, but we also
6298   // note that we're moving in the opposite direction.
6299   bool Descending = Signed && Step.isNegative();
6300 
6301   if (Signed)
6302     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6303     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6304     // This equations hold true due to the well-defined wrap-around behavior of
6305     // APInt.
6306     Step = Step.abs();
6307 
6308   // Check if Offset is more than full span of BitWidth. If it is, the
6309   // expression is guaranteed to overflow.
6310   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6311     return ConstantRange::getFull(BitWidth);
6312 
6313   // Offset is by how much the expression can change. Checks above guarantee no
6314   // overflow here.
6315   APInt Offset = Step * MaxBECount;
6316 
6317   // Minimum value of the final range will match the minimal value of StartRange
6318   // if the expression is increasing and will be decreased by Offset otherwise.
6319   // Maximum value of the final range will match the maximal value of StartRange
6320   // if the expression is decreasing and will be increased by Offset otherwise.
6321   APInt StartLower = StartRange.getLower();
6322   APInt StartUpper = StartRange.getUpper() - 1;
6323   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6324                                    : (StartUpper + std::move(Offset));
6325 
6326   // It's possible that the new minimum/maximum value will fall into the initial
6327   // range (due to wrap around). This means that the expression can take any
6328   // value in this bitwidth, and we have to return full range.
6329   if (StartRange.contains(MovedBoundary))
6330     return ConstantRange::getFull(BitWidth);
6331 
6332   APInt NewLower =
6333       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6334   APInt NewUpper =
6335       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6336   NewUpper += 1;
6337 
6338   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6339   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6340 }
6341 
6342 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6343                                                    const SCEV *Step,
6344                                                    const SCEV *MaxBECount,
6345                                                    unsigned BitWidth) {
6346   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6347          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6348          "Precondition!");
6349 
6350   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6351   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6352 
6353   // First, consider step signed.
6354   ConstantRange StartSRange = getSignedRange(Start);
6355   ConstantRange StepSRange = getSignedRange(Step);
6356 
6357   // If Step can be both positive and negative, we need to find ranges for the
6358   // maximum absolute step values in both directions and union them.
6359   ConstantRange SR =
6360       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6361                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6362   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6363                                               StartSRange, MaxBECountValue,
6364                                               BitWidth, /* Signed = */ true));
6365 
6366   // Next, consider step unsigned.
6367   ConstantRange UR = getRangeForAffineARHelper(
6368       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6369       MaxBECountValue, BitWidth, /* Signed = */ false);
6370 
6371   // Finally, intersect signed and unsigned ranges.
6372   return SR.intersectWith(UR, ConstantRange::Smallest);
6373 }
6374 
6375 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6376     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6377     ScalarEvolution::RangeSignHint SignHint) {
6378   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6379   assert(AddRec->hasNoSelfWrap() &&
6380          "This only works for non-self-wrapping AddRecs!");
6381   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6382   const SCEV *Step = AddRec->getStepRecurrence(*this);
6383   // Only deal with constant step to save compile time.
6384   if (!isa<SCEVConstant>(Step))
6385     return ConstantRange::getFull(BitWidth);
6386   // Let's make sure that we can prove that we do not self-wrap during
6387   // MaxBECount iterations. We need this because MaxBECount is a maximum
6388   // iteration count estimate, and we might infer nw from some exit for which we
6389   // do not know max exit count (or any other side reasoning).
6390   // TODO: Turn into assert at some point.
6391   if (getTypeSizeInBits(MaxBECount->getType()) >
6392       getTypeSizeInBits(AddRec->getType()))
6393     return ConstantRange::getFull(BitWidth);
6394   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6395   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6396   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6397   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6398   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6399                                          MaxItersWithoutWrap))
6400     return ConstantRange::getFull(BitWidth);
6401 
6402   ICmpInst::Predicate LEPred =
6403       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6404   ICmpInst::Predicate GEPred =
6405       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6406   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6407 
6408   // We know that there is no self-wrap. Let's take Start and End values and
6409   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6410   // the iteration. They either lie inside the range [Min(Start, End),
6411   // Max(Start, End)] or outside it:
6412   //
6413   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6414   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6415   //
6416   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6417   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6418   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6419   // Start <= End and step is positive, or Start >= End and step is negative.
6420   const SCEV *Start = AddRec->getStart();
6421   ConstantRange StartRange = getRangeRef(Start, SignHint);
6422   ConstantRange EndRange = getRangeRef(End, SignHint);
6423   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6424   // If they already cover full iteration space, we will know nothing useful
6425   // even if we prove what we want to prove.
6426   if (RangeBetween.isFullSet())
6427     return RangeBetween;
6428   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6429   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6430                                : RangeBetween.isWrappedSet();
6431   if (IsWrappedSet)
6432     return ConstantRange::getFull(BitWidth);
6433 
6434   if (isKnownPositive(Step) &&
6435       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6436     return RangeBetween;
6437   else if (isKnownNegative(Step) &&
6438            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6439     return RangeBetween;
6440   return ConstantRange::getFull(BitWidth);
6441 }
6442 
6443 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6444                                                     const SCEV *Step,
6445                                                     const SCEV *MaxBECount,
6446                                                     unsigned BitWidth) {
6447   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6448   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6449 
6450   struct SelectPattern {
6451     Value *Condition = nullptr;
6452     APInt TrueValue;
6453     APInt FalseValue;
6454 
6455     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6456                            const SCEV *S) {
6457       Optional<unsigned> CastOp;
6458       APInt Offset(BitWidth, 0);
6459 
6460       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6461              "Should be!");
6462 
6463       // Peel off a constant offset:
6464       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6465         // In the future we could consider being smarter here and handle
6466         // {Start+Step,+,Step} too.
6467         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6468           return;
6469 
6470         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6471         S = SA->getOperand(1);
6472       }
6473 
6474       // Peel off a cast operation
6475       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6476         CastOp = SCast->getSCEVType();
6477         S = SCast->getOperand();
6478       }
6479 
6480       using namespace llvm::PatternMatch;
6481 
6482       auto *SU = dyn_cast<SCEVUnknown>(S);
6483       const APInt *TrueVal, *FalseVal;
6484       if (!SU ||
6485           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6486                                           m_APInt(FalseVal)))) {
6487         Condition = nullptr;
6488         return;
6489       }
6490 
6491       TrueValue = *TrueVal;
6492       FalseValue = *FalseVal;
6493 
6494       // Re-apply the cast we peeled off earlier
6495       if (CastOp.hasValue())
6496         switch (*CastOp) {
6497         default:
6498           llvm_unreachable("Unknown SCEV cast type!");
6499 
6500         case scTruncate:
6501           TrueValue = TrueValue.trunc(BitWidth);
6502           FalseValue = FalseValue.trunc(BitWidth);
6503           break;
6504         case scZeroExtend:
6505           TrueValue = TrueValue.zext(BitWidth);
6506           FalseValue = FalseValue.zext(BitWidth);
6507           break;
6508         case scSignExtend:
6509           TrueValue = TrueValue.sext(BitWidth);
6510           FalseValue = FalseValue.sext(BitWidth);
6511           break;
6512         }
6513 
6514       // Re-apply the constant offset we peeled off earlier
6515       TrueValue += Offset;
6516       FalseValue += Offset;
6517     }
6518 
6519     bool isRecognized() { return Condition != nullptr; }
6520   };
6521 
6522   SelectPattern StartPattern(*this, BitWidth, Start);
6523   if (!StartPattern.isRecognized())
6524     return ConstantRange::getFull(BitWidth);
6525 
6526   SelectPattern StepPattern(*this, BitWidth, Step);
6527   if (!StepPattern.isRecognized())
6528     return ConstantRange::getFull(BitWidth);
6529 
6530   if (StartPattern.Condition != StepPattern.Condition) {
6531     // We don't handle this case today; but we could, by considering four
6532     // possibilities below instead of two. I'm not sure if there are cases where
6533     // that will help over what getRange already does, though.
6534     return ConstantRange::getFull(BitWidth);
6535   }
6536 
6537   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6538   // construct arbitrary general SCEV expressions here.  This function is called
6539   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6540   // say) can end up caching a suboptimal value.
6541 
6542   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6543   // C2352 and C2512 (otherwise it isn't needed).
6544 
6545   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6546   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6547   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6548   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6549 
6550   ConstantRange TrueRange =
6551       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6552   ConstantRange FalseRange =
6553       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6554 
6555   return TrueRange.unionWith(FalseRange);
6556 }
6557 
6558 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6559   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6560   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6561 
6562   // Return early if there are no flags to propagate to the SCEV.
6563   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6564   if (BinOp->hasNoUnsignedWrap())
6565     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6566   if (BinOp->hasNoSignedWrap())
6567     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6568   if (Flags == SCEV::FlagAnyWrap)
6569     return SCEV::FlagAnyWrap;
6570 
6571   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6572 }
6573 
6574 const Instruction *
6575 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
6576   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
6577     return &*AddRec->getLoop()->getHeader()->begin();
6578   if (auto *U = dyn_cast<SCEVUnknown>(S))
6579     if (auto *I = dyn_cast<Instruction>(U->getValue()))
6580       return I;
6581   return nullptr;
6582 }
6583 
6584 /// Fills \p Ops with unique operands of \p S, if it has operands. If not,
6585 /// \p Ops remains unmodified.
6586 static void collectUniqueOps(const SCEV *S,
6587                              SmallVectorImpl<const SCEV *> &Ops) {
6588   SmallPtrSet<const SCEV *, 4> Unique;
6589   auto InsertUnique = [&](const SCEV *S) {
6590     if (Unique.insert(S).second)
6591       Ops.push_back(S);
6592   };
6593   if (auto *S2 = dyn_cast<SCEVCastExpr>(S))
6594     for (auto *Op : S2->operands())
6595       InsertUnique(Op);
6596   else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S))
6597     for (auto *Op : S2->operands())
6598       InsertUnique(Op);
6599   else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S))
6600     for (auto *Op : S2->operands())
6601       InsertUnique(Op);
6602 }
6603 
6604 const Instruction *
6605 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
6606                                        bool &Precise) {
6607   Precise = true;
6608   // Do a bounded search of the def relation of the requested SCEVs.
6609   SmallSet<const SCEV *, 16> Visited;
6610   SmallVector<const SCEV *> Worklist;
6611   auto pushOp = [&](const SCEV *S) {
6612     if (!Visited.insert(S).second)
6613       return;
6614     // Threshold of 30 here is arbitrary.
6615     if (Visited.size() > 30) {
6616       Precise = false;
6617       return;
6618     }
6619     Worklist.push_back(S);
6620   };
6621 
6622   for (auto *S : Ops)
6623     pushOp(S);
6624 
6625   const Instruction *Bound = nullptr;
6626   while (!Worklist.empty()) {
6627     auto *S = Worklist.pop_back_val();
6628     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
6629       if (!Bound || DT.dominates(Bound, DefI))
6630         Bound = DefI;
6631     } else {
6632       SmallVector<const SCEV *, 4> Ops;
6633       collectUniqueOps(S, Ops);
6634       for (auto *Op : Ops)
6635         pushOp(Op);
6636     }
6637   }
6638   return Bound ? Bound : &*F.getEntryBlock().begin();
6639 }
6640 
6641 const Instruction *
6642 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
6643   bool Discard;
6644   return getDefiningScopeBound(Ops, Discard);
6645 }
6646 
6647 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
6648                                                         const Instruction *B) {
6649   if (A->getParent() == B->getParent() &&
6650       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
6651                                                  B->getIterator()))
6652     return true;
6653 
6654   auto *BLoop = LI.getLoopFor(B->getParent());
6655   if (BLoop && BLoop->getHeader() == B->getParent() &&
6656       BLoop->getLoopPreheader() == A->getParent() &&
6657       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
6658                                                  A->getParent()->end()) &&
6659       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
6660                                                  B->getIterator()))
6661     return true;
6662   return false;
6663 }
6664 
6665 
6666 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6667   // Only proceed if we can prove that I does not yield poison.
6668   if (!programUndefinedIfPoison(I))
6669     return false;
6670 
6671   // At this point we know that if I is executed, then it does not wrap
6672   // according to at least one of NSW or NUW. If I is not executed, then we do
6673   // not know if the calculation that I represents would wrap. Multiple
6674   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6675   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6676   // derived from other instructions that map to the same SCEV. We cannot make
6677   // that guarantee for cases where I is not executed. So we need to find a
6678   // upper bound on the defining scope for the SCEV, and prove that I is
6679   // executed every time we enter that scope.  When the bounding scope is a
6680   // loop (the common case), this is equivalent to proving I executes on every
6681   // iteration of that loop.
6682   SmallVector<const SCEV *> SCEVOps;
6683   for (const Use &Op : I->operands()) {
6684     // I could be an extractvalue from a call to an overflow intrinsic.
6685     // TODO: We can do better here in some cases.
6686     if (isSCEVable(Op->getType()))
6687       SCEVOps.push_back(getSCEV(Op));
6688   }
6689   auto *DefI = getDefiningScopeBound(SCEVOps);
6690   return isGuaranteedToTransferExecutionTo(DefI, I);
6691 }
6692 
6693 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6694   // If we know that \c I can never be poison period, then that's enough.
6695   if (isSCEVExprNeverPoison(I))
6696     return true;
6697 
6698   // For an add recurrence specifically, we assume that infinite loops without
6699   // side effects are undefined behavior, and then reason as follows:
6700   //
6701   // If the add recurrence is poison in any iteration, it is poison on all
6702   // future iterations (since incrementing poison yields poison). If the result
6703   // of the add recurrence is fed into the loop latch condition and the loop
6704   // does not contain any throws or exiting blocks other than the latch, we now
6705   // have the ability to "choose" whether the backedge is taken or not (by
6706   // choosing a sufficiently evil value for the poison feeding into the branch)
6707   // for every iteration including and after the one in which \p I first became
6708   // poison.  There are two possibilities (let's call the iteration in which \p
6709   // I first became poison as K):
6710   //
6711   //  1. In the set of iterations including and after K, the loop body executes
6712   //     no side effects.  In this case executing the backege an infinte number
6713   //     of times will yield undefined behavior.
6714   //
6715   //  2. In the set of iterations including and after K, the loop body executes
6716   //     at least one side effect.  In this case, that specific instance of side
6717   //     effect is control dependent on poison, which also yields undefined
6718   //     behavior.
6719 
6720   auto *ExitingBB = L->getExitingBlock();
6721   auto *LatchBB = L->getLoopLatch();
6722   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6723     return false;
6724 
6725   SmallPtrSet<const Instruction *, 16> Pushed;
6726   SmallVector<const Instruction *, 8> PoisonStack;
6727 
6728   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6729   // things that are known to be poison under that assumption go on the
6730   // PoisonStack.
6731   Pushed.insert(I);
6732   PoisonStack.push_back(I);
6733 
6734   bool LatchControlDependentOnPoison = false;
6735   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6736     const Instruction *Poison = PoisonStack.pop_back_val();
6737 
6738     for (auto *PoisonUser : Poison->users()) {
6739       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6740         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6741           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6742       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6743         assert(BI->isConditional() && "Only possibility!");
6744         if (BI->getParent() == LatchBB) {
6745           LatchControlDependentOnPoison = true;
6746           break;
6747         }
6748       }
6749     }
6750   }
6751 
6752   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6753 }
6754 
6755 ScalarEvolution::LoopProperties
6756 ScalarEvolution::getLoopProperties(const Loop *L) {
6757   using LoopProperties = ScalarEvolution::LoopProperties;
6758 
6759   auto Itr = LoopPropertiesCache.find(L);
6760   if (Itr == LoopPropertiesCache.end()) {
6761     auto HasSideEffects = [](Instruction *I) {
6762       if (auto *SI = dyn_cast<StoreInst>(I))
6763         return !SI->isSimple();
6764 
6765       return I->mayThrow() || I->mayWriteToMemory();
6766     };
6767 
6768     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6769                          /*HasNoSideEffects*/ true};
6770 
6771     for (auto *BB : L->getBlocks())
6772       for (auto &I : *BB) {
6773         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6774           LP.HasNoAbnormalExits = false;
6775         if (HasSideEffects(&I))
6776           LP.HasNoSideEffects = false;
6777         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6778           break; // We're already as pessimistic as we can get.
6779       }
6780 
6781     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6782     assert(InsertPair.second && "We just checked!");
6783     Itr = InsertPair.first;
6784   }
6785 
6786   return Itr->second;
6787 }
6788 
6789 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
6790   // A mustprogress loop without side effects must be finite.
6791   // TODO: The check used here is very conservative.  It's only *specific*
6792   // side effects which are well defined in infinite loops.
6793   return isMustProgress(L) && loopHasNoSideEffects(L);
6794 }
6795 
6796 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6797   if (!isSCEVable(V->getType()))
6798     return getUnknown(V);
6799 
6800   if (Instruction *I = dyn_cast<Instruction>(V)) {
6801     // Don't attempt to analyze instructions in blocks that aren't
6802     // reachable. Such instructions don't matter, and they aren't required
6803     // to obey basic rules for definitions dominating uses which this
6804     // analysis depends on.
6805     if (!DT.isReachableFromEntry(I->getParent()))
6806       return getUnknown(UndefValue::get(V->getType()));
6807   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6808     return getConstant(CI);
6809   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6810     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6811   else if (!isa<ConstantExpr>(V))
6812     return getUnknown(V);
6813 
6814   Operator *U = cast<Operator>(V);
6815   if (auto BO = MatchBinaryOp(U, DT)) {
6816     switch (BO->Opcode) {
6817     case Instruction::Add: {
6818       // The simple thing to do would be to just call getSCEV on both operands
6819       // and call getAddExpr with the result. However if we're looking at a
6820       // bunch of things all added together, this can be quite inefficient,
6821       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6822       // Instead, gather up all the operands and make a single getAddExpr call.
6823       // LLVM IR canonical form means we need only traverse the left operands.
6824       SmallVector<const SCEV *, 4> AddOps;
6825       do {
6826         if (BO->Op) {
6827           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6828             AddOps.push_back(OpSCEV);
6829             break;
6830           }
6831 
6832           // If a NUW or NSW flag can be applied to the SCEV for this
6833           // addition, then compute the SCEV for this addition by itself
6834           // with a separate call to getAddExpr. We need to do that
6835           // instead of pushing the operands of the addition onto AddOps,
6836           // since the flags are only known to apply to this particular
6837           // addition - they may not apply to other additions that can be
6838           // formed with operands from AddOps.
6839           const SCEV *RHS = getSCEV(BO->RHS);
6840           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6841           if (Flags != SCEV::FlagAnyWrap) {
6842             const SCEV *LHS = getSCEV(BO->LHS);
6843             if (BO->Opcode == Instruction::Sub)
6844               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6845             else
6846               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6847             break;
6848           }
6849         }
6850 
6851         if (BO->Opcode == Instruction::Sub)
6852           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6853         else
6854           AddOps.push_back(getSCEV(BO->RHS));
6855 
6856         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6857         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6858                        NewBO->Opcode != Instruction::Sub)) {
6859           AddOps.push_back(getSCEV(BO->LHS));
6860           break;
6861         }
6862         BO = NewBO;
6863       } while (true);
6864 
6865       return getAddExpr(AddOps);
6866     }
6867 
6868     case Instruction::Mul: {
6869       SmallVector<const SCEV *, 4> MulOps;
6870       do {
6871         if (BO->Op) {
6872           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6873             MulOps.push_back(OpSCEV);
6874             break;
6875           }
6876 
6877           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6878           if (Flags != SCEV::FlagAnyWrap) {
6879             MulOps.push_back(
6880                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6881             break;
6882           }
6883         }
6884 
6885         MulOps.push_back(getSCEV(BO->RHS));
6886         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6887         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6888           MulOps.push_back(getSCEV(BO->LHS));
6889           break;
6890         }
6891         BO = NewBO;
6892       } while (true);
6893 
6894       return getMulExpr(MulOps);
6895     }
6896     case Instruction::UDiv:
6897       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6898     case Instruction::URem:
6899       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6900     case Instruction::Sub: {
6901       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6902       if (BO->Op)
6903         Flags = getNoWrapFlagsFromUB(BO->Op);
6904       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6905     }
6906     case Instruction::And:
6907       // For an expression like x&255 that merely masks off the high bits,
6908       // use zext(trunc(x)) as the SCEV expression.
6909       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6910         if (CI->isZero())
6911           return getSCEV(BO->RHS);
6912         if (CI->isMinusOne())
6913           return getSCEV(BO->LHS);
6914         const APInt &A = CI->getValue();
6915 
6916         // Instcombine's ShrinkDemandedConstant may strip bits out of
6917         // constants, obscuring what would otherwise be a low-bits mask.
6918         // Use computeKnownBits to compute what ShrinkDemandedConstant
6919         // knew about to reconstruct a low-bits mask value.
6920         unsigned LZ = A.countLeadingZeros();
6921         unsigned TZ = A.countTrailingZeros();
6922         unsigned BitWidth = A.getBitWidth();
6923         KnownBits Known(BitWidth);
6924         computeKnownBits(BO->LHS, Known, getDataLayout(),
6925                          0, &AC, nullptr, &DT);
6926 
6927         APInt EffectiveMask =
6928             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6929         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6930           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6931           const SCEV *LHS = getSCEV(BO->LHS);
6932           const SCEV *ShiftedLHS = nullptr;
6933           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6934             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6935               // For an expression like (x * 8) & 8, simplify the multiply.
6936               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6937               unsigned GCD = std::min(MulZeros, TZ);
6938               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6939               SmallVector<const SCEV*, 4> MulOps;
6940               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6941               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6942               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6943               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6944             }
6945           }
6946           if (!ShiftedLHS)
6947             ShiftedLHS = getUDivExpr(LHS, MulCount);
6948           return getMulExpr(
6949               getZeroExtendExpr(
6950                   getTruncateExpr(ShiftedLHS,
6951                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6952                   BO->LHS->getType()),
6953               MulCount);
6954         }
6955       }
6956       break;
6957 
6958     case Instruction::Or:
6959       // If the RHS of the Or is a constant, we may have something like:
6960       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6961       // optimizations will transparently handle this case.
6962       //
6963       // In order for this transformation to be safe, the LHS must be of the
6964       // form X*(2^n) and the Or constant must be less than 2^n.
6965       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6966         const SCEV *LHS = getSCEV(BO->LHS);
6967         const APInt &CIVal = CI->getValue();
6968         if (GetMinTrailingZeros(LHS) >=
6969             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6970           // Build a plain add SCEV.
6971           return getAddExpr(LHS, getSCEV(CI),
6972                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6973         }
6974       }
6975       break;
6976 
6977     case Instruction::Xor:
6978       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6979         // If the RHS of xor is -1, then this is a not operation.
6980         if (CI->isMinusOne())
6981           return getNotSCEV(getSCEV(BO->LHS));
6982 
6983         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6984         // This is a variant of the check for xor with -1, and it handles
6985         // the case where instcombine has trimmed non-demanded bits out
6986         // of an xor with -1.
6987         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6988           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6989             if (LBO->getOpcode() == Instruction::And &&
6990                 LCI->getValue() == CI->getValue())
6991               if (const SCEVZeroExtendExpr *Z =
6992                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6993                 Type *UTy = BO->LHS->getType();
6994                 const SCEV *Z0 = Z->getOperand();
6995                 Type *Z0Ty = Z0->getType();
6996                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6997 
6998                 // If C is a low-bits mask, the zero extend is serving to
6999                 // mask off the high bits. Complement the operand and
7000                 // re-apply the zext.
7001                 if (CI->getValue().isMask(Z0TySize))
7002                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7003 
7004                 // If C is a single bit, it may be in the sign-bit position
7005                 // before the zero-extend. In this case, represent the xor
7006                 // using an add, which is equivalent, and re-apply the zext.
7007                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7008                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7009                     Trunc.isSignMask())
7010                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7011                                            UTy);
7012               }
7013       }
7014       break;
7015 
7016     case Instruction::Shl:
7017       // Turn shift left of a constant amount into a multiply.
7018       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7019         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7020 
7021         // If the shift count is not less than the bitwidth, the result of
7022         // the shift is undefined. Don't try to analyze it, because the
7023         // resolution chosen here may differ from the resolution chosen in
7024         // other parts of the compiler.
7025         if (SA->getValue().uge(BitWidth))
7026           break;
7027 
7028         // We can safely preserve the nuw flag in all cases. It's also safe to
7029         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7030         // requires special handling. It can be preserved as long as we're not
7031         // left shifting by bitwidth - 1.
7032         auto Flags = SCEV::FlagAnyWrap;
7033         if (BO->Op) {
7034           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7035           if ((MulFlags & SCEV::FlagNSW) &&
7036               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7037             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7038           if (MulFlags & SCEV::FlagNUW)
7039             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7040         }
7041 
7042         Constant *X = ConstantInt::get(
7043             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7044         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
7045       }
7046       break;
7047 
7048     case Instruction::AShr: {
7049       // AShr X, C, where C is a constant.
7050       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7051       if (!CI)
7052         break;
7053 
7054       Type *OuterTy = BO->LHS->getType();
7055       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7056       // If the shift count is not less than the bitwidth, the result of
7057       // the shift is undefined. Don't try to analyze it, because the
7058       // resolution chosen here may differ from the resolution chosen in
7059       // other parts of the compiler.
7060       if (CI->getValue().uge(BitWidth))
7061         break;
7062 
7063       if (CI->isZero())
7064         return getSCEV(BO->LHS); // shift by zero --> noop
7065 
7066       uint64_t AShrAmt = CI->getZExtValue();
7067       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7068 
7069       Operator *L = dyn_cast<Operator>(BO->LHS);
7070       if (L && L->getOpcode() == Instruction::Shl) {
7071         // X = Shl A, n
7072         // Y = AShr X, m
7073         // Both n and m are constant.
7074 
7075         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7076         if (L->getOperand(1) == BO->RHS)
7077           // For a two-shift sext-inreg, i.e. n = m,
7078           // use sext(trunc(x)) as the SCEV expression.
7079           return getSignExtendExpr(
7080               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7081 
7082         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7083         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7084           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7085           if (ShlAmt > AShrAmt) {
7086             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7087             // expression. We already checked that ShlAmt < BitWidth, so
7088             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7089             // ShlAmt - AShrAmt < Amt.
7090             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7091                                             ShlAmt - AShrAmt);
7092             return getSignExtendExpr(
7093                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7094                 getConstant(Mul)), OuterTy);
7095           }
7096         }
7097       }
7098       break;
7099     }
7100     }
7101   }
7102 
7103   switch (U->getOpcode()) {
7104   case Instruction::Trunc:
7105     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7106 
7107   case Instruction::ZExt:
7108     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7109 
7110   case Instruction::SExt:
7111     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7112       // The NSW flag of a subtract does not always survive the conversion to
7113       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7114       // more likely to preserve NSW and allow later AddRec optimisations.
7115       //
7116       // NOTE: This is effectively duplicating this logic from getSignExtend:
7117       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7118       // but by that point the NSW information has potentially been lost.
7119       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7120         Type *Ty = U->getType();
7121         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7122         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7123         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7124       }
7125     }
7126     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7127 
7128   case Instruction::BitCast:
7129     // BitCasts are no-op casts so we just eliminate the cast.
7130     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7131       return getSCEV(U->getOperand(0));
7132     break;
7133 
7134   case Instruction::PtrToInt: {
7135     // Pointer to integer cast is straight-forward, so do model it.
7136     const SCEV *Op = getSCEV(U->getOperand(0));
7137     Type *DstIntTy = U->getType();
7138     // But only if effective SCEV (integer) type is wide enough to represent
7139     // all possible pointer values.
7140     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7141     if (isa<SCEVCouldNotCompute>(IntOp))
7142       return getUnknown(V);
7143     return IntOp;
7144   }
7145   case Instruction::IntToPtr:
7146     // Just don't deal with inttoptr casts.
7147     return getUnknown(V);
7148 
7149   case Instruction::SDiv:
7150     // If both operands are non-negative, this is just an udiv.
7151     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7152         isKnownNonNegative(getSCEV(U->getOperand(1))))
7153       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7154     break;
7155 
7156   case Instruction::SRem:
7157     // If both operands are non-negative, this is just an urem.
7158     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7159         isKnownNonNegative(getSCEV(U->getOperand(1))))
7160       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7161     break;
7162 
7163   case Instruction::GetElementPtr:
7164     return createNodeForGEP(cast<GEPOperator>(U));
7165 
7166   case Instruction::PHI:
7167     return createNodeForPHI(cast<PHINode>(U));
7168 
7169   case Instruction::Select:
7170     // U can also be a select constant expr, which let fall through.  Since
7171     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
7172     // constant expressions cannot have instructions as operands, we'd have
7173     // returned getUnknown for a select constant expressions anyway.
7174     if (isa<Instruction>(U))
7175       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
7176                                       U->getOperand(1), U->getOperand(2));
7177     break;
7178 
7179   case Instruction::Call:
7180   case Instruction::Invoke:
7181     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7182       return getSCEV(RV);
7183 
7184     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7185       switch (II->getIntrinsicID()) {
7186       case Intrinsic::abs:
7187         return getAbsExpr(
7188             getSCEV(II->getArgOperand(0)),
7189             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7190       case Intrinsic::umax:
7191         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7192                            getSCEV(II->getArgOperand(1)));
7193       case Intrinsic::umin:
7194         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7195                            getSCEV(II->getArgOperand(1)));
7196       case Intrinsic::smax:
7197         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7198                            getSCEV(II->getArgOperand(1)));
7199       case Intrinsic::smin:
7200         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7201                            getSCEV(II->getArgOperand(1)));
7202       case Intrinsic::usub_sat: {
7203         const SCEV *X = getSCEV(II->getArgOperand(0));
7204         const SCEV *Y = getSCEV(II->getArgOperand(1));
7205         const SCEV *ClampedY = getUMinExpr(X, Y);
7206         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7207       }
7208       case Intrinsic::uadd_sat: {
7209         const SCEV *X = getSCEV(II->getArgOperand(0));
7210         const SCEV *Y = getSCEV(II->getArgOperand(1));
7211         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7212         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7213       }
7214       case Intrinsic::start_loop_iterations:
7215         // A start_loop_iterations is just equivalent to the first operand for
7216         // SCEV purposes.
7217         return getSCEV(II->getArgOperand(0));
7218       default:
7219         break;
7220       }
7221     }
7222     break;
7223   }
7224 
7225   return getUnknown(V);
7226 }
7227 
7228 //===----------------------------------------------------------------------===//
7229 //                   Iteration Count Computation Code
7230 //
7231 
7232 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
7233                                                        bool Extend) {
7234   if (isa<SCEVCouldNotCompute>(ExitCount))
7235     return getCouldNotCompute();
7236 
7237   auto *ExitCountType = ExitCount->getType();
7238   assert(ExitCountType->isIntegerTy());
7239 
7240   if (!Extend)
7241     return getAddExpr(ExitCount, getOne(ExitCountType));
7242 
7243   auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
7244                                     1 + ExitCountType->getScalarSizeInBits());
7245   return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
7246                     getOne(WiderType));
7247 }
7248 
7249 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7250   if (!ExitCount)
7251     return 0;
7252 
7253   ConstantInt *ExitConst = ExitCount->getValue();
7254 
7255   // Guard against huge trip counts.
7256   if (ExitConst->getValue().getActiveBits() > 32)
7257     return 0;
7258 
7259   // In case of integer overflow, this returns 0, which is correct.
7260   return ((unsigned)ExitConst->getZExtValue()) + 1;
7261 }
7262 
7263 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7264   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7265   return getConstantTripCount(ExitCount);
7266 }
7267 
7268 unsigned
7269 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7270                                            const BasicBlock *ExitingBlock) {
7271   assert(ExitingBlock && "Must pass a non-null exiting block!");
7272   assert(L->isLoopExiting(ExitingBlock) &&
7273          "Exiting block must actually branch out of the loop!");
7274   const SCEVConstant *ExitCount =
7275       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7276   return getConstantTripCount(ExitCount);
7277 }
7278 
7279 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7280   const auto *MaxExitCount =
7281       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7282   return getConstantTripCount(MaxExitCount);
7283 }
7284 
7285 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
7286   // We can't infer from Array in Irregular Loop.
7287   // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
7288   if (!L->isLoopSimplifyForm() || !L->isInnermost())
7289     return getCouldNotCompute();
7290 
7291   // FIXME: To make the scene more typical, we only analysis loops that have
7292   // one exiting block and that block must be the latch. To make it easier to
7293   // capture loops that have memory access and memory access will be executed
7294   // in each iteration.
7295   const BasicBlock *LoopLatch = L->getLoopLatch();
7296   assert(LoopLatch && "See defination of simplify form loop.");
7297   if (L->getExitingBlock() != LoopLatch)
7298     return getCouldNotCompute();
7299 
7300   const DataLayout &DL = getDataLayout();
7301   SmallVector<const SCEV *> InferCountColl;
7302   for (auto *BB : L->getBlocks()) {
7303     // Go here, we can know that Loop is a single exiting and simplified form
7304     // loop. Make sure that infer from Memory Operation in those BBs must be
7305     // executed in loop. First step, we can make sure that max execution time
7306     // of MemAccessBB in loop represents latch max excution time.
7307     // If MemAccessBB does not dom Latch, skip.
7308     //            Entry
7309     //              │
7310     //        ┌─────▼─────┐
7311     //        │Loop Header◄─────┐
7312     //        └──┬──────┬─┘     │
7313     //           │      │       │
7314     //  ┌────────▼──┐ ┌─▼─────┐ │
7315     //  │MemAccessBB│ │OtherBB│ │
7316     //  └────────┬──┘ └─┬─────┘ │
7317     //           │      │       │
7318     //         ┌─▼──────▼─┐     │
7319     //         │Loop Latch├─────┘
7320     //         └────┬─────┘
7321     //              ▼
7322     //             Exit
7323     if (!DT.dominates(BB, LoopLatch))
7324       continue;
7325 
7326     for (Instruction &Inst : *BB) {
7327       // Find Memory Operation Instruction.
7328       auto *GEP = getLoadStorePointerOperand(&Inst);
7329       if (!GEP)
7330         continue;
7331 
7332       auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
7333       // Do not infer from scalar type, eg."ElemSize = sizeof()".
7334       if (!ElemSize)
7335         continue;
7336 
7337       // Use a existing polynomial recurrence on the trip count.
7338       auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
7339       if (!AddRec)
7340         continue;
7341       auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
7342       auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
7343       if (!ArrBase || !Step)
7344         continue;
7345       assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
7346 
7347       // Only handle { %array + step },
7348       // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
7349       if (AddRec->getStart() != ArrBase)
7350         continue;
7351 
7352       // Memory operation pattern which have gaps.
7353       // Or repeat memory opreation.
7354       // And index of GEP wraps arround.
7355       if (Step->getAPInt().getActiveBits() > 32 ||
7356           Step->getAPInt().getZExtValue() !=
7357               ElemSize->getAPInt().getZExtValue() ||
7358           Step->isZero() || Step->getAPInt().isNegative())
7359         continue;
7360 
7361       // Only infer from stack array which has certain size.
7362       // Make sure alloca instruction is not excuted in loop.
7363       AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
7364       if (!AllocateInst || L->contains(AllocateInst->getParent()))
7365         continue;
7366 
7367       // Make sure only handle normal array.
7368       auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
7369       auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
7370       if (!Ty || !ArrSize || !ArrSize->isOne())
7371         continue;
7372       // Also make sure step was increased the same with sizeof allocated
7373       // element type.
7374       const PointerType *GEPT = dyn_cast<PointerType>(GEP->getType());
7375       if (Ty->getElementType() != GEPT->getElementType())
7376         continue;
7377 
7378       // FIXME: Since gep indices are silently zext to the indexing type,
7379       // we will have a narrow gep index which wraps around rather than
7380       // increasing strictly, we shoule ensure that step is increasing
7381       // strictly by the loop iteration.
7382       // Now we can infer a max execution time by MemLength/StepLength.
7383       const SCEV *MemSize =
7384           getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
7385       auto *MaxExeCount =
7386           dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
7387       if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
7388         continue;
7389 
7390       // If the loop reaches the maximum number of executions, we can not
7391       // access bytes starting outside the statically allocated size without
7392       // being immediate UB. But it is allowed to enter loop header one more
7393       // time.
7394       auto *InferCount = dyn_cast<SCEVConstant>(
7395           getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
7396       // Discard the maximum number of execution times under 32bits.
7397       if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
7398         continue;
7399 
7400       InferCountColl.push_back(InferCount);
7401     }
7402   }
7403 
7404   if (InferCountColl.size() == 0)
7405     return getCouldNotCompute();
7406 
7407   return getUMinFromMismatchedTypes(InferCountColl);
7408 }
7409 
7410 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7411   SmallVector<BasicBlock *, 8> ExitingBlocks;
7412   L->getExitingBlocks(ExitingBlocks);
7413 
7414   Optional<unsigned> Res = None;
7415   for (auto *ExitingBB : ExitingBlocks) {
7416     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7417     if (!Res)
7418       Res = Multiple;
7419     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7420   }
7421   return Res.getValueOr(1);
7422 }
7423 
7424 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7425                                                        const SCEV *ExitCount) {
7426   if (ExitCount == getCouldNotCompute())
7427     return 1;
7428 
7429   // Get the trip count
7430   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7431 
7432   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7433   if (!TC)
7434     // Attempt to factor more general cases. Returns the greatest power of
7435     // two divisor. If overflow happens, the trip count expression is still
7436     // divisible by the greatest power of 2 divisor returned.
7437     return 1U << std::min((uint32_t)31,
7438                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7439 
7440   ConstantInt *Result = TC->getValue();
7441 
7442   // Guard against huge trip counts (this requires checking
7443   // for zero to handle the case where the trip count == -1 and the
7444   // addition wraps).
7445   if (!Result || Result->getValue().getActiveBits() > 32 ||
7446       Result->getValue().getActiveBits() == 0)
7447     return 1;
7448 
7449   return (unsigned)Result->getZExtValue();
7450 }
7451 
7452 /// Returns the largest constant divisor of the trip count of this loop as a
7453 /// normal unsigned value, if possible. This means that the actual trip count is
7454 /// always a multiple of the returned value (don't forget the trip count could
7455 /// very well be zero as well!).
7456 ///
7457 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7458 /// multiple of a constant (which is also the case if the trip count is simply
7459 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7460 /// if the trip count is very large (>= 2^32).
7461 ///
7462 /// As explained in the comments for getSmallConstantTripCount, this assumes
7463 /// that control exits the loop via ExitingBlock.
7464 unsigned
7465 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7466                                               const BasicBlock *ExitingBlock) {
7467   assert(ExitingBlock && "Must pass a non-null exiting block!");
7468   assert(L->isLoopExiting(ExitingBlock) &&
7469          "Exiting block must actually branch out of the loop!");
7470   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7471   return getSmallConstantTripMultiple(L, ExitCount);
7472 }
7473 
7474 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7475                                           const BasicBlock *ExitingBlock,
7476                                           ExitCountKind Kind) {
7477   switch (Kind) {
7478   case Exact:
7479   case SymbolicMaximum:
7480     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7481   case ConstantMaximum:
7482     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7483   };
7484   llvm_unreachable("Invalid ExitCountKind!");
7485 }
7486 
7487 const SCEV *
7488 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7489                                                  SCEVUnionPredicate &Preds) {
7490   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7491 }
7492 
7493 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7494                                                    ExitCountKind Kind) {
7495   switch (Kind) {
7496   case Exact:
7497     return getBackedgeTakenInfo(L).getExact(L, this);
7498   case ConstantMaximum:
7499     return getBackedgeTakenInfo(L).getConstantMax(this);
7500   case SymbolicMaximum:
7501     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7502   };
7503   llvm_unreachable("Invalid ExitCountKind!");
7504 }
7505 
7506 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7507   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7508 }
7509 
7510 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7511 static void PushLoopPHIs(const Loop *L,
7512                          SmallVectorImpl<Instruction *> &Worklist,
7513                          SmallPtrSetImpl<Instruction *> &Visited) {
7514   BasicBlock *Header = L->getHeader();
7515 
7516   // Push all Loop-header PHIs onto the Worklist stack.
7517   for (PHINode &PN : Header->phis())
7518     if (Visited.insert(&PN).second)
7519       Worklist.push_back(&PN);
7520 }
7521 
7522 const ScalarEvolution::BackedgeTakenInfo &
7523 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7524   auto &BTI = getBackedgeTakenInfo(L);
7525   if (BTI.hasFullInfo())
7526     return BTI;
7527 
7528   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7529 
7530   if (!Pair.second)
7531     return Pair.first->second;
7532 
7533   BackedgeTakenInfo Result =
7534       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7535 
7536   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7537 }
7538 
7539 ScalarEvolution::BackedgeTakenInfo &
7540 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7541   // Initially insert an invalid entry for this loop. If the insertion
7542   // succeeds, proceed to actually compute a backedge-taken count and
7543   // update the value. The temporary CouldNotCompute value tells SCEV
7544   // code elsewhere that it shouldn't attempt to request a new
7545   // backedge-taken count, which could result in infinite recursion.
7546   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7547       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7548   if (!Pair.second)
7549     return Pair.first->second;
7550 
7551   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7552   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7553   // must be cleared in this scope.
7554   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7555 
7556   // In product build, there are no usage of statistic.
7557   (void)NumTripCountsComputed;
7558   (void)NumTripCountsNotComputed;
7559 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7560   const SCEV *BEExact = Result.getExact(L, this);
7561   if (BEExact != getCouldNotCompute()) {
7562     assert(isLoopInvariant(BEExact, L) &&
7563            isLoopInvariant(Result.getConstantMax(this), L) &&
7564            "Computed backedge-taken count isn't loop invariant for loop!");
7565     ++NumTripCountsComputed;
7566   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7567              isa<PHINode>(L->getHeader()->begin())) {
7568     // Only count loops that have phi nodes as not being computable.
7569     ++NumTripCountsNotComputed;
7570   }
7571 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7572 
7573   // Now that we know more about the trip count for this loop, forget any
7574   // existing SCEV values for PHI nodes in this loop since they are only
7575   // conservative estimates made without the benefit of trip count
7576   // information. This invalidation is not necessary for correctness, and is
7577   // only done to produce more precise results.
7578   if (Result.hasAnyInfo()) {
7579     // Invalidate any expression using an addrec in this loop.
7580     SmallVector<const SCEV *, 8> ToForget;
7581     auto LoopUsersIt = LoopUsers.find(L);
7582     if (LoopUsersIt != LoopUsers.end())
7583       append_range(ToForget, LoopUsersIt->second);
7584     forgetMemoizedResults(ToForget);
7585 
7586     // Invalidate constant-evolved loop header phis.
7587     for (PHINode &PN : L->getHeader()->phis())
7588       ConstantEvolutionLoopExitValue.erase(&PN);
7589   }
7590 
7591   // Re-lookup the insert position, since the call to
7592   // computeBackedgeTakenCount above could result in a
7593   // recusive call to getBackedgeTakenInfo (on a different
7594   // loop), which would invalidate the iterator computed
7595   // earlier.
7596   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7597 }
7598 
7599 void ScalarEvolution::forgetAllLoops() {
7600   // This method is intended to forget all info about loops. It should
7601   // invalidate caches as if the following happened:
7602   // - The trip counts of all loops have changed arbitrarily
7603   // - Every llvm::Value has been updated in place to produce a different
7604   // result.
7605   BackedgeTakenCounts.clear();
7606   PredicatedBackedgeTakenCounts.clear();
7607   LoopPropertiesCache.clear();
7608   ConstantEvolutionLoopExitValue.clear();
7609   ValueExprMap.clear();
7610   ValuesAtScopes.clear();
7611   LoopDispositions.clear();
7612   BlockDispositions.clear();
7613   UnsignedRanges.clear();
7614   SignedRanges.clear();
7615   ExprValueMap.clear();
7616   HasRecMap.clear();
7617   MinTrailingZerosCache.clear();
7618   PredicatedSCEVRewrites.clear();
7619 }
7620 
7621 void ScalarEvolution::forgetLoop(const Loop *L) {
7622   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7623   SmallVector<Instruction *, 32> Worklist;
7624   SmallPtrSet<Instruction *, 16> Visited;
7625   SmallVector<const SCEV *, 16> ToForget;
7626 
7627   // Iterate over all the loops and sub-loops to drop SCEV information.
7628   while (!LoopWorklist.empty()) {
7629     auto *CurrL = LoopWorklist.pop_back_val();
7630 
7631     // Drop any stored trip count value.
7632     BackedgeTakenCounts.erase(CurrL);
7633     PredicatedBackedgeTakenCounts.erase(CurrL);
7634 
7635     // Drop information about predicated SCEV rewrites for this loop.
7636     for (auto I = PredicatedSCEVRewrites.begin();
7637          I != PredicatedSCEVRewrites.end();) {
7638       std::pair<const SCEV *, const Loop *> Entry = I->first;
7639       if (Entry.second == CurrL)
7640         PredicatedSCEVRewrites.erase(I++);
7641       else
7642         ++I;
7643     }
7644 
7645     auto LoopUsersItr = LoopUsers.find(CurrL);
7646     if (LoopUsersItr != LoopUsers.end()) {
7647       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
7648                 LoopUsersItr->second.end());
7649       LoopUsers.erase(LoopUsersItr);
7650     }
7651 
7652     // Drop information about expressions based on loop-header PHIs.
7653     PushLoopPHIs(CurrL, Worklist, Visited);
7654 
7655     while (!Worklist.empty()) {
7656       Instruction *I = Worklist.pop_back_val();
7657 
7658       ValueExprMapType::iterator It =
7659           ValueExprMap.find_as(static_cast<Value *>(I));
7660       if (It != ValueExprMap.end()) {
7661         eraseValueFromMap(It->first);
7662         ToForget.push_back(It->second);
7663         if (PHINode *PN = dyn_cast<PHINode>(I))
7664           ConstantEvolutionLoopExitValue.erase(PN);
7665       }
7666 
7667       PushDefUseChildren(I, Worklist, Visited);
7668     }
7669 
7670     LoopPropertiesCache.erase(CurrL);
7671     // Forget all contained loops too, to avoid dangling entries in the
7672     // ValuesAtScopes map.
7673     LoopWorklist.append(CurrL->begin(), CurrL->end());
7674   }
7675   forgetMemoizedResults(ToForget);
7676 }
7677 
7678 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7679   while (Loop *Parent = L->getParentLoop())
7680     L = Parent;
7681   forgetLoop(L);
7682 }
7683 
7684 void ScalarEvolution::forgetValue(Value *V) {
7685   Instruction *I = dyn_cast<Instruction>(V);
7686   if (!I) return;
7687 
7688   // Drop information about expressions based on loop-header PHIs.
7689   SmallVector<Instruction *, 16> Worklist;
7690   SmallPtrSet<Instruction *, 8> Visited;
7691   SmallVector<const SCEV *, 8> ToForget;
7692   Worklist.push_back(I);
7693   Visited.insert(I);
7694 
7695   while (!Worklist.empty()) {
7696     I = Worklist.pop_back_val();
7697     ValueExprMapType::iterator It =
7698       ValueExprMap.find_as(static_cast<Value *>(I));
7699     if (It != ValueExprMap.end()) {
7700       eraseValueFromMap(It->first);
7701       ToForget.push_back(It->second);
7702       if (PHINode *PN = dyn_cast<PHINode>(I))
7703         ConstantEvolutionLoopExitValue.erase(PN);
7704     }
7705 
7706     PushDefUseChildren(I, Worklist, Visited);
7707   }
7708   forgetMemoizedResults(ToForget);
7709 }
7710 
7711 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7712   LoopDispositions.clear();
7713 }
7714 
7715 /// Get the exact loop backedge taken count considering all loop exits. A
7716 /// computable result can only be returned for loops with all exiting blocks
7717 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7718 /// is never skipped. This is a valid assumption as long as the loop exits via
7719 /// that test. For precise results, it is the caller's responsibility to specify
7720 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7721 const SCEV *
7722 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7723                                              SCEVUnionPredicate *Preds) const {
7724   // If any exits were not computable, the loop is not computable.
7725   if (!isComplete() || ExitNotTaken.empty())
7726     return SE->getCouldNotCompute();
7727 
7728   const BasicBlock *Latch = L->getLoopLatch();
7729   // All exiting blocks we have collected must dominate the only backedge.
7730   if (!Latch)
7731     return SE->getCouldNotCompute();
7732 
7733   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7734   // count is simply a minimum out of all these calculated exit counts.
7735   SmallVector<const SCEV *, 2> Ops;
7736   for (auto &ENT : ExitNotTaken) {
7737     const SCEV *BECount = ENT.ExactNotTaken;
7738     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7739     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7740            "We should only have known counts for exiting blocks that dominate "
7741            "latch!");
7742 
7743     Ops.push_back(BECount);
7744 
7745     if (Preds && !ENT.hasAlwaysTruePredicate())
7746       Preds->add(ENT.Predicate.get());
7747 
7748     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7749            "Predicate should be always true!");
7750   }
7751 
7752   return SE->getUMinFromMismatchedTypes(Ops);
7753 }
7754 
7755 /// Get the exact not taken count for this loop exit.
7756 const SCEV *
7757 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7758                                              ScalarEvolution *SE) const {
7759   for (auto &ENT : ExitNotTaken)
7760     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7761       return ENT.ExactNotTaken;
7762 
7763   return SE->getCouldNotCompute();
7764 }
7765 
7766 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7767     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7768   for (auto &ENT : ExitNotTaken)
7769     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7770       return ENT.MaxNotTaken;
7771 
7772   return SE->getCouldNotCompute();
7773 }
7774 
7775 /// getConstantMax - Get the constant max backedge taken count for the loop.
7776 const SCEV *
7777 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7778   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7779     return !ENT.hasAlwaysTruePredicate();
7780   };
7781 
7782   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
7783     return SE->getCouldNotCompute();
7784 
7785   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7786           isa<SCEVConstant>(getConstantMax())) &&
7787          "No point in having a non-constant max backedge taken count!");
7788   return getConstantMax();
7789 }
7790 
7791 const SCEV *
7792 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7793                                                    ScalarEvolution *SE) {
7794   if (!SymbolicMax)
7795     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7796   return SymbolicMax;
7797 }
7798 
7799 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7800     ScalarEvolution *SE) const {
7801   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7802     return !ENT.hasAlwaysTruePredicate();
7803   };
7804   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7805 }
7806 
7807 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const {
7808   return Operands.contains(S);
7809 }
7810 
7811 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7812     : ExitLimit(E, E, false, None) {
7813 }
7814 
7815 ScalarEvolution::ExitLimit::ExitLimit(
7816     const SCEV *E, const SCEV *M, bool MaxOrZero,
7817     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7818     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7819   // If we prove the max count is zero, so is the symbolic bound.  This happens
7820   // in practice due to differences in a) how context sensitive we've chosen
7821   // to be and b) how we reason about bounds impied by UB.
7822   if (MaxNotTaken->isZero())
7823     ExactNotTaken = MaxNotTaken;
7824 
7825   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7826           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7827          "Exact is not allowed to be less precise than Max");
7828   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7829           isa<SCEVConstant>(MaxNotTaken)) &&
7830          "No point in having a non-constant max backedge taken count!");
7831   for (auto *PredSet : PredSetList)
7832     for (auto *P : *PredSet)
7833       addPredicate(P);
7834   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
7835          "Backedge count should be int");
7836   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
7837          "Max backedge count should be int");
7838 }
7839 
7840 ScalarEvolution::ExitLimit::ExitLimit(
7841     const SCEV *E, const SCEV *M, bool MaxOrZero,
7842     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7843     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7844 }
7845 
7846 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7847                                       bool MaxOrZero)
7848     : ExitLimit(E, M, MaxOrZero, None) {
7849 }
7850 
7851 class SCEVRecordOperands {
7852   SmallPtrSetImpl<const SCEV *> &Operands;
7853 
7854 public:
7855   SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands)
7856     : Operands(Operands) {}
7857   bool follow(const SCEV *S) {
7858     Operands.insert(S);
7859     return true;
7860   }
7861   bool isDone() { return false; }
7862 };
7863 
7864 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7865 /// computable exit into a persistent ExitNotTakenInfo array.
7866 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7867     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7868     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7869     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7870   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7871 
7872   ExitNotTaken.reserve(ExitCounts.size());
7873   std::transform(
7874       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7875       [&](const EdgeExitInfo &EEI) {
7876         BasicBlock *ExitBB = EEI.first;
7877         const ExitLimit &EL = EEI.second;
7878         if (EL.Predicates.empty())
7879           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7880                                   nullptr);
7881 
7882         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7883         for (auto *Pred : EL.Predicates)
7884           Predicate->add(Pred);
7885 
7886         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7887                                 std::move(Predicate));
7888       });
7889   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7890           isa<SCEVConstant>(ConstantMax)) &&
7891          "No point in having a non-constant max backedge taken count!");
7892 
7893   SCEVRecordOperands RecordOperands(Operands);
7894   SCEVTraversal<SCEVRecordOperands> ST(RecordOperands);
7895   if (!isa<SCEVCouldNotCompute>(ConstantMax))
7896     ST.visitAll(ConstantMax);
7897   for (auto &ENT : ExitNotTaken)
7898     if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken))
7899       ST.visitAll(ENT.ExactNotTaken);
7900 }
7901 
7902 /// Compute the number of times the backedge of the specified loop will execute.
7903 ScalarEvolution::BackedgeTakenInfo
7904 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7905                                            bool AllowPredicates) {
7906   SmallVector<BasicBlock *, 8> ExitingBlocks;
7907   L->getExitingBlocks(ExitingBlocks);
7908 
7909   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7910 
7911   SmallVector<EdgeExitInfo, 4> ExitCounts;
7912   bool CouldComputeBECount = true;
7913   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7914   const SCEV *MustExitMaxBECount = nullptr;
7915   const SCEV *MayExitMaxBECount = nullptr;
7916   bool MustExitMaxOrZero = false;
7917 
7918   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7919   // and compute maxBECount.
7920   // Do a union of all the predicates here.
7921   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7922     BasicBlock *ExitBB = ExitingBlocks[i];
7923 
7924     // We canonicalize untaken exits to br (constant), ignore them so that
7925     // proving an exit untaken doesn't negatively impact our ability to reason
7926     // about the loop as whole.
7927     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7928       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7929         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7930         if (ExitIfTrue == CI->isZero())
7931           continue;
7932       }
7933 
7934     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7935 
7936     assert((AllowPredicates || EL.Predicates.empty()) &&
7937            "Predicated exit limit when predicates are not allowed!");
7938 
7939     // 1. For each exit that can be computed, add an entry to ExitCounts.
7940     // CouldComputeBECount is true only if all exits can be computed.
7941     if (EL.ExactNotTaken == getCouldNotCompute())
7942       // We couldn't compute an exact value for this exit, so
7943       // we won't be able to compute an exact value for the loop.
7944       CouldComputeBECount = false;
7945     else
7946       ExitCounts.emplace_back(ExitBB, EL);
7947 
7948     // 2. Derive the loop's MaxBECount from each exit's max number of
7949     // non-exiting iterations. Partition the loop exits into two kinds:
7950     // LoopMustExits and LoopMayExits.
7951     //
7952     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7953     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7954     // MaxBECount is the minimum EL.MaxNotTaken of computable
7955     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7956     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7957     // computable EL.MaxNotTaken.
7958     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7959         DT.dominates(ExitBB, Latch)) {
7960       if (!MustExitMaxBECount) {
7961         MustExitMaxBECount = EL.MaxNotTaken;
7962         MustExitMaxOrZero = EL.MaxOrZero;
7963       } else {
7964         MustExitMaxBECount =
7965             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7966       }
7967     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7968       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7969         MayExitMaxBECount = EL.MaxNotTaken;
7970       else {
7971         MayExitMaxBECount =
7972             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7973       }
7974     }
7975   }
7976   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7977     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7978   // The loop backedge will be taken the maximum or zero times if there's
7979   // a single exit that must be taken the maximum or zero times.
7980   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7981   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7982                            MaxBECount, MaxOrZero);
7983 }
7984 
7985 ScalarEvolution::ExitLimit
7986 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7987                                       bool AllowPredicates) {
7988   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7989   // If our exiting block does not dominate the latch, then its connection with
7990   // loop's exit limit may be far from trivial.
7991   const BasicBlock *Latch = L->getLoopLatch();
7992   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7993     return getCouldNotCompute();
7994 
7995   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7996   Instruction *Term = ExitingBlock->getTerminator();
7997   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7998     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7999     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8000     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8001            "It should have one successor in loop and one exit block!");
8002     // Proceed to the next level to examine the exit condition expression.
8003     return computeExitLimitFromCond(
8004         L, BI->getCondition(), ExitIfTrue,
8005         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8006   }
8007 
8008   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8009     // For switch, make sure that there is a single exit from the loop.
8010     BasicBlock *Exit = nullptr;
8011     for (auto *SBB : successors(ExitingBlock))
8012       if (!L->contains(SBB)) {
8013         if (Exit) // Multiple exit successors.
8014           return getCouldNotCompute();
8015         Exit = SBB;
8016       }
8017     assert(Exit && "Exiting block must have at least one exit");
8018     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8019                                                 /*ControlsExit=*/IsOnlyExit);
8020   }
8021 
8022   return getCouldNotCompute();
8023 }
8024 
8025 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8026     const Loop *L, Value *ExitCond, bool ExitIfTrue,
8027     bool ControlsExit, bool AllowPredicates) {
8028   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8029   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8030                                         ControlsExit, AllowPredicates);
8031 }
8032 
8033 Optional<ScalarEvolution::ExitLimit>
8034 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8035                                       bool ExitIfTrue, bool ControlsExit,
8036                                       bool AllowPredicates) {
8037   (void)this->L;
8038   (void)this->ExitIfTrue;
8039   (void)this->AllowPredicates;
8040 
8041   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8042          this->AllowPredicates == AllowPredicates &&
8043          "Variance in assumed invariant key components!");
8044   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8045   if (Itr == TripCountMap.end())
8046     return None;
8047   return Itr->second;
8048 }
8049 
8050 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8051                                              bool ExitIfTrue,
8052                                              bool ControlsExit,
8053                                              bool AllowPredicates,
8054                                              const ExitLimit &EL) {
8055   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8056          this->AllowPredicates == AllowPredicates &&
8057          "Variance in assumed invariant key components!");
8058 
8059   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8060   assert(InsertResult.second && "Expected successful insertion!");
8061   (void)InsertResult;
8062   (void)ExitIfTrue;
8063 }
8064 
8065 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8066     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8067     bool ControlsExit, bool AllowPredicates) {
8068 
8069   if (auto MaybeEL =
8070           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8071     return *MaybeEL;
8072 
8073   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8074                                               ControlsExit, AllowPredicates);
8075   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8076   return EL;
8077 }
8078 
8079 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8080     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8081     bool ControlsExit, bool AllowPredicates) {
8082   // Handle BinOp conditions (And, Or).
8083   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8084           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8085     return *LimitFromBinOp;
8086 
8087   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8088   // Proceed to the next level to examine the icmp.
8089   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8090     ExitLimit EL =
8091         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8092     if (EL.hasFullInfo() || !AllowPredicates)
8093       return EL;
8094 
8095     // Try again, but use SCEV predicates this time.
8096     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8097                                     /*AllowPredicates=*/true);
8098   }
8099 
8100   // Check for a constant condition. These are normally stripped out by
8101   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8102   // preserve the CFG and is temporarily leaving constant conditions
8103   // in place.
8104   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8105     if (ExitIfTrue == !CI->getZExtValue())
8106       // The backedge is always taken.
8107       return getCouldNotCompute();
8108     else
8109       // The backedge is never taken.
8110       return getZero(CI->getType());
8111   }
8112 
8113   // If it's not an integer or pointer comparison then compute it the hard way.
8114   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8115 }
8116 
8117 Optional<ScalarEvolution::ExitLimit>
8118 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8119     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8120     bool ControlsExit, bool AllowPredicates) {
8121   // Check if the controlling expression for this loop is an And or Or.
8122   Value *Op0, *Op1;
8123   bool IsAnd = false;
8124   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8125     IsAnd = true;
8126   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8127     IsAnd = false;
8128   else
8129     return None;
8130 
8131   // EitherMayExit is true in these two cases:
8132   //   br (and Op0 Op1), loop, exit
8133   //   br (or  Op0 Op1), exit, loop
8134   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8135   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
8136                                                  ControlsExit && !EitherMayExit,
8137                                                  AllowPredicates);
8138   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
8139                                                  ControlsExit && !EitherMayExit,
8140                                                  AllowPredicates);
8141 
8142   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8143   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8144   if (isa<ConstantInt>(Op1))
8145     return Op1 == NeutralElement ? EL0 : EL1;
8146   if (isa<ConstantInt>(Op0))
8147     return Op0 == NeutralElement ? EL1 : EL0;
8148 
8149   const SCEV *BECount = getCouldNotCompute();
8150   const SCEV *MaxBECount = getCouldNotCompute();
8151   if (EitherMayExit) {
8152     // Both conditions must be same for the loop to continue executing.
8153     // Choose the less conservative count.
8154     // If ExitCond is a short-circuit form (select), using
8155     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
8156     // To see the detailed examples, please see
8157     // test/Analysis/ScalarEvolution/exit-count-select.ll
8158     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
8159     if (!PoisonSafe)
8160       // Even if ExitCond is select, we can safely derive BECount using both
8161       // EL0 and EL1 in these cases:
8162       // (1) EL0.ExactNotTaken is non-zero
8163       // (2) EL1.ExactNotTaken is non-poison
8164       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
8165       //     it cannot be umin(0, ..))
8166       // The PoisonSafe assignment below is simplified and the assertion after
8167       // BECount calculation fully guarantees the condition (3).
8168       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
8169                    isa<SCEVConstant>(EL1.ExactNotTaken);
8170     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8171         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
8172       BECount =
8173           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
8174 
8175       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
8176       // it should have been simplified to zero (see the condition (3) above)
8177       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
8178              BECount->isZero());
8179     }
8180     if (EL0.MaxNotTaken == getCouldNotCompute())
8181       MaxBECount = EL1.MaxNotTaken;
8182     else if (EL1.MaxNotTaken == getCouldNotCompute())
8183       MaxBECount = EL0.MaxNotTaken;
8184     else
8185       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
8186   } else {
8187     // Both conditions must be same at the same time for the loop to exit.
8188     // For now, be conservative.
8189     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8190       BECount = EL0.ExactNotTaken;
8191   }
8192 
8193   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8194   // to be more aggressive when computing BECount than when computing
8195   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
8196   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
8197   // to not.
8198   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
8199       !isa<SCEVCouldNotCompute>(BECount))
8200     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
8201 
8202   return ExitLimit(BECount, MaxBECount, false,
8203                    { &EL0.Predicates, &EL1.Predicates });
8204 }
8205 
8206 ScalarEvolution::ExitLimit
8207 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8208                                           ICmpInst *ExitCond,
8209                                           bool ExitIfTrue,
8210                                           bool ControlsExit,
8211                                           bool AllowPredicates) {
8212   // If the condition was exit on true, convert the condition to exit on false
8213   ICmpInst::Predicate Pred;
8214   if (!ExitIfTrue)
8215     Pred = ExitCond->getPredicate();
8216   else
8217     Pred = ExitCond->getInversePredicate();
8218   const ICmpInst::Predicate OriginalPred = Pred;
8219 
8220   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8221   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8222 
8223   // Try to evaluate any dependencies out of the loop.
8224   LHS = getSCEVAtScope(LHS, L);
8225   RHS = getSCEVAtScope(RHS, L);
8226 
8227   // At this point, we would like to compute how many iterations of the
8228   // loop the predicate will return true for these inputs.
8229   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8230     // If there is a loop-invariant, force it into the RHS.
8231     std::swap(LHS, RHS);
8232     Pred = ICmpInst::getSwappedPredicate(Pred);
8233   }
8234 
8235   // Simplify the operands before analyzing them.
8236   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8237 
8238   // If we have a comparison of a chrec against a constant, try to use value
8239   // ranges to answer this query.
8240   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8241     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8242       if (AddRec->getLoop() == L) {
8243         // Form the constant range.
8244         ConstantRange CompRange =
8245             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8246 
8247         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8248         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8249       }
8250 
8251   // If this loop must exit based on this condition (or execute undefined
8252   // behaviour), and we can prove the test sequence produced must repeat
8253   // the same values on self-wrap of the IV, then we can infer that IV
8254   // doesn't self wrap because if it did, we'd have an infinite (undefined)
8255   // loop.
8256   if (ControlsExit && isLoopInvariant(RHS, L) && loopHasNoAbnormalExits(L) &&
8257       loopIsFiniteByAssumption(L)) {
8258 
8259     // TODO: We can peel off any functions which are invertible *in L*.  Loop
8260     // invariant terms are effectively constants for our purposes here.
8261     auto *InnerLHS = LHS;
8262     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
8263       InnerLHS = ZExt->getOperand();
8264     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
8265       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
8266       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
8267           StrideC && StrideC->getAPInt().isPowerOf2()) {
8268         auto Flags = AR->getNoWrapFlags();
8269         Flags = setFlags(Flags, SCEV::FlagNW);
8270         SmallVector<const SCEV*> Operands{AR->operands()};
8271         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
8272         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
8273       }
8274     }
8275   }
8276 
8277   switch (Pred) {
8278   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8279     // Convert to: while (X-Y != 0)
8280     if (LHS->getType()->isPointerTy()) {
8281       LHS = getLosslessPtrToIntExpr(LHS);
8282       if (isa<SCEVCouldNotCompute>(LHS))
8283         return LHS;
8284     }
8285     if (RHS->getType()->isPointerTy()) {
8286       RHS = getLosslessPtrToIntExpr(RHS);
8287       if (isa<SCEVCouldNotCompute>(RHS))
8288         return RHS;
8289     }
8290     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8291                                 AllowPredicates);
8292     if (EL.hasAnyInfo()) return EL;
8293     break;
8294   }
8295   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8296     // Convert to: while (X-Y == 0)
8297     if (LHS->getType()->isPointerTy()) {
8298       LHS = getLosslessPtrToIntExpr(LHS);
8299       if (isa<SCEVCouldNotCompute>(LHS))
8300         return LHS;
8301     }
8302     if (RHS->getType()->isPointerTy()) {
8303       RHS = getLosslessPtrToIntExpr(RHS);
8304       if (isa<SCEVCouldNotCompute>(RHS))
8305         return RHS;
8306     }
8307     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8308     if (EL.hasAnyInfo()) return EL;
8309     break;
8310   }
8311   case ICmpInst::ICMP_SLT:
8312   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8313     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8314     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8315                                     AllowPredicates);
8316     if (EL.hasAnyInfo()) return EL;
8317     break;
8318   }
8319   case ICmpInst::ICMP_SGT:
8320   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8321     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8322     ExitLimit EL =
8323         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8324                             AllowPredicates);
8325     if (EL.hasAnyInfo()) return EL;
8326     break;
8327   }
8328   default:
8329     break;
8330   }
8331 
8332   auto *ExhaustiveCount =
8333       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8334 
8335   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8336     return ExhaustiveCount;
8337 
8338   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8339                                       ExitCond->getOperand(1), L, OriginalPred);
8340 }
8341 
8342 ScalarEvolution::ExitLimit
8343 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8344                                                       SwitchInst *Switch,
8345                                                       BasicBlock *ExitingBlock,
8346                                                       bool ControlsExit) {
8347   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8348 
8349   // Give up if the exit is the default dest of a switch.
8350   if (Switch->getDefaultDest() == ExitingBlock)
8351     return getCouldNotCompute();
8352 
8353   assert(L->contains(Switch->getDefaultDest()) &&
8354          "Default case must not exit the loop!");
8355   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8356   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8357 
8358   // while (X != Y) --> while (X-Y != 0)
8359   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8360   if (EL.hasAnyInfo())
8361     return EL;
8362 
8363   return getCouldNotCompute();
8364 }
8365 
8366 static ConstantInt *
8367 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8368                                 ScalarEvolution &SE) {
8369   const SCEV *InVal = SE.getConstant(C);
8370   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8371   assert(isa<SCEVConstant>(Val) &&
8372          "Evaluation of SCEV at constant didn't fold correctly?");
8373   return cast<SCEVConstant>(Val)->getValue();
8374 }
8375 
8376 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8377     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8378   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8379   if (!RHS)
8380     return getCouldNotCompute();
8381 
8382   const BasicBlock *Latch = L->getLoopLatch();
8383   if (!Latch)
8384     return getCouldNotCompute();
8385 
8386   const BasicBlock *Predecessor = L->getLoopPredecessor();
8387   if (!Predecessor)
8388     return getCouldNotCompute();
8389 
8390   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8391   // Return LHS in OutLHS and shift_opt in OutOpCode.
8392   auto MatchPositiveShift =
8393       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8394 
8395     using namespace PatternMatch;
8396 
8397     ConstantInt *ShiftAmt;
8398     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8399       OutOpCode = Instruction::LShr;
8400     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8401       OutOpCode = Instruction::AShr;
8402     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8403       OutOpCode = Instruction::Shl;
8404     else
8405       return false;
8406 
8407     return ShiftAmt->getValue().isStrictlyPositive();
8408   };
8409 
8410   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8411   //
8412   // loop:
8413   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8414   //   %iv.shifted = lshr i32 %iv, <positive constant>
8415   //
8416   // Return true on a successful match.  Return the corresponding PHI node (%iv
8417   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8418   auto MatchShiftRecurrence =
8419       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8420     Optional<Instruction::BinaryOps> PostShiftOpCode;
8421 
8422     {
8423       Instruction::BinaryOps OpC;
8424       Value *V;
8425 
8426       // If we encounter a shift instruction, "peel off" the shift operation,
8427       // and remember that we did so.  Later when we inspect %iv's backedge
8428       // value, we will make sure that the backedge value uses the same
8429       // operation.
8430       //
8431       // Note: the peeled shift operation does not have to be the same
8432       // instruction as the one feeding into the PHI's backedge value.  We only
8433       // really care about it being the same *kind* of shift instruction --
8434       // that's all that is required for our later inferences to hold.
8435       if (MatchPositiveShift(LHS, V, OpC)) {
8436         PostShiftOpCode = OpC;
8437         LHS = V;
8438       }
8439     }
8440 
8441     PNOut = dyn_cast<PHINode>(LHS);
8442     if (!PNOut || PNOut->getParent() != L->getHeader())
8443       return false;
8444 
8445     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8446     Value *OpLHS;
8447 
8448     return
8449         // The backedge value for the PHI node must be a shift by a positive
8450         // amount
8451         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8452 
8453         // of the PHI node itself
8454         OpLHS == PNOut &&
8455 
8456         // and the kind of shift should be match the kind of shift we peeled
8457         // off, if any.
8458         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8459   };
8460 
8461   PHINode *PN;
8462   Instruction::BinaryOps OpCode;
8463   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8464     return getCouldNotCompute();
8465 
8466   const DataLayout &DL = getDataLayout();
8467 
8468   // The key rationale for this optimization is that for some kinds of shift
8469   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8470   // within a finite number of iterations.  If the condition guarding the
8471   // backedge (in the sense that the backedge is taken if the condition is true)
8472   // is false for the value the shift recurrence stabilizes to, then we know
8473   // that the backedge is taken only a finite number of times.
8474 
8475   ConstantInt *StableValue = nullptr;
8476   switch (OpCode) {
8477   default:
8478     llvm_unreachable("Impossible case!");
8479 
8480   case Instruction::AShr: {
8481     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8482     // bitwidth(K) iterations.
8483     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8484     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8485                                        Predecessor->getTerminator(), &DT);
8486     auto *Ty = cast<IntegerType>(RHS->getType());
8487     if (Known.isNonNegative())
8488       StableValue = ConstantInt::get(Ty, 0);
8489     else if (Known.isNegative())
8490       StableValue = ConstantInt::get(Ty, -1, true);
8491     else
8492       return getCouldNotCompute();
8493 
8494     break;
8495   }
8496   case Instruction::LShr:
8497   case Instruction::Shl:
8498     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8499     // stabilize to 0 in at most bitwidth(K) iterations.
8500     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8501     break;
8502   }
8503 
8504   auto *Result =
8505       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8506   assert(Result->getType()->isIntegerTy(1) &&
8507          "Otherwise cannot be an operand to a branch instruction");
8508 
8509   if (Result->isZeroValue()) {
8510     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8511     const SCEV *UpperBound =
8512         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8513     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8514   }
8515 
8516   return getCouldNotCompute();
8517 }
8518 
8519 /// Return true if we can constant fold an instruction of the specified type,
8520 /// assuming that all operands were constants.
8521 static bool CanConstantFold(const Instruction *I) {
8522   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8523       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8524       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8525     return true;
8526 
8527   if (const CallInst *CI = dyn_cast<CallInst>(I))
8528     if (const Function *F = CI->getCalledFunction())
8529       return canConstantFoldCallTo(CI, F);
8530   return false;
8531 }
8532 
8533 /// Determine whether this instruction can constant evolve within this loop
8534 /// assuming its operands can all constant evolve.
8535 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8536   // An instruction outside of the loop can't be derived from a loop PHI.
8537   if (!L->contains(I)) return false;
8538 
8539   if (isa<PHINode>(I)) {
8540     // We don't currently keep track of the control flow needed to evaluate
8541     // PHIs, so we cannot handle PHIs inside of loops.
8542     return L->getHeader() == I->getParent();
8543   }
8544 
8545   // If we won't be able to constant fold this expression even if the operands
8546   // are constants, bail early.
8547   return CanConstantFold(I);
8548 }
8549 
8550 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8551 /// recursing through each instruction operand until reaching a loop header phi.
8552 static PHINode *
8553 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8554                                DenseMap<Instruction *, PHINode *> &PHIMap,
8555                                unsigned Depth) {
8556   if (Depth > MaxConstantEvolvingDepth)
8557     return nullptr;
8558 
8559   // Otherwise, we can evaluate this instruction if all of its operands are
8560   // constant or derived from a PHI node themselves.
8561   PHINode *PHI = nullptr;
8562   for (Value *Op : UseInst->operands()) {
8563     if (isa<Constant>(Op)) continue;
8564 
8565     Instruction *OpInst = dyn_cast<Instruction>(Op);
8566     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8567 
8568     PHINode *P = dyn_cast<PHINode>(OpInst);
8569     if (!P)
8570       // If this operand is already visited, reuse the prior result.
8571       // We may have P != PHI if this is the deepest point at which the
8572       // inconsistent paths meet.
8573       P = PHIMap.lookup(OpInst);
8574     if (!P) {
8575       // Recurse and memoize the results, whether a phi is found or not.
8576       // This recursive call invalidates pointers into PHIMap.
8577       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8578       PHIMap[OpInst] = P;
8579     }
8580     if (!P)
8581       return nullptr;  // Not evolving from PHI
8582     if (PHI && PHI != P)
8583       return nullptr;  // Evolving from multiple different PHIs.
8584     PHI = P;
8585   }
8586   // This is a expression evolving from a constant PHI!
8587   return PHI;
8588 }
8589 
8590 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8591 /// in the loop that V is derived from.  We allow arbitrary operations along the
8592 /// way, but the operands of an operation must either be constants or a value
8593 /// derived from a constant PHI.  If this expression does not fit with these
8594 /// constraints, return null.
8595 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8596   Instruction *I = dyn_cast<Instruction>(V);
8597   if (!I || !canConstantEvolve(I, L)) return nullptr;
8598 
8599   if (PHINode *PN = dyn_cast<PHINode>(I))
8600     return PN;
8601 
8602   // Record non-constant instructions contained by the loop.
8603   DenseMap<Instruction *, PHINode *> PHIMap;
8604   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8605 }
8606 
8607 /// EvaluateExpression - Given an expression that passes the
8608 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8609 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8610 /// reason, return null.
8611 static Constant *EvaluateExpression(Value *V, const Loop *L,
8612                                     DenseMap<Instruction *, Constant *> &Vals,
8613                                     const DataLayout &DL,
8614                                     const TargetLibraryInfo *TLI) {
8615   // Convenient constant check, but redundant for recursive calls.
8616   if (Constant *C = dyn_cast<Constant>(V)) return C;
8617   Instruction *I = dyn_cast<Instruction>(V);
8618   if (!I) return nullptr;
8619 
8620   if (Constant *C = Vals.lookup(I)) return C;
8621 
8622   // An instruction inside the loop depends on a value outside the loop that we
8623   // weren't given a mapping for, or a value such as a call inside the loop.
8624   if (!canConstantEvolve(I, L)) return nullptr;
8625 
8626   // An unmapped PHI can be due to a branch or another loop inside this loop,
8627   // or due to this not being the initial iteration through a loop where we
8628   // couldn't compute the evolution of this particular PHI last time.
8629   if (isa<PHINode>(I)) return nullptr;
8630 
8631   std::vector<Constant*> Operands(I->getNumOperands());
8632 
8633   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8634     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8635     if (!Operand) {
8636       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8637       if (!Operands[i]) return nullptr;
8638       continue;
8639     }
8640     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8641     Vals[Operand] = C;
8642     if (!C) return nullptr;
8643     Operands[i] = C;
8644   }
8645 
8646   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8647     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8648                                            Operands[1], DL, TLI);
8649   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8650     if (!LI->isVolatile())
8651       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8652   }
8653   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8654 }
8655 
8656 
8657 // If every incoming value to PN except the one for BB is a specific Constant,
8658 // return that, else return nullptr.
8659 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8660   Constant *IncomingVal = nullptr;
8661 
8662   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8663     if (PN->getIncomingBlock(i) == BB)
8664       continue;
8665 
8666     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8667     if (!CurrentVal)
8668       return nullptr;
8669 
8670     if (IncomingVal != CurrentVal) {
8671       if (IncomingVal)
8672         return nullptr;
8673       IncomingVal = CurrentVal;
8674     }
8675   }
8676 
8677   return IncomingVal;
8678 }
8679 
8680 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8681 /// in the header of its containing loop, we know the loop executes a
8682 /// constant number of times, and the PHI node is just a recurrence
8683 /// involving constants, fold it.
8684 Constant *
8685 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8686                                                    const APInt &BEs,
8687                                                    const Loop *L) {
8688   auto I = ConstantEvolutionLoopExitValue.find(PN);
8689   if (I != ConstantEvolutionLoopExitValue.end())
8690     return I->second;
8691 
8692   if (BEs.ugt(MaxBruteForceIterations))
8693     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8694 
8695   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8696 
8697   DenseMap<Instruction *, Constant *> CurrentIterVals;
8698   BasicBlock *Header = L->getHeader();
8699   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8700 
8701   BasicBlock *Latch = L->getLoopLatch();
8702   if (!Latch)
8703     return nullptr;
8704 
8705   for (PHINode &PHI : Header->phis()) {
8706     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8707       CurrentIterVals[&PHI] = StartCST;
8708   }
8709   if (!CurrentIterVals.count(PN))
8710     return RetVal = nullptr;
8711 
8712   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8713 
8714   // Execute the loop symbolically to determine the exit value.
8715   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8716          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8717 
8718   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8719   unsigned IterationNum = 0;
8720   const DataLayout &DL = getDataLayout();
8721   for (; ; ++IterationNum) {
8722     if (IterationNum == NumIterations)
8723       return RetVal = CurrentIterVals[PN];  // Got exit value!
8724 
8725     // Compute the value of the PHIs for the next iteration.
8726     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8727     DenseMap<Instruction *, Constant *> NextIterVals;
8728     Constant *NextPHI =
8729         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8730     if (!NextPHI)
8731       return nullptr;        // Couldn't evaluate!
8732     NextIterVals[PN] = NextPHI;
8733 
8734     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8735 
8736     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8737     // cease to be able to evaluate one of them or if they stop evolving,
8738     // because that doesn't necessarily prevent us from computing PN.
8739     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8740     for (const auto &I : CurrentIterVals) {
8741       PHINode *PHI = dyn_cast<PHINode>(I.first);
8742       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8743       PHIsToCompute.emplace_back(PHI, I.second);
8744     }
8745     // We use two distinct loops because EvaluateExpression may invalidate any
8746     // iterators into CurrentIterVals.
8747     for (const auto &I : PHIsToCompute) {
8748       PHINode *PHI = I.first;
8749       Constant *&NextPHI = NextIterVals[PHI];
8750       if (!NextPHI) {   // Not already computed.
8751         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8752         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8753       }
8754       if (NextPHI != I.second)
8755         StoppedEvolving = false;
8756     }
8757 
8758     // If all entries in CurrentIterVals == NextIterVals then we can stop
8759     // iterating, the loop can't continue to change.
8760     if (StoppedEvolving)
8761       return RetVal = CurrentIterVals[PN];
8762 
8763     CurrentIterVals.swap(NextIterVals);
8764   }
8765 }
8766 
8767 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8768                                                           Value *Cond,
8769                                                           bool ExitWhen) {
8770   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8771   if (!PN) return getCouldNotCompute();
8772 
8773   // If the loop is canonicalized, the PHI will have exactly two entries.
8774   // That's the only form we support here.
8775   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8776 
8777   DenseMap<Instruction *, Constant *> CurrentIterVals;
8778   BasicBlock *Header = L->getHeader();
8779   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8780 
8781   BasicBlock *Latch = L->getLoopLatch();
8782   assert(Latch && "Should follow from NumIncomingValues == 2!");
8783 
8784   for (PHINode &PHI : Header->phis()) {
8785     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8786       CurrentIterVals[&PHI] = StartCST;
8787   }
8788   if (!CurrentIterVals.count(PN))
8789     return getCouldNotCompute();
8790 
8791   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8792   // the loop symbolically to determine when the condition gets a value of
8793   // "ExitWhen".
8794   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8795   const DataLayout &DL = getDataLayout();
8796   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8797     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8798         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8799 
8800     // Couldn't symbolically evaluate.
8801     if (!CondVal) return getCouldNotCompute();
8802 
8803     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8804       ++NumBruteForceTripCountsComputed;
8805       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8806     }
8807 
8808     // Update all the PHI nodes for the next iteration.
8809     DenseMap<Instruction *, Constant *> NextIterVals;
8810 
8811     // Create a list of which PHIs we need to compute. We want to do this before
8812     // calling EvaluateExpression on them because that may invalidate iterators
8813     // into CurrentIterVals.
8814     SmallVector<PHINode *, 8> PHIsToCompute;
8815     for (const auto &I : CurrentIterVals) {
8816       PHINode *PHI = dyn_cast<PHINode>(I.first);
8817       if (!PHI || PHI->getParent() != Header) continue;
8818       PHIsToCompute.push_back(PHI);
8819     }
8820     for (PHINode *PHI : PHIsToCompute) {
8821       Constant *&NextPHI = NextIterVals[PHI];
8822       if (NextPHI) continue;    // Already computed!
8823 
8824       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8825       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8826     }
8827     CurrentIterVals.swap(NextIterVals);
8828   }
8829 
8830   // Too many iterations were needed to evaluate.
8831   return getCouldNotCompute();
8832 }
8833 
8834 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8835   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8836       ValuesAtScopes[V];
8837   // Check to see if we've folded this expression at this loop before.
8838   for (auto &LS : Values)
8839     if (LS.first == L)
8840       return LS.second ? LS.second : V;
8841 
8842   Values.emplace_back(L, nullptr);
8843 
8844   // Otherwise compute it.
8845   const SCEV *C = computeSCEVAtScope(V, L);
8846   for (auto &LS : reverse(ValuesAtScopes[V]))
8847     if (LS.first == L) {
8848       LS.second = C;
8849       break;
8850     }
8851   return C;
8852 }
8853 
8854 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8855 /// will return Constants for objects which aren't represented by a
8856 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8857 /// Returns NULL if the SCEV isn't representable as a Constant.
8858 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8859   switch (V->getSCEVType()) {
8860   case scCouldNotCompute:
8861   case scAddRecExpr:
8862     return nullptr;
8863   case scConstant:
8864     return cast<SCEVConstant>(V)->getValue();
8865   case scUnknown:
8866     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8867   case scSignExtend: {
8868     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8869     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8870       return ConstantExpr::getSExt(CastOp, SS->getType());
8871     return nullptr;
8872   }
8873   case scZeroExtend: {
8874     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8875     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8876       return ConstantExpr::getZExt(CastOp, SZ->getType());
8877     return nullptr;
8878   }
8879   case scPtrToInt: {
8880     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8881     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8882       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8883 
8884     return nullptr;
8885   }
8886   case scTruncate: {
8887     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8888     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8889       return ConstantExpr::getTrunc(CastOp, ST->getType());
8890     return nullptr;
8891   }
8892   case scAddExpr: {
8893     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8894     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8895       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8896         unsigned AS = PTy->getAddressSpace();
8897         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8898         C = ConstantExpr::getBitCast(C, DestPtrTy);
8899       }
8900       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8901         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8902         if (!C2)
8903           return nullptr;
8904 
8905         // First pointer!
8906         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8907           unsigned AS = C2->getType()->getPointerAddressSpace();
8908           std::swap(C, C2);
8909           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8910           // The offsets have been converted to bytes.  We can add bytes to an
8911           // i8* by GEP with the byte count in the first index.
8912           C = ConstantExpr::getBitCast(C, DestPtrTy);
8913         }
8914 
8915         // Don't bother trying to sum two pointers. We probably can't
8916         // statically compute a load that results from it anyway.
8917         if (C2->getType()->isPointerTy())
8918           return nullptr;
8919 
8920         if (C->getType()->isPointerTy()) {
8921           C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
8922                                              C, C2);
8923         } else {
8924           C = ConstantExpr::getAdd(C, C2);
8925         }
8926       }
8927       return C;
8928     }
8929     return nullptr;
8930   }
8931   case scMulExpr: {
8932     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8933     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8934       // Don't bother with pointers at all.
8935       if (C->getType()->isPointerTy())
8936         return nullptr;
8937       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8938         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8939         if (!C2 || C2->getType()->isPointerTy())
8940           return nullptr;
8941         C = ConstantExpr::getMul(C, C2);
8942       }
8943       return C;
8944     }
8945     return nullptr;
8946   }
8947   case scUDivExpr: {
8948     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8949     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8950       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8951         if (LHS->getType() == RHS->getType())
8952           return ConstantExpr::getUDiv(LHS, RHS);
8953     return nullptr;
8954   }
8955   case scSMaxExpr:
8956   case scUMaxExpr:
8957   case scSMinExpr:
8958   case scUMinExpr:
8959     return nullptr; // TODO: smax, umax, smin, umax.
8960   }
8961   llvm_unreachable("Unknown SCEV kind!");
8962 }
8963 
8964 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8965   if (isa<SCEVConstant>(V)) return V;
8966 
8967   // If this instruction is evolved from a constant-evolving PHI, compute the
8968   // exit value from the loop without using SCEVs.
8969   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8970     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8971       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8972         const Loop *CurrLoop = this->LI[I->getParent()];
8973         // Looking for loop exit value.
8974         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8975             PN->getParent() == CurrLoop->getHeader()) {
8976           // Okay, there is no closed form solution for the PHI node.  Check
8977           // to see if the loop that contains it has a known backedge-taken
8978           // count.  If so, we may be able to force computation of the exit
8979           // value.
8980           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8981           // This trivial case can show up in some degenerate cases where
8982           // the incoming IR has not yet been fully simplified.
8983           if (BackedgeTakenCount->isZero()) {
8984             Value *InitValue = nullptr;
8985             bool MultipleInitValues = false;
8986             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8987               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8988                 if (!InitValue)
8989                   InitValue = PN->getIncomingValue(i);
8990                 else if (InitValue != PN->getIncomingValue(i)) {
8991                   MultipleInitValues = true;
8992                   break;
8993                 }
8994               }
8995             }
8996             if (!MultipleInitValues && InitValue)
8997               return getSCEV(InitValue);
8998           }
8999           // Do we have a loop invariant value flowing around the backedge
9000           // for a loop which must execute the backedge?
9001           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9002               isKnownPositive(BackedgeTakenCount) &&
9003               PN->getNumIncomingValues() == 2) {
9004 
9005             unsigned InLoopPred =
9006                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9007             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9008             if (CurrLoop->isLoopInvariant(BackedgeVal))
9009               return getSCEV(BackedgeVal);
9010           }
9011           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9012             // Okay, we know how many times the containing loop executes.  If
9013             // this is a constant evolving PHI node, get the final value at
9014             // the specified iteration number.
9015             Constant *RV = getConstantEvolutionLoopExitValue(
9016                 PN, BTCC->getAPInt(), CurrLoop);
9017             if (RV) return getSCEV(RV);
9018           }
9019         }
9020 
9021         // If there is a single-input Phi, evaluate it at our scope. If we can
9022         // prove that this replacement does not break LCSSA form, use new value.
9023         if (PN->getNumOperands() == 1) {
9024           const SCEV *Input = getSCEV(PN->getOperand(0));
9025           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
9026           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
9027           // for the simplest case just support constants.
9028           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
9029         }
9030       }
9031 
9032       // Okay, this is an expression that we cannot symbolically evaluate
9033       // into a SCEV.  Check to see if it's possible to symbolically evaluate
9034       // the arguments into constants, and if so, try to constant propagate the
9035       // result.  This is particularly useful for computing loop exit values.
9036       if (CanConstantFold(I)) {
9037         SmallVector<Constant *, 4> Operands;
9038         bool MadeImprovement = false;
9039         for (Value *Op : I->operands()) {
9040           if (Constant *C = dyn_cast<Constant>(Op)) {
9041             Operands.push_back(C);
9042             continue;
9043           }
9044 
9045           // If any of the operands is non-constant and if they are
9046           // non-integer and non-pointer, don't even try to analyze them
9047           // with scev techniques.
9048           if (!isSCEVable(Op->getType()))
9049             return V;
9050 
9051           const SCEV *OrigV = getSCEV(Op);
9052           const SCEV *OpV = getSCEVAtScope(OrigV, L);
9053           MadeImprovement |= OrigV != OpV;
9054 
9055           Constant *C = BuildConstantFromSCEV(OpV);
9056           if (!C) return V;
9057           if (C->getType() != Op->getType())
9058             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
9059                                                               Op->getType(),
9060                                                               false),
9061                                       C, Op->getType());
9062           Operands.push_back(C);
9063         }
9064 
9065         // Check to see if getSCEVAtScope actually made an improvement.
9066         if (MadeImprovement) {
9067           Constant *C = nullptr;
9068           const DataLayout &DL = getDataLayout();
9069           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
9070             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9071                                                 Operands[1], DL, &TLI);
9072           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
9073             if (!Load->isVolatile())
9074               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
9075                                                DL);
9076           } else
9077             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9078           if (!C) return V;
9079           return getSCEV(C);
9080         }
9081       }
9082     }
9083 
9084     // This is some other type of SCEVUnknown, just return it.
9085     return V;
9086   }
9087 
9088   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
9089     // Avoid performing the look-up in the common case where the specified
9090     // expression has no loop-variant portions.
9091     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
9092       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9093       if (OpAtScope != Comm->getOperand(i)) {
9094         // Okay, at least one of these operands is loop variant but might be
9095         // foldable.  Build a new instance of the folded commutative expression.
9096         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
9097                                             Comm->op_begin()+i);
9098         NewOps.push_back(OpAtScope);
9099 
9100         for (++i; i != e; ++i) {
9101           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9102           NewOps.push_back(OpAtScope);
9103         }
9104         if (isa<SCEVAddExpr>(Comm))
9105           return getAddExpr(NewOps, Comm->getNoWrapFlags());
9106         if (isa<SCEVMulExpr>(Comm))
9107           return getMulExpr(NewOps, Comm->getNoWrapFlags());
9108         if (isa<SCEVMinMaxExpr>(Comm))
9109           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
9110         llvm_unreachable("Unknown commutative SCEV type!");
9111       }
9112     }
9113     // If we got here, all operands are loop invariant.
9114     return Comm;
9115   }
9116 
9117   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
9118     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
9119     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
9120     if (LHS == Div->getLHS() && RHS == Div->getRHS())
9121       return Div;   // must be loop invariant
9122     return getUDivExpr(LHS, RHS);
9123   }
9124 
9125   // If this is a loop recurrence for a loop that does not contain L, then we
9126   // are dealing with the final value computed by the loop.
9127   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
9128     // First, attempt to evaluate each operand.
9129     // Avoid performing the look-up in the common case where the specified
9130     // expression has no loop-variant portions.
9131     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9132       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9133       if (OpAtScope == AddRec->getOperand(i))
9134         continue;
9135 
9136       // Okay, at least one of these operands is loop variant but might be
9137       // foldable.  Build a new instance of the folded commutative expression.
9138       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9139                                           AddRec->op_begin()+i);
9140       NewOps.push_back(OpAtScope);
9141       for (++i; i != e; ++i)
9142         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9143 
9144       const SCEV *FoldedRec =
9145         getAddRecExpr(NewOps, AddRec->getLoop(),
9146                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9147       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9148       // The addrec may be folded to a nonrecurrence, for example, if the
9149       // induction variable is multiplied by zero after constant folding. Go
9150       // ahead and return the folded value.
9151       if (!AddRec)
9152         return FoldedRec;
9153       break;
9154     }
9155 
9156     // If the scope is outside the addrec's loop, evaluate it by using the
9157     // loop exit value of the addrec.
9158     if (!AddRec->getLoop()->contains(L)) {
9159       // To evaluate this recurrence, we need to know how many times the AddRec
9160       // loop iterates.  Compute this now.
9161       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9162       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9163 
9164       // Then, evaluate the AddRec.
9165       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9166     }
9167 
9168     return AddRec;
9169   }
9170 
9171   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
9172     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9173     if (Op == Cast->getOperand())
9174       return Cast;  // must be loop invariant
9175     return getZeroExtendExpr(Op, Cast->getType());
9176   }
9177 
9178   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
9179     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9180     if (Op == Cast->getOperand())
9181       return Cast;  // must be loop invariant
9182     return getSignExtendExpr(Op, Cast->getType());
9183   }
9184 
9185   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
9186     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9187     if (Op == Cast->getOperand())
9188       return Cast;  // must be loop invariant
9189     return getTruncateExpr(Op, Cast->getType());
9190   }
9191 
9192   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
9193     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9194     if (Op == Cast->getOperand())
9195       return Cast; // must be loop invariant
9196     return getPtrToIntExpr(Op, Cast->getType());
9197   }
9198 
9199   llvm_unreachable("Unknown SCEV type!");
9200 }
9201 
9202 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9203   return getSCEVAtScope(getSCEV(V), L);
9204 }
9205 
9206 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9207   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9208     return stripInjectiveFunctions(ZExt->getOperand());
9209   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9210     return stripInjectiveFunctions(SExt->getOperand());
9211   return S;
9212 }
9213 
9214 /// Finds the minimum unsigned root of the following equation:
9215 ///
9216 ///     A * X = B (mod N)
9217 ///
9218 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9219 /// A and B isn't important.
9220 ///
9221 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9222 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9223                                                ScalarEvolution &SE) {
9224   uint32_t BW = A.getBitWidth();
9225   assert(BW == SE.getTypeSizeInBits(B->getType()));
9226   assert(A != 0 && "A must be non-zero.");
9227 
9228   // 1. D = gcd(A, N)
9229   //
9230   // The gcd of A and N may have only one prime factor: 2. The number of
9231   // trailing zeros in A is its multiplicity
9232   uint32_t Mult2 = A.countTrailingZeros();
9233   // D = 2^Mult2
9234 
9235   // 2. Check if B is divisible by D.
9236   //
9237   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9238   // is not less than multiplicity of this prime factor for D.
9239   if (SE.GetMinTrailingZeros(B) < Mult2)
9240     return SE.getCouldNotCompute();
9241 
9242   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9243   // modulo (N / D).
9244   //
9245   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9246   // (N / D) in general. The inverse itself always fits into BW bits, though,
9247   // so we immediately truncate it.
9248   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9249   APInt Mod(BW + 1, 0);
9250   Mod.setBit(BW - Mult2);  // Mod = N / D
9251   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9252 
9253   // 4. Compute the minimum unsigned root of the equation:
9254   // I * (B / D) mod (N / D)
9255   // To simplify the computation, we factor out the divide by D:
9256   // (I * B mod N) / D
9257   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9258   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9259 }
9260 
9261 /// For a given quadratic addrec, generate coefficients of the corresponding
9262 /// quadratic equation, multiplied by a common value to ensure that they are
9263 /// integers.
9264 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9265 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9266 /// were multiplied by, and BitWidth is the bit width of the original addrec
9267 /// coefficients.
9268 /// This function returns None if the addrec coefficients are not compile-
9269 /// time constants.
9270 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9271 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9272   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9273   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9274   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9275   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9276   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9277                     << *AddRec << '\n');
9278 
9279   // We currently can only solve this if the coefficients are constants.
9280   if (!LC || !MC || !NC) {
9281     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9282     return None;
9283   }
9284 
9285   APInt L = LC->getAPInt();
9286   APInt M = MC->getAPInt();
9287   APInt N = NC->getAPInt();
9288   assert(!N.isZero() && "This is not a quadratic addrec");
9289 
9290   unsigned BitWidth = LC->getAPInt().getBitWidth();
9291   unsigned NewWidth = BitWidth + 1;
9292   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9293                     << BitWidth << '\n');
9294   // The sign-extension (as opposed to a zero-extension) here matches the
9295   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9296   N = N.sext(NewWidth);
9297   M = M.sext(NewWidth);
9298   L = L.sext(NewWidth);
9299 
9300   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9301   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9302   //   L+M, L+2M+N, L+3M+3N, ...
9303   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9304   //
9305   // The equation Acc = 0 is then
9306   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9307   // In a quadratic form it becomes:
9308   //   N n^2 + (2M-N) n + 2L = 0.
9309 
9310   APInt A = N;
9311   APInt B = 2 * M - A;
9312   APInt C = 2 * L;
9313   APInt T = APInt(NewWidth, 2);
9314   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9315                     << "x + " << C << ", coeff bw: " << NewWidth
9316                     << ", multiplied by " << T << '\n');
9317   return std::make_tuple(A, B, C, T, BitWidth);
9318 }
9319 
9320 /// Helper function to compare optional APInts:
9321 /// (a) if X and Y both exist, return min(X, Y),
9322 /// (b) if neither X nor Y exist, return None,
9323 /// (c) if exactly one of X and Y exists, return that value.
9324 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9325   if (X.hasValue() && Y.hasValue()) {
9326     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9327     APInt XW = X->sextOrSelf(W);
9328     APInt YW = Y->sextOrSelf(W);
9329     return XW.slt(YW) ? *X : *Y;
9330   }
9331   if (!X.hasValue() && !Y.hasValue())
9332     return None;
9333   return X.hasValue() ? *X : *Y;
9334 }
9335 
9336 /// Helper function to truncate an optional APInt to a given BitWidth.
9337 /// When solving addrec-related equations, it is preferable to return a value
9338 /// that has the same bit width as the original addrec's coefficients. If the
9339 /// solution fits in the original bit width, truncate it (except for i1).
9340 /// Returning a value of a different bit width may inhibit some optimizations.
9341 ///
9342 /// In general, a solution to a quadratic equation generated from an addrec
9343 /// may require BW+1 bits, where BW is the bit width of the addrec's
9344 /// coefficients. The reason is that the coefficients of the quadratic
9345 /// equation are BW+1 bits wide (to avoid truncation when converting from
9346 /// the addrec to the equation).
9347 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9348   if (!X.hasValue())
9349     return None;
9350   unsigned W = X->getBitWidth();
9351   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9352     return X->trunc(BitWidth);
9353   return X;
9354 }
9355 
9356 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9357 /// iterations. The values L, M, N are assumed to be signed, and they
9358 /// should all have the same bit widths.
9359 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9360 /// where BW is the bit width of the addrec's coefficients.
9361 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9362 /// returned as such, otherwise the bit width of the returned value may
9363 /// be greater than BW.
9364 ///
9365 /// This function returns None if
9366 /// (a) the addrec coefficients are not constant, or
9367 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9368 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9369 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9370 static Optional<APInt>
9371 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9372   APInt A, B, C, M;
9373   unsigned BitWidth;
9374   auto T = GetQuadraticEquation(AddRec);
9375   if (!T.hasValue())
9376     return None;
9377 
9378   std::tie(A, B, C, M, BitWidth) = *T;
9379   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9380   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9381   if (!X.hasValue())
9382     return None;
9383 
9384   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9385   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9386   if (!V->isZero())
9387     return None;
9388 
9389   return TruncIfPossible(X, BitWidth);
9390 }
9391 
9392 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9393 /// iterations. The values M, N are assumed to be signed, and they
9394 /// should all have the same bit widths.
9395 /// Find the least n such that c(n) does not belong to the given range,
9396 /// while c(n-1) does.
9397 ///
9398 /// This function returns None if
9399 /// (a) the addrec coefficients are not constant, or
9400 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9401 ///     bounds of the range.
9402 static Optional<APInt>
9403 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9404                           const ConstantRange &Range, ScalarEvolution &SE) {
9405   assert(AddRec->getOperand(0)->isZero() &&
9406          "Starting value of addrec should be 0");
9407   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9408                     << Range << ", addrec " << *AddRec << '\n');
9409   // This case is handled in getNumIterationsInRange. Here we can assume that
9410   // we start in the range.
9411   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9412          "Addrec's initial value should be in range");
9413 
9414   APInt A, B, C, M;
9415   unsigned BitWidth;
9416   auto T = GetQuadraticEquation(AddRec);
9417   if (!T.hasValue())
9418     return None;
9419 
9420   // Be careful about the return value: there can be two reasons for not
9421   // returning an actual number. First, if no solutions to the equations
9422   // were found, and second, if the solutions don't leave the given range.
9423   // The first case means that the actual solution is "unknown", the second
9424   // means that it's known, but not valid. If the solution is unknown, we
9425   // cannot make any conclusions.
9426   // Return a pair: the optional solution and a flag indicating if the
9427   // solution was found.
9428   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9429     // Solve for signed overflow and unsigned overflow, pick the lower
9430     // solution.
9431     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9432                       << Bound << " (before multiplying by " << M << ")\n");
9433     Bound *= M; // The quadratic equation multiplier.
9434 
9435     Optional<APInt> SO = None;
9436     if (BitWidth > 1) {
9437       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9438                            "signed overflow\n");
9439       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9440     }
9441     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9442                          "unsigned overflow\n");
9443     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9444                                                               BitWidth+1);
9445 
9446     auto LeavesRange = [&] (const APInt &X) {
9447       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9448       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9449       if (Range.contains(V0->getValue()))
9450         return false;
9451       // X should be at least 1, so X-1 is non-negative.
9452       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9453       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9454       if (Range.contains(V1->getValue()))
9455         return true;
9456       return false;
9457     };
9458 
9459     // If SolveQuadraticEquationWrap returns None, it means that there can
9460     // be a solution, but the function failed to find it. We cannot treat it
9461     // as "no solution".
9462     if (!SO.hasValue() || !UO.hasValue())
9463       return { None, false };
9464 
9465     // Check the smaller value first to see if it leaves the range.
9466     // At this point, both SO and UO must have values.
9467     Optional<APInt> Min = MinOptional(SO, UO);
9468     if (LeavesRange(*Min))
9469       return { Min, true };
9470     Optional<APInt> Max = Min == SO ? UO : SO;
9471     if (LeavesRange(*Max))
9472       return { Max, true };
9473 
9474     // Solutions were found, but were eliminated, hence the "true".
9475     return { None, true };
9476   };
9477 
9478   std::tie(A, B, C, M, BitWidth) = *T;
9479   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9480   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9481   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9482   auto SL = SolveForBoundary(Lower);
9483   auto SU = SolveForBoundary(Upper);
9484   // If any of the solutions was unknown, no meaninigful conclusions can
9485   // be made.
9486   if (!SL.second || !SU.second)
9487     return None;
9488 
9489   // Claim: The correct solution is not some value between Min and Max.
9490   //
9491   // Justification: Assuming that Min and Max are different values, one of
9492   // them is when the first signed overflow happens, the other is when the
9493   // first unsigned overflow happens. Crossing the range boundary is only
9494   // possible via an overflow (treating 0 as a special case of it, modeling
9495   // an overflow as crossing k*2^W for some k).
9496   //
9497   // The interesting case here is when Min was eliminated as an invalid
9498   // solution, but Max was not. The argument is that if there was another
9499   // overflow between Min and Max, it would also have been eliminated if
9500   // it was considered.
9501   //
9502   // For a given boundary, it is possible to have two overflows of the same
9503   // type (signed/unsigned) without having the other type in between: this
9504   // can happen when the vertex of the parabola is between the iterations
9505   // corresponding to the overflows. This is only possible when the two
9506   // overflows cross k*2^W for the same k. In such case, if the second one
9507   // left the range (and was the first one to do so), the first overflow
9508   // would have to enter the range, which would mean that either we had left
9509   // the range before or that we started outside of it. Both of these cases
9510   // are contradictions.
9511   //
9512   // Claim: In the case where SolveForBoundary returns None, the correct
9513   // solution is not some value between the Max for this boundary and the
9514   // Min of the other boundary.
9515   //
9516   // Justification: Assume that we had such Max_A and Min_B corresponding
9517   // to range boundaries A and B and such that Max_A < Min_B. If there was
9518   // a solution between Max_A and Min_B, it would have to be caused by an
9519   // overflow corresponding to either A or B. It cannot correspond to B,
9520   // since Min_B is the first occurrence of such an overflow. If it
9521   // corresponded to A, it would have to be either a signed or an unsigned
9522   // overflow that is larger than both eliminated overflows for A. But
9523   // between the eliminated overflows and this overflow, the values would
9524   // cover the entire value space, thus crossing the other boundary, which
9525   // is a contradiction.
9526 
9527   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9528 }
9529 
9530 ScalarEvolution::ExitLimit
9531 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9532                               bool AllowPredicates) {
9533 
9534   // This is only used for loops with a "x != y" exit test. The exit condition
9535   // is now expressed as a single expression, V = x-y. So the exit test is
9536   // effectively V != 0.  We know and take advantage of the fact that this
9537   // expression only being used in a comparison by zero context.
9538 
9539   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9540   // If the value is a constant
9541   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9542     // If the value is already zero, the branch will execute zero times.
9543     if (C->getValue()->isZero()) return C;
9544     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9545   }
9546 
9547   const SCEVAddRecExpr *AddRec =
9548       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9549 
9550   if (!AddRec && AllowPredicates)
9551     // Try to make this an AddRec using runtime tests, in the first X
9552     // iterations of this loop, where X is the SCEV expression found by the
9553     // algorithm below.
9554     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9555 
9556   if (!AddRec || AddRec->getLoop() != L)
9557     return getCouldNotCompute();
9558 
9559   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9560   // the quadratic equation to solve it.
9561   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9562     // We can only use this value if the chrec ends up with an exact zero
9563     // value at this index.  When solving for "X*X != 5", for example, we
9564     // should not accept a root of 2.
9565     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9566       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9567       return ExitLimit(R, R, false, Predicates);
9568     }
9569     return getCouldNotCompute();
9570   }
9571 
9572   // Otherwise we can only handle this if it is affine.
9573   if (!AddRec->isAffine())
9574     return getCouldNotCompute();
9575 
9576   // If this is an affine expression, the execution count of this branch is
9577   // the minimum unsigned root of the following equation:
9578   //
9579   //     Start + Step*N = 0 (mod 2^BW)
9580   //
9581   // equivalent to:
9582   //
9583   //             Step*N = -Start (mod 2^BW)
9584   //
9585   // where BW is the common bit width of Start and Step.
9586 
9587   // Get the initial value for the loop.
9588   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9589   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9590 
9591   // For now we handle only constant steps.
9592   //
9593   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9594   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9595   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9596   // We have not yet seen any such cases.
9597   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9598   if (!StepC || StepC->getValue()->isZero())
9599     return getCouldNotCompute();
9600 
9601   // For positive steps (counting up until unsigned overflow):
9602   //   N = -Start/Step (as unsigned)
9603   // For negative steps (counting down to zero):
9604   //   N = Start/-Step
9605   // First compute the unsigned distance from zero in the direction of Step.
9606   bool CountDown = StepC->getAPInt().isNegative();
9607   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9608 
9609   // Handle unitary steps, which cannot wraparound.
9610   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9611   //   N = Distance (as unsigned)
9612   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9613     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9614     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
9615 
9616     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9617     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9618     // case, and see if we can improve the bound.
9619     //
9620     // Explicitly handling this here is necessary because getUnsignedRange
9621     // isn't context-sensitive; it doesn't know that we only care about the
9622     // range inside the loop.
9623     const SCEV *Zero = getZero(Distance->getType());
9624     const SCEV *One = getOne(Distance->getType());
9625     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9626     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9627       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9628       // as "unsigned_max(Distance + 1) - 1".
9629       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9630       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9631     }
9632     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9633   }
9634 
9635   // If the condition controls loop exit (the loop exits only if the expression
9636   // is true) and the addition is no-wrap we can use unsigned divide to
9637   // compute the backedge count.  In this case, the step may not divide the
9638   // distance, but we don't care because if the condition is "missed" the loop
9639   // will have undefined behavior due to wrapping.
9640   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9641       loopHasNoAbnormalExits(AddRec->getLoop())) {
9642     const SCEV *Exact =
9643         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9644     const SCEV *Max = getCouldNotCompute();
9645     if (Exact != getCouldNotCompute()) {
9646       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
9647       Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
9648     }
9649     return ExitLimit(Exact, Max, false, Predicates);
9650   }
9651 
9652   // Solve the general equation.
9653   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9654                                                getNegativeSCEV(Start), *this);
9655 
9656   const SCEV *M = E;
9657   if (E != getCouldNotCompute()) {
9658     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
9659     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
9660   }
9661   return ExitLimit(E, M, false, Predicates);
9662 }
9663 
9664 ScalarEvolution::ExitLimit
9665 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9666   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9667   // handle them yet except for the trivial case.  This could be expanded in the
9668   // future as needed.
9669 
9670   // If the value is a constant, check to see if it is known to be non-zero
9671   // already.  If so, the backedge will execute zero times.
9672   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9673     if (!C->getValue()->isZero())
9674       return getZero(C->getType());
9675     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9676   }
9677 
9678   // We could implement others, but I really doubt anyone writes loops like
9679   // this, and if they did, they would already be constant folded.
9680   return getCouldNotCompute();
9681 }
9682 
9683 std::pair<const BasicBlock *, const BasicBlock *>
9684 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9685     const {
9686   // If the block has a unique predecessor, then there is no path from the
9687   // predecessor to the block that does not go through the direct edge
9688   // from the predecessor to the block.
9689   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9690     return {Pred, BB};
9691 
9692   // A loop's header is defined to be a block that dominates the loop.
9693   // If the header has a unique predecessor outside the loop, it must be
9694   // a block that has exactly one successor that can reach the loop.
9695   if (const Loop *L = LI.getLoopFor(BB))
9696     return {L->getLoopPredecessor(), L->getHeader()};
9697 
9698   return {nullptr, nullptr};
9699 }
9700 
9701 /// SCEV structural equivalence is usually sufficient for testing whether two
9702 /// expressions are equal, however for the purposes of looking for a condition
9703 /// guarding a loop, it can be useful to be a little more general, since a
9704 /// front-end may have replicated the controlling expression.
9705 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9706   // Quick check to see if they are the same SCEV.
9707   if (A == B) return true;
9708 
9709   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9710     // Not all instructions that are "identical" compute the same value.  For
9711     // instance, two distinct alloca instructions allocating the same type are
9712     // identical and do not read memory; but compute distinct values.
9713     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9714   };
9715 
9716   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9717   // two different instructions with the same value. Check for this case.
9718   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9719     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9720       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9721         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9722           if (ComputesEqualValues(AI, BI))
9723             return true;
9724 
9725   // Otherwise assume they may have a different value.
9726   return false;
9727 }
9728 
9729 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9730                                            const SCEV *&LHS, const SCEV *&RHS,
9731                                            unsigned Depth) {
9732   bool Changed = false;
9733   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9734   // '0 != 0'.
9735   auto TrivialCase = [&](bool TriviallyTrue) {
9736     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9737     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9738     return true;
9739   };
9740   // If we hit the max recursion limit bail out.
9741   if (Depth >= 3)
9742     return false;
9743 
9744   // Canonicalize a constant to the right side.
9745   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9746     // Check for both operands constant.
9747     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9748       if (ConstantExpr::getICmp(Pred,
9749                                 LHSC->getValue(),
9750                                 RHSC->getValue())->isNullValue())
9751         return TrivialCase(false);
9752       else
9753         return TrivialCase(true);
9754     }
9755     // Otherwise swap the operands to put the constant on the right.
9756     std::swap(LHS, RHS);
9757     Pred = ICmpInst::getSwappedPredicate(Pred);
9758     Changed = true;
9759   }
9760 
9761   // If we're comparing an addrec with a value which is loop-invariant in the
9762   // addrec's loop, put the addrec on the left. Also make a dominance check,
9763   // as both operands could be addrecs loop-invariant in each other's loop.
9764   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9765     const Loop *L = AR->getLoop();
9766     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9767       std::swap(LHS, RHS);
9768       Pred = ICmpInst::getSwappedPredicate(Pred);
9769       Changed = true;
9770     }
9771   }
9772 
9773   // If there's a constant operand, canonicalize comparisons with boundary
9774   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9775   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9776     const APInt &RA = RC->getAPInt();
9777 
9778     bool SimplifiedByConstantRange = false;
9779 
9780     if (!ICmpInst::isEquality(Pred)) {
9781       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9782       if (ExactCR.isFullSet())
9783         return TrivialCase(true);
9784       else if (ExactCR.isEmptySet())
9785         return TrivialCase(false);
9786 
9787       APInt NewRHS;
9788       CmpInst::Predicate NewPred;
9789       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9790           ICmpInst::isEquality(NewPred)) {
9791         // We were able to convert an inequality to an equality.
9792         Pred = NewPred;
9793         RHS = getConstant(NewRHS);
9794         Changed = SimplifiedByConstantRange = true;
9795       }
9796     }
9797 
9798     if (!SimplifiedByConstantRange) {
9799       switch (Pred) {
9800       default:
9801         break;
9802       case ICmpInst::ICMP_EQ:
9803       case ICmpInst::ICMP_NE:
9804         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9805         if (!RA)
9806           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9807             if (const SCEVMulExpr *ME =
9808                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9809               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9810                   ME->getOperand(0)->isAllOnesValue()) {
9811                 RHS = AE->getOperand(1);
9812                 LHS = ME->getOperand(1);
9813                 Changed = true;
9814               }
9815         break;
9816 
9817 
9818         // The "Should have been caught earlier!" messages refer to the fact
9819         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9820         // should have fired on the corresponding cases, and canonicalized the
9821         // check to trivial case.
9822 
9823       case ICmpInst::ICMP_UGE:
9824         assert(!RA.isMinValue() && "Should have been caught earlier!");
9825         Pred = ICmpInst::ICMP_UGT;
9826         RHS = getConstant(RA - 1);
9827         Changed = true;
9828         break;
9829       case ICmpInst::ICMP_ULE:
9830         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9831         Pred = ICmpInst::ICMP_ULT;
9832         RHS = getConstant(RA + 1);
9833         Changed = true;
9834         break;
9835       case ICmpInst::ICMP_SGE:
9836         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9837         Pred = ICmpInst::ICMP_SGT;
9838         RHS = getConstant(RA - 1);
9839         Changed = true;
9840         break;
9841       case ICmpInst::ICMP_SLE:
9842         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9843         Pred = ICmpInst::ICMP_SLT;
9844         RHS = getConstant(RA + 1);
9845         Changed = true;
9846         break;
9847       }
9848     }
9849   }
9850 
9851   // Check for obvious equality.
9852   if (HasSameValue(LHS, RHS)) {
9853     if (ICmpInst::isTrueWhenEqual(Pred))
9854       return TrivialCase(true);
9855     if (ICmpInst::isFalseWhenEqual(Pred))
9856       return TrivialCase(false);
9857   }
9858 
9859   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9860   // adding or subtracting 1 from one of the operands.
9861   switch (Pred) {
9862   case ICmpInst::ICMP_SLE:
9863     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9864       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9865                        SCEV::FlagNSW);
9866       Pred = ICmpInst::ICMP_SLT;
9867       Changed = true;
9868     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9869       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9870                        SCEV::FlagNSW);
9871       Pred = ICmpInst::ICMP_SLT;
9872       Changed = true;
9873     }
9874     break;
9875   case ICmpInst::ICMP_SGE:
9876     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9877       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9878                        SCEV::FlagNSW);
9879       Pred = ICmpInst::ICMP_SGT;
9880       Changed = true;
9881     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9882       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9883                        SCEV::FlagNSW);
9884       Pred = ICmpInst::ICMP_SGT;
9885       Changed = true;
9886     }
9887     break;
9888   case ICmpInst::ICMP_ULE:
9889     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9890       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9891                        SCEV::FlagNUW);
9892       Pred = ICmpInst::ICMP_ULT;
9893       Changed = true;
9894     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9895       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9896       Pred = ICmpInst::ICMP_ULT;
9897       Changed = true;
9898     }
9899     break;
9900   case ICmpInst::ICMP_UGE:
9901     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9902       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9903       Pred = ICmpInst::ICMP_UGT;
9904       Changed = true;
9905     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9906       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9907                        SCEV::FlagNUW);
9908       Pred = ICmpInst::ICMP_UGT;
9909       Changed = true;
9910     }
9911     break;
9912   default:
9913     break;
9914   }
9915 
9916   // TODO: More simplifications are possible here.
9917 
9918   // Recursively simplify until we either hit a recursion limit or nothing
9919   // changes.
9920   if (Changed)
9921     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9922 
9923   return Changed;
9924 }
9925 
9926 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9927   return getSignedRangeMax(S).isNegative();
9928 }
9929 
9930 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9931   return getSignedRangeMin(S).isStrictlyPositive();
9932 }
9933 
9934 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9935   return !getSignedRangeMin(S).isNegative();
9936 }
9937 
9938 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9939   return !getSignedRangeMax(S).isStrictlyPositive();
9940 }
9941 
9942 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9943   return getUnsignedRangeMin(S) != 0;
9944 }
9945 
9946 std::pair<const SCEV *, const SCEV *>
9947 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9948   // Compute SCEV on entry of loop L.
9949   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9950   if (Start == getCouldNotCompute())
9951     return { Start, Start };
9952   // Compute post increment SCEV for loop L.
9953   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9954   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9955   return { Start, PostInc };
9956 }
9957 
9958 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9959                                           const SCEV *LHS, const SCEV *RHS) {
9960   // First collect all loops.
9961   SmallPtrSet<const Loop *, 8> LoopsUsed;
9962   getUsedLoops(LHS, LoopsUsed);
9963   getUsedLoops(RHS, LoopsUsed);
9964 
9965   if (LoopsUsed.empty())
9966     return false;
9967 
9968   // Domination relationship must be a linear order on collected loops.
9969 #ifndef NDEBUG
9970   for (auto *L1 : LoopsUsed)
9971     for (auto *L2 : LoopsUsed)
9972       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9973               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9974              "Domination relationship is not a linear order");
9975 #endif
9976 
9977   const Loop *MDL =
9978       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9979                         [&](const Loop *L1, const Loop *L2) {
9980          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9981        });
9982 
9983   // Get init and post increment value for LHS.
9984   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9985   // if LHS contains unknown non-invariant SCEV then bail out.
9986   if (SplitLHS.first == getCouldNotCompute())
9987     return false;
9988   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9989   // Get init and post increment value for RHS.
9990   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9991   // if RHS contains unknown non-invariant SCEV then bail out.
9992   if (SplitRHS.first == getCouldNotCompute())
9993     return false;
9994   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9995   // It is possible that init SCEV contains an invariant load but it does
9996   // not dominate MDL and is not available at MDL loop entry, so we should
9997   // check it here.
9998   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9999       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10000     return false;
10001 
10002   // It seems backedge guard check is faster than entry one so in some cases
10003   // it can speed up whole estimation by short circuit
10004   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10005                                      SplitRHS.second) &&
10006          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10007 }
10008 
10009 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10010                                        const SCEV *LHS, const SCEV *RHS) {
10011   // Canonicalize the inputs first.
10012   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10013 
10014   if (isKnownViaInduction(Pred, LHS, RHS))
10015     return true;
10016 
10017   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10018     return true;
10019 
10020   // Otherwise see what can be done with some simple reasoning.
10021   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10022 }
10023 
10024 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10025                                                   const SCEV *LHS,
10026                                                   const SCEV *RHS) {
10027   if (isKnownPredicate(Pred, LHS, RHS))
10028     return true;
10029   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10030     return false;
10031   return None;
10032 }
10033 
10034 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10035                                          const SCEV *LHS, const SCEV *RHS,
10036                                          const Instruction *CtxI) {
10037   // TODO: Analyze guards and assumes from Context's block.
10038   return isKnownPredicate(Pred, LHS, RHS) ||
10039          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10040 }
10041 
10042 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred,
10043                                                     const SCEV *LHS,
10044                                                     const SCEV *RHS,
10045                                                     const Instruction *CtxI) {
10046   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10047   if (KnownWithoutContext)
10048     return KnownWithoutContext;
10049 
10050   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10051     return true;
10052   else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10053                                           ICmpInst::getInversePredicate(Pred),
10054                                           LHS, RHS))
10055     return false;
10056   return None;
10057 }
10058 
10059 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10060                                               const SCEVAddRecExpr *LHS,
10061                                               const SCEV *RHS) {
10062   const Loop *L = LHS->getLoop();
10063   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10064          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10065 }
10066 
10067 Optional<ScalarEvolution::MonotonicPredicateType>
10068 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10069                                            ICmpInst::Predicate Pred) {
10070   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10071 
10072 #ifndef NDEBUG
10073   // Verify an invariant: inverting the predicate should turn a monotonically
10074   // increasing change to a monotonically decreasing one, and vice versa.
10075   if (Result) {
10076     auto ResultSwapped =
10077         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10078 
10079     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
10080     assert(ResultSwapped.getValue() != Result.getValue() &&
10081            "monotonicity should flip as we flip the predicate");
10082   }
10083 #endif
10084 
10085   return Result;
10086 }
10087 
10088 Optional<ScalarEvolution::MonotonicPredicateType>
10089 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10090                                                ICmpInst::Predicate Pred) {
10091   // A zero step value for LHS means the induction variable is essentially a
10092   // loop invariant value. We don't really depend on the predicate actually
10093   // flipping from false to true (for increasing predicates, and the other way
10094   // around for decreasing predicates), all we care about is that *if* the
10095   // predicate changes then it only changes from false to true.
10096   //
10097   // A zero step value in itself is not very useful, but there may be places
10098   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10099   // as general as possible.
10100 
10101   // Only handle LE/LT/GE/GT predicates.
10102   if (!ICmpInst::isRelational(Pred))
10103     return None;
10104 
10105   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10106   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10107          "Should be greater or less!");
10108 
10109   // Check that AR does not wrap.
10110   if (ICmpInst::isUnsigned(Pred)) {
10111     if (!LHS->hasNoUnsignedWrap())
10112       return None;
10113     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10114   } else {
10115     assert(ICmpInst::isSigned(Pred) &&
10116            "Relational predicate is either signed or unsigned!");
10117     if (!LHS->hasNoSignedWrap())
10118       return None;
10119 
10120     const SCEV *Step = LHS->getStepRecurrence(*this);
10121 
10122     if (isKnownNonNegative(Step))
10123       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10124 
10125     if (isKnownNonPositive(Step))
10126       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10127 
10128     return None;
10129   }
10130 }
10131 
10132 Optional<ScalarEvolution::LoopInvariantPredicate>
10133 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10134                                            const SCEV *LHS, const SCEV *RHS,
10135                                            const Loop *L) {
10136 
10137   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10138   if (!isLoopInvariant(RHS, L)) {
10139     if (!isLoopInvariant(LHS, L))
10140       return None;
10141 
10142     std::swap(LHS, RHS);
10143     Pred = ICmpInst::getSwappedPredicate(Pred);
10144   }
10145 
10146   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10147   if (!ArLHS || ArLHS->getLoop() != L)
10148     return None;
10149 
10150   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10151   if (!MonotonicType)
10152     return None;
10153   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10154   // true as the loop iterates, and the backedge is control dependent on
10155   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10156   //
10157   //   * if the predicate was false in the first iteration then the predicate
10158   //     is never evaluated again, since the loop exits without taking the
10159   //     backedge.
10160   //   * if the predicate was true in the first iteration then it will
10161   //     continue to be true for all future iterations since it is
10162   //     monotonically increasing.
10163   //
10164   // For both the above possibilities, we can replace the loop varying
10165   // predicate with its value on the first iteration of the loop (which is
10166   // loop invariant).
10167   //
10168   // A similar reasoning applies for a monotonically decreasing predicate, by
10169   // replacing true with false and false with true in the above two bullets.
10170   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10171   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10172 
10173   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10174     return None;
10175 
10176   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10177 }
10178 
10179 Optional<ScalarEvolution::LoopInvariantPredicate>
10180 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10181     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10182     const Instruction *CtxI, const SCEV *MaxIter) {
10183   // Try to prove the following set of facts:
10184   // - The predicate is monotonic in the iteration space.
10185   // - If the check does not fail on the 1st iteration:
10186   //   - No overflow will happen during first MaxIter iterations;
10187   //   - It will not fail on the MaxIter'th iteration.
10188   // If the check does fail on the 1st iteration, we leave the loop and no
10189   // other checks matter.
10190 
10191   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10192   if (!isLoopInvariant(RHS, L)) {
10193     if (!isLoopInvariant(LHS, L))
10194       return None;
10195 
10196     std::swap(LHS, RHS);
10197     Pred = ICmpInst::getSwappedPredicate(Pred);
10198   }
10199 
10200   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10201   if (!AR || AR->getLoop() != L)
10202     return None;
10203 
10204   // The predicate must be relational (i.e. <, <=, >=, >).
10205   if (!ICmpInst::isRelational(Pred))
10206     return None;
10207 
10208   // TODO: Support steps other than +/- 1.
10209   const SCEV *Step = AR->getStepRecurrence(*this);
10210   auto *One = getOne(Step->getType());
10211   auto *MinusOne = getNegativeSCEV(One);
10212   if (Step != One && Step != MinusOne)
10213     return None;
10214 
10215   // Type mismatch here means that MaxIter is potentially larger than max
10216   // unsigned value in start type, which mean we cannot prove no wrap for the
10217   // indvar.
10218   if (AR->getType() != MaxIter->getType())
10219     return None;
10220 
10221   // Value of IV on suggested last iteration.
10222   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10223   // Does it still meet the requirement?
10224   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10225     return None;
10226   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10227   // not exceed max unsigned value of this type), this effectively proves
10228   // that there is no wrap during the iteration. To prove that there is no
10229   // signed/unsigned wrap, we need to check that
10230   // Start <= Last for step = 1 or Start >= Last for step = -1.
10231   ICmpInst::Predicate NoOverflowPred =
10232       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10233   if (Step == MinusOne)
10234     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10235   const SCEV *Start = AR->getStart();
10236   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
10237     return None;
10238 
10239   // Everything is fine.
10240   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10241 }
10242 
10243 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10244     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10245   if (HasSameValue(LHS, RHS))
10246     return ICmpInst::isTrueWhenEqual(Pred);
10247 
10248   // This code is split out from isKnownPredicate because it is called from
10249   // within isLoopEntryGuardedByCond.
10250 
10251   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10252                          const ConstantRange &RangeRHS) {
10253     return RangeLHS.icmp(Pred, RangeRHS);
10254   };
10255 
10256   // The check at the top of the function catches the case where the values are
10257   // known to be equal.
10258   if (Pred == CmpInst::ICMP_EQ)
10259     return false;
10260 
10261   if (Pred == CmpInst::ICMP_NE) {
10262     if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10263         CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)))
10264       return true;
10265     auto *Diff = getMinusSCEV(LHS, RHS);
10266     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10267   }
10268 
10269   if (CmpInst::isSigned(Pred))
10270     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10271 
10272   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10273 }
10274 
10275 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10276                                                     const SCEV *LHS,
10277                                                     const SCEV *RHS) {
10278   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10279   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10280   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10281   // OutC1 and OutC2.
10282   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10283                                       APInt &OutC1, APInt &OutC2,
10284                                       SCEV::NoWrapFlags ExpectedFlags) {
10285     const SCEV *XNonConstOp, *XConstOp;
10286     const SCEV *YNonConstOp, *YConstOp;
10287     SCEV::NoWrapFlags XFlagsPresent;
10288     SCEV::NoWrapFlags YFlagsPresent;
10289 
10290     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10291       XConstOp = getZero(X->getType());
10292       XNonConstOp = X;
10293       XFlagsPresent = ExpectedFlags;
10294     }
10295     if (!isa<SCEVConstant>(XConstOp) ||
10296         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10297       return false;
10298 
10299     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10300       YConstOp = getZero(Y->getType());
10301       YNonConstOp = Y;
10302       YFlagsPresent = ExpectedFlags;
10303     }
10304 
10305     if (!isa<SCEVConstant>(YConstOp) ||
10306         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10307       return false;
10308 
10309     if (YNonConstOp != XNonConstOp)
10310       return false;
10311 
10312     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10313     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10314 
10315     return true;
10316   };
10317 
10318   APInt C1;
10319   APInt C2;
10320 
10321   switch (Pred) {
10322   default:
10323     break;
10324 
10325   case ICmpInst::ICMP_SGE:
10326     std::swap(LHS, RHS);
10327     LLVM_FALLTHROUGH;
10328   case ICmpInst::ICMP_SLE:
10329     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10330     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10331       return true;
10332 
10333     break;
10334 
10335   case ICmpInst::ICMP_SGT:
10336     std::swap(LHS, RHS);
10337     LLVM_FALLTHROUGH;
10338   case ICmpInst::ICMP_SLT:
10339     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10340     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10341       return true;
10342 
10343     break;
10344 
10345   case ICmpInst::ICMP_UGE:
10346     std::swap(LHS, RHS);
10347     LLVM_FALLTHROUGH;
10348   case ICmpInst::ICMP_ULE:
10349     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10350     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10351       return true;
10352 
10353     break;
10354 
10355   case ICmpInst::ICMP_UGT:
10356     std::swap(LHS, RHS);
10357     LLVM_FALLTHROUGH;
10358   case ICmpInst::ICMP_ULT:
10359     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10360     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10361       return true;
10362     break;
10363   }
10364 
10365   return false;
10366 }
10367 
10368 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10369                                                    const SCEV *LHS,
10370                                                    const SCEV *RHS) {
10371   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10372     return false;
10373 
10374   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10375   // the stack can result in exponential time complexity.
10376   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10377 
10378   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10379   //
10380   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10381   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10382   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10383   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10384   // use isKnownPredicate later if needed.
10385   return isKnownNonNegative(RHS) &&
10386          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10387          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10388 }
10389 
10390 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10391                                         ICmpInst::Predicate Pred,
10392                                         const SCEV *LHS, const SCEV *RHS) {
10393   // No need to even try if we know the module has no guards.
10394   if (!HasGuards)
10395     return false;
10396 
10397   return any_of(*BB, [&](const Instruction &I) {
10398     using namespace llvm::PatternMatch;
10399 
10400     Value *Condition;
10401     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10402                          m_Value(Condition))) &&
10403            isImpliedCond(Pred, LHS, RHS, Condition, false);
10404   });
10405 }
10406 
10407 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10408 /// protected by a conditional between LHS and RHS.  This is used to
10409 /// to eliminate casts.
10410 bool
10411 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10412                                              ICmpInst::Predicate Pred,
10413                                              const SCEV *LHS, const SCEV *RHS) {
10414   // Interpret a null as meaning no loop, where there is obviously no guard
10415   // (interprocedural conditions notwithstanding).
10416   if (!L) return true;
10417 
10418   if (VerifyIR)
10419     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10420            "This cannot be done on broken IR!");
10421 
10422 
10423   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10424     return true;
10425 
10426   BasicBlock *Latch = L->getLoopLatch();
10427   if (!Latch)
10428     return false;
10429 
10430   BranchInst *LoopContinuePredicate =
10431     dyn_cast<BranchInst>(Latch->getTerminator());
10432   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10433       isImpliedCond(Pred, LHS, RHS,
10434                     LoopContinuePredicate->getCondition(),
10435                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10436     return true;
10437 
10438   // We don't want more than one activation of the following loops on the stack
10439   // -- that can lead to O(n!) time complexity.
10440   if (WalkingBEDominatingConds)
10441     return false;
10442 
10443   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10444 
10445   // See if we can exploit a trip count to prove the predicate.
10446   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10447   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10448   if (LatchBECount != getCouldNotCompute()) {
10449     // We know that Latch branches back to the loop header exactly
10450     // LatchBECount times.  This means the backdege condition at Latch is
10451     // equivalent to  "{0,+,1} u< LatchBECount".
10452     Type *Ty = LatchBECount->getType();
10453     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10454     const SCEV *LoopCounter =
10455       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10456     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10457                       LatchBECount))
10458       return true;
10459   }
10460 
10461   // Check conditions due to any @llvm.assume intrinsics.
10462   for (auto &AssumeVH : AC.assumptions()) {
10463     if (!AssumeVH)
10464       continue;
10465     auto *CI = cast<CallInst>(AssumeVH);
10466     if (!DT.dominates(CI, Latch->getTerminator()))
10467       continue;
10468 
10469     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10470       return true;
10471   }
10472 
10473   // If the loop is not reachable from the entry block, we risk running into an
10474   // infinite loop as we walk up into the dom tree.  These loops do not matter
10475   // anyway, so we just return a conservative answer when we see them.
10476   if (!DT.isReachableFromEntry(L->getHeader()))
10477     return false;
10478 
10479   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10480     return true;
10481 
10482   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10483        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10484     assert(DTN && "should reach the loop header before reaching the root!");
10485 
10486     BasicBlock *BB = DTN->getBlock();
10487     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10488       return true;
10489 
10490     BasicBlock *PBB = BB->getSinglePredecessor();
10491     if (!PBB)
10492       continue;
10493 
10494     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10495     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10496       continue;
10497 
10498     Value *Condition = ContinuePredicate->getCondition();
10499 
10500     // If we have an edge `E` within the loop body that dominates the only
10501     // latch, the condition guarding `E` also guards the backedge.  This
10502     // reasoning works only for loops with a single latch.
10503 
10504     BasicBlockEdge DominatingEdge(PBB, BB);
10505     if (DominatingEdge.isSingleEdge()) {
10506       // We're constructively (and conservatively) enumerating edges within the
10507       // loop body that dominate the latch.  The dominator tree better agree
10508       // with us on this:
10509       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10510 
10511       if (isImpliedCond(Pred, LHS, RHS, Condition,
10512                         BB != ContinuePredicate->getSuccessor(0)))
10513         return true;
10514     }
10515   }
10516 
10517   return false;
10518 }
10519 
10520 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10521                                                      ICmpInst::Predicate Pred,
10522                                                      const SCEV *LHS,
10523                                                      const SCEV *RHS) {
10524   if (VerifyIR)
10525     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10526            "This cannot be done on broken IR!");
10527 
10528   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10529   // the facts (a >= b && a != b) separately. A typical situation is when the
10530   // non-strict comparison is known from ranges and non-equality is known from
10531   // dominating predicates. If we are proving strict comparison, we always try
10532   // to prove non-equality and non-strict comparison separately.
10533   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10534   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10535   bool ProvedNonStrictComparison = false;
10536   bool ProvedNonEquality = false;
10537 
10538   auto SplitAndProve =
10539     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10540     if (!ProvedNonStrictComparison)
10541       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10542     if (!ProvedNonEquality)
10543       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10544     if (ProvedNonStrictComparison && ProvedNonEquality)
10545       return true;
10546     return false;
10547   };
10548 
10549   if (ProvingStrictComparison) {
10550     auto ProofFn = [&](ICmpInst::Predicate P) {
10551       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10552     };
10553     if (SplitAndProve(ProofFn))
10554       return true;
10555   }
10556 
10557   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10558   auto ProveViaGuard = [&](const BasicBlock *Block) {
10559     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10560       return true;
10561     if (ProvingStrictComparison) {
10562       auto ProofFn = [&](ICmpInst::Predicate P) {
10563         return isImpliedViaGuard(Block, P, LHS, RHS);
10564       };
10565       if (SplitAndProve(ProofFn))
10566         return true;
10567     }
10568     return false;
10569   };
10570 
10571   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10572   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10573     const Instruction *CtxI = &BB->front();
10574     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
10575       return true;
10576     if (ProvingStrictComparison) {
10577       auto ProofFn = [&](ICmpInst::Predicate P) {
10578         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
10579       };
10580       if (SplitAndProve(ProofFn))
10581         return true;
10582     }
10583     return false;
10584   };
10585 
10586   // Starting at the block's predecessor, climb up the predecessor chain, as long
10587   // as there are predecessors that can be found that have unique successors
10588   // leading to the original block.
10589   const Loop *ContainingLoop = LI.getLoopFor(BB);
10590   const BasicBlock *PredBB;
10591   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10592     PredBB = ContainingLoop->getLoopPredecessor();
10593   else
10594     PredBB = BB->getSinglePredecessor();
10595   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10596        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10597     if (ProveViaGuard(Pair.first))
10598       return true;
10599 
10600     const BranchInst *LoopEntryPredicate =
10601         dyn_cast<BranchInst>(Pair.first->getTerminator());
10602     if (!LoopEntryPredicate ||
10603         LoopEntryPredicate->isUnconditional())
10604       continue;
10605 
10606     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10607                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10608       return true;
10609   }
10610 
10611   // Check conditions due to any @llvm.assume intrinsics.
10612   for (auto &AssumeVH : AC.assumptions()) {
10613     if (!AssumeVH)
10614       continue;
10615     auto *CI = cast<CallInst>(AssumeVH);
10616     if (!DT.dominates(CI, BB))
10617       continue;
10618 
10619     if (ProveViaCond(CI->getArgOperand(0), false))
10620       return true;
10621   }
10622 
10623   return false;
10624 }
10625 
10626 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10627                                                ICmpInst::Predicate Pred,
10628                                                const SCEV *LHS,
10629                                                const SCEV *RHS) {
10630   // Interpret a null as meaning no loop, where there is obviously no guard
10631   // (interprocedural conditions notwithstanding).
10632   if (!L)
10633     return false;
10634 
10635   // Both LHS and RHS must be available at loop entry.
10636   assert(isAvailableAtLoopEntry(LHS, L) &&
10637          "LHS is not available at Loop Entry");
10638   assert(isAvailableAtLoopEntry(RHS, L) &&
10639          "RHS is not available at Loop Entry");
10640 
10641   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10642     return true;
10643 
10644   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10645 }
10646 
10647 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10648                                     const SCEV *RHS,
10649                                     const Value *FoundCondValue, bool Inverse,
10650                                     const Instruction *CtxI) {
10651   // False conditions implies anything. Do not bother analyzing it further.
10652   if (FoundCondValue ==
10653       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10654     return true;
10655 
10656   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10657     return false;
10658 
10659   auto ClearOnExit =
10660       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10661 
10662   // Recursively handle And and Or conditions.
10663   const Value *Op0, *Op1;
10664   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10665     if (!Inverse)
10666       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
10667              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
10668   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10669     if (Inverse)
10670       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
10671              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
10672   }
10673 
10674   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10675   if (!ICI) return false;
10676 
10677   // Now that we found a conditional branch that dominates the loop or controls
10678   // the loop latch. Check to see if it is the comparison we are looking for.
10679   ICmpInst::Predicate FoundPred;
10680   if (Inverse)
10681     FoundPred = ICI->getInversePredicate();
10682   else
10683     FoundPred = ICI->getPredicate();
10684 
10685   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10686   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10687 
10688   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
10689 }
10690 
10691 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10692                                     const SCEV *RHS,
10693                                     ICmpInst::Predicate FoundPred,
10694                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10695                                     const Instruction *CtxI) {
10696   // Balance the types.
10697   if (getTypeSizeInBits(LHS->getType()) <
10698       getTypeSizeInBits(FoundLHS->getType())) {
10699     // For unsigned and equality predicates, try to prove that both found
10700     // operands fit into narrow unsigned range. If so, try to prove facts in
10701     // narrow types.
10702     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) {
10703       auto *NarrowType = LHS->getType();
10704       auto *WideType = FoundLHS->getType();
10705       auto BitWidth = getTypeSizeInBits(NarrowType);
10706       const SCEV *MaxValue = getZeroExtendExpr(
10707           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10708       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
10709                                           MaxValue) &&
10710           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
10711                                           MaxValue)) {
10712         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10713         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10714         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10715                                        TruncFoundRHS, CtxI))
10716           return true;
10717       }
10718     }
10719 
10720     if (LHS->getType()->isPointerTy())
10721       return false;
10722     if (CmpInst::isSigned(Pred)) {
10723       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10724       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10725     } else {
10726       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10727       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10728     }
10729   } else if (getTypeSizeInBits(LHS->getType()) >
10730       getTypeSizeInBits(FoundLHS->getType())) {
10731     if (FoundLHS->getType()->isPointerTy())
10732       return false;
10733     if (CmpInst::isSigned(FoundPred)) {
10734       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10735       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10736     } else {
10737       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10738       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10739     }
10740   }
10741   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10742                                     FoundRHS, CtxI);
10743 }
10744 
10745 bool ScalarEvolution::isImpliedCondBalancedTypes(
10746     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10747     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10748     const Instruction *CtxI) {
10749   assert(getTypeSizeInBits(LHS->getType()) ==
10750              getTypeSizeInBits(FoundLHS->getType()) &&
10751          "Types should be balanced!");
10752   // Canonicalize the query to match the way instcombine will have
10753   // canonicalized the comparison.
10754   if (SimplifyICmpOperands(Pred, LHS, RHS))
10755     if (LHS == RHS)
10756       return CmpInst::isTrueWhenEqual(Pred);
10757   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10758     if (FoundLHS == FoundRHS)
10759       return CmpInst::isFalseWhenEqual(FoundPred);
10760 
10761   // Check to see if we can make the LHS or RHS match.
10762   if (LHS == FoundRHS || RHS == FoundLHS) {
10763     if (isa<SCEVConstant>(RHS)) {
10764       std::swap(FoundLHS, FoundRHS);
10765       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10766     } else {
10767       std::swap(LHS, RHS);
10768       Pred = ICmpInst::getSwappedPredicate(Pred);
10769     }
10770   }
10771 
10772   // Check whether the found predicate is the same as the desired predicate.
10773   if (FoundPred == Pred)
10774     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
10775 
10776   // Check whether swapping the found predicate makes it the same as the
10777   // desired predicate.
10778   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10779     // We can write the implication
10780     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10781     // using one of the following ways:
10782     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10783     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10784     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10785     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10786     // Forms 1. and 2. require swapping the operands of one condition. Don't
10787     // do this if it would break canonical constant/addrec ordering.
10788     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10789       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10790                                    CtxI);
10791     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10792       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
10793 
10794     // There's no clear preference between forms 3. and 4., try both.  Avoid
10795     // forming getNotSCEV of pointer values as the resulting subtract is
10796     // not legal.
10797     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
10798         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10799                               FoundLHS, FoundRHS, CtxI))
10800       return true;
10801 
10802     if (!FoundLHS->getType()->isPointerTy() &&
10803         !FoundRHS->getType()->isPointerTy() &&
10804         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10805                               getNotSCEV(FoundRHS), CtxI))
10806       return true;
10807 
10808     return false;
10809   }
10810 
10811   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
10812                                    CmpInst::Predicate P2) {
10813     assert(P1 != P2 && "Handled earlier!");
10814     return CmpInst::isRelational(P2) &&
10815            P1 == CmpInst::getFlippedSignednessPredicate(P2);
10816   };
10817   if (IsSignFlippedPredicate(Pred, FoundPred)) {
10818     // Unsigned comparison is the same as signed comparison when both the
10819     // operands are non-negative or negative.
10820     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
10821         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
10822       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
10823     // Create local copies that we can freely swap and canonicalize our
10824     // conditions to "le/lt".
10825     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
10826     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
10827                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
10828     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
10829       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
10830       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
10831       std::swap(CanonicalLHS, CanonicalRHS);
10832       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
10833     }
10834     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
10835            "Must be!");
10836     assert((ICmpInst::isLT(CanonicalFoundPred) ||
10837             ICmpInst::isLE(CanonicalFoundPred)) &&
10838            "Must be!");
10839     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
10840       // Use implication:
10841       // x <u y && y >=s 0 --> x <s y.
10842       // If we can prove the left part, the right part is also proven.
10843       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
10844                                    CanonicalRHS, CanonicalFoundLHS,
10845                                    CanonicalFoundRHS);
10846     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
10847       // Use implication:
10848       // x <s y && y <s 0 --> x <u y.
10849       // If we can prove the left part, the right part is also proven.
10850       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
10851                                    CanonicalRHS, CanonicalFoundLHS,
10852                                    CanonicalFoundRHS);
10853   }
10854 
10855   // Check if we can make progress by sharpening ranges.
10856   if (FoundPred == ICmpInst::ICMP_NE &&
10857       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10858 
10859     const SCEVConstant *C = nullptr;
10860     const SCEV *V = nullptr;
10861 
10862     if (isa<SCEVConstant>(FoundLHS)) {
10863       C = cast<SCEVConstant>(FoundLHS);
10864       V = FoundRHS;
10865     } else {
10866       C = cast<SCEVConstant>(FoundRHS);
10867       V = FoundLHS;
10868     }
10869 
10870     // The guarding predicate tells us that C != V. If the known range
10871     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10872     // range we consider has to correspond to same signedness as the
10873     // predicate we're interested in folding.
10874 
10875     APInt Min = ICmpInst::isSigned(Pred) ?
10876         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10877 
10878     if (Min == C->getAPInt()) {
10879       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10880       // This is true even if (Min + 1) wraps around -- in case of
10881       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10882 
10883       APInt SharperMin = Min + 1;
10884 
10885       switch (Pred) {
10886         case ICmpInst::ICMP_SGE:
10887         case ICmpInst::ICMP_UGE:
10888           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10889           // RHS, we're done.
10890           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10891                                     CtxI))
10892             return true;
10893           LLVM_FALLTHROUGH;
10894 
10895         case ICmpInst::ICMP_SGT:
10896         case ICmpInst::ICMP_UGT:
10897           // We know from the range information that (V `Pred` Min ||
10898           // V == Min).  We know from the guarding condition that !(V
10899           // == Min).  This gives us
10900           //
10901           //       V `Pred` Min || V == Min && !(V == Min)
10902           //   =>  V `Pred` Min
10903           //
10904           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10905 
10906           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
10907             return true;
10908           break;
10909 
10910         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10911         case ICmpInst::ICMP_SLE:
10912         case ICmpInst::ICMP_ULE:
10913           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10914                                     LHS, V, getConstant(SharperMin), CtxI))
10915             return true;
10916           LLVM_FALLTHROUGH;
10917 
10918         case ICmpInst::ICMP_SLT:
10919         case ICmpInst::ICMP_ULT:
10920           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10921                                     LHS, V, getConstant(Min), CtxI))
10922             return true;
10923           break;
10924 
10925         default:
10926           // No change
10927           break;
10928       }
10929     }
10930   }
10931 
10932   // Check whether the actual condition is beyond sufficient.
10933   if (FoundPred == ICmpInst::ICMP_EQ)
10934     if (ICmpInst::isTrueWhenEqual(Pred))
10935       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
10936         return true;
10937   if (Pred == ICmpInst::ICMP_NE)
10938     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10939       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
10940         return true;
10941 
10942   // Otherwise assume the worst.
10943   return false;
10944 }
10945 
10946 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10947                                      const SCEV *&L, const SCEV *&R,
10948                                      SCEV::NoWrapFlags &Flags) {
10949   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10950   if (!AE || AE->getNumOperands() != 2)
10951     return false;
10952 
10953   L = AE->getOperand(0);
10954   R = AE->getOperand(1);
10955   Flags = AE->getNoWrapFlags();
10956   return true;
10957 }
10958 
10959 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10960                                                            const SCEV *Less) {
10961   // We avoid subtracting expressions here because this function is usually
10962   // fairly deep in the call stack (i.e. is called many times).
10963 
10964   // X - X = 0.
10965   if (More == Less)
10966     return APInt(getTypeSizeInBits(More->getType()), 0);
10967 
10968   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10969     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10970     const auto *MAR = cast<SCEVAddRecExpr>(More);
10971 
10972     if (LAR->getLoop() != MAR->getLoop())
10973       return None;
10974 
10975     // We look at affine expressions only; not for correctness but to keep
10976     // getStepRecurrence cheap.
10977     if (!LAR->isAffine() || !MAR->isAffine())
10978       return None;
10979 
10980     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10981       return None;
10982 
10983     Less = LAR->getStart();
10984     More = MAR->getStart();
10985 
10986     // fall through
10987   }
10988 
10989   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10990     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10991     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10992     return M - L;
10993   }
10994 
10995   SCEV::NoWrapFlags Flags;
10996   const SCEV *LLess = nullptr, *RLess = nullptr;
10997   const SCEV *LMore = nullptr, *RMore = nullptr;
10998   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10999   // Compare (X + C1) vs X.
11000   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11001     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11002       if (RLess == More)
11003         return -(C1->getAPInt());
11004 
11005   // Compare X vs (X + C2).
11006   if (splitBinaryAdd(More, LMore, RMore, Flags))
11007     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11008       if (RMore == Less)
11009         return C2->getAPInt();
11010 
11011   // Compare (X + C1) vs (X + C2).
11012   if (C1 && C2 && RLess == RMore)
11013     return C2->getAPInt() - C1->getAPInt();
11014 
11015   return None;
11016 }
11017 
11018 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11019     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11020     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11021   // Try to recognize the following pattern:
11022   //
11023   //   FoundRHS = ...
11024   // ...
11025   // loop:
11026   //   FoundLHS = {Start,+,W}
11027   // context_bb: // Basic block from the same loop
11028   //   known(Pred, FoundLHS, FoundRHS)
11029   //
11030   // If some predicate is known in the context of a loop, it is also known on
11031   // each iteration of this loop, including the first iteration. Therefore, in
11032   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11033   // prove the original pred using this fact.
11034   if (!CtxI)
11035     return false;
11036   const BasicBlock *ContextBB = CtxI->getParent();
11037   // Make sure AR varies in the context block.
11038   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11039     const Loop *L = AR->getLoop();
11040     // Make sure that context belongs to the loop and executes on 1st iteration
11041     // (if it ever executes at all).
11042     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11043       return false;
11044     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11045       return false;
11046     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11047   }
11048 
11049   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11050     const Loop *L = AR->getLoop();
11051     // Make sure that context belongs to the loop and executes on 1st iteration
11052     // (if it ever executes at all).
11053     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11054       return false;
11055     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11056       return false;
11057     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11058   }
11059 
11060   return false;
11061 }
11062 
11063 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11064     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11065     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11066   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11067     return false;
11068 
11069   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11070   if (!AddRecLHS)
11071     return false;
11072 
11073   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11074   if (!AddRecFoundLHS)
11075     return false;
11076 
11077   // We'd like to let SCEV reason about control dependencies, so we constrain
11078   // both the inequalities to be about add recurrences on the same loop.  This
11079   // way we can use isLoopEntryGuardedByCond later.
11080 
11081   const Loop *L = AddRecFoundLHS->getLoop();
11082   if (L != AddRecLHS->getLoop())
11083     return false;
11084 
11085   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11086   //
11087   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11088   //                                                                  ... (2)
11089   //
11090   // Informal proof for (2), assuming (1) [*]:
11091   //
11092   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11093   //
11094   // Then
11095   //
11096   //       FoundLHS s< FoundRHS s< INT_MIN - C
11097   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11098   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11099   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11100   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11101   // <=>  FoundLHS + C s< FoundRHS + C
11102   //
11103   // [*]: (1) can be proved by ruling out overflow.
11104   //
11105   // [**]: This can be proved by analyzing all the four possibilities:
11106   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11107   //    (A s>= 0, B s>= 0).
11108   //
11109   // Note:
11110   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11111   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11112   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11113   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11114   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11115   // C)".
11116 
11117   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11118   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11119   if (!LDiff || !RDiff || *LDiff != *RDiff)
11120     return false;
11121 
11122   if (LDiff->isMinValue())
11123     return true;
11124 
11125   APInt FoundRHSLimit;
11126 
11127   if (Pred == CmpInst::ICMP_ULT) {
11128     FoundRHSLimit = -(*RDiff);
11129   } else {
11130     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11131     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11132   }
11133 
11134   // Try to prove (1) or (2), as needed.
11135   return isAvailableAtLoopEntry(FoundRHS, L) &&
11136          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11137                                   getConstant(FoundRHSLimit));
11138 }
11139 
11140 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11141                                         const SCEV *LHS, const SCEV *RHS,
11142                                         const SCEV *FoundLHS,
11143                                         const SCEV *FoundRHS, unsigned Depth) {
11144   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11145 
11146   auto ClearOnExit = make_scope_exit([&]() {
11147     if (LPhi) {
11148       bool Erased = PendingMerges.erase(LPhi);
11149       assert(Erased && "Failed to erase LPhi!");
11150       (void)Erased;
11151     }
11152     if (RPhi) {
11153       bool Erased = PendingMerges.erase(RPhi);
11154       assert(Erased && "Failed to erase RPhi!");
11155       (void)Erased;
11156     }
11157   });
11158 
11159   // Find respective Phis and check that they are not being pending.
11160   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11161     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11162       if (!PendingMerges.insert(Phi).second)
11163         return false;
11164       LPhi = Phi;
11165     }
11166   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11167     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11168       // If we detect a loop of Phi nodes being processed by this method, for
11169       // example:
11170       //
11171       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11172       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11173       //
11174       // we don't want to deal with a case that complex, so return conservative
11175       // answer false.
11176       if (!PendingMerges.insert(Phi).second)
11177         return false;
11178       RPhi = Phi;
11179     }
11180 
11181   // If none of LHS, RHS is a Phi, nothing to do here.
11182   if (!LPhi && !RPhi)
11183     return false;
11184 
11185   // If there is a SCEVUnknown Phi we are interested in, make it left.
11186   if (!LPhi) {
11187     std::swap(LHS, RHS);
11188     std::swap(FoundLHS, FoundRHS);
11189     std::swap(LPhi, RPhi);
11190     Pred = ICmpInst::getSwappedPredicate(Pred);
11191   }
11192 
11193   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11194   const BasicBlock *LBB = LPhi->getParent();
11195   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11196 
11197   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11198     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11199            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11200            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11201   };
11202 
11203   if (RPhi && RPhi->getParent() == LBB) {
11204     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11205     // If we compare two Phis from the same block, and for each entry block
11206     // the predicate is true for incoming values from this block, then the
11207     // predicate is also true for the Phis.
11208     for (const BasicBlock *IncBB : predecessors(LBB)) {
11209       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11210       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11211       if (!ProvedEasily(L, R))
11212         return false;
11213     }
11214   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11215     // Case two: RHS is also a Phi from the same basic block, and it is an
11216     // AddRec. It means that there is a loop which has both AddRec and Unknown
11217     // PHIs, for it we can compare incoming values of AddRec from above the loop
11218     // and latch with their respective incoming values of LPhi.
11219     // TODO: Generalize to handle loops with many inputs in a header.
11220     if (LPhi->getNumIncomingValues() != 2) return false;
11221 
11222     auto *RLoop = RAR->getLoop();
11223     auto *Predecessor = RLoop->getLoopPredecessor();
11224     assert(Predecessor && "Loop with AddRec with no predecessor?");
11225     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11226     if (!ProvedEasily(L1, RAR->getStart()))
11227       return false;
11228     auto *Latch = RLoop->getLoopLatch();
11229     assert(Latch && "Loop with AddRec with no latch?");
11230     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11231     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11232       return false;
11233   } else {
11234     // In all other cases go over inputs of LHS and compare each of them to RHS,
11235     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11236     // At this point RHS is either a non-Phi, or it is a Phi from some block
11237     // different from LBB.
11238     for (const BasicBlock *IncBB : predecessors(LBB)) {
11239       // Check that RHS is available in this block.
11240       if (!dominates(RHS, IncBB))
11241         return false;
11242       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11243       // Make sure L does not refer to a value from a potentially previous
11244       // iteration of a loop.
11245       if (!properlyDominates(L, IncBB))
11246         return false;
11247       if (!ProvedEasily(L, RHS))
11248         return false;
11249     }
11250   }
11251   return true;
11252 }
11253 
11254 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11255                                             const SCEV *LHS, const SCEV *RHS,
11256                                             const SCEV *FoundLHS,
11257                                             const SCEV *FoundRHS,
11258                                             const Instruction *CtxI) {
11259   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11260     return true;
11261 
11262   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11263     return true;
11264 
11265   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11266                                           CtxI))
11267     return true;
11268 
11269   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11270                                      FoundLHS, FoundRHS);
11271 }
11272 
11273 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11274 template <typename MinMaxExprType>
11275 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11276                                  const SCEV *Candidate) {
11277   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11278   if (!MinMaxExpr)
11279     return false;
11280 
11281   return is_contained(MinMaxExpr->operands(), Candidate);
11282 }
11283 
11284 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11285                                            ICmpInst::Predicate Pred,
11286                                            const SCEV *LHS, const SCEV *RHS) {
11287   // If both sides are affine addrecs for the same loop, with equal
11288   // steps, and we know the recurrences don't wrap, then we only
11289   // need to check the predicate on the starting values.
11290 
11291   if (!ICmpInst::isRelational(Pred))
11292     return false;
11293 
11294   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11295   if (!LAR)
11296     return false;
11297   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11298   if (!RAR)
11299     return false;
11300   if (LAR->getLoop() != RAR->getLoop())
11301     return false;
11302   if (!LAR->isAffine() || !RAR->isAffine())
11303     return false;
11304 
11305   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11306     return false;
11307 
11308   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11309                          SCEV::FlagNSW : SCEV::FlagNUW;
11310   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11311     return false;
11312 
11313   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11314 }
11315 
11316 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11317 /// expression?
11318 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11319                                         ICmpInst::Predicate Pred,
11320                                         const SCEV *LHS, const SCEV *RHS) {
11321   switch (Pred) {
11322   default:
11323     return false;
11324 
11325   case ICmpInst::ICMP_SGE:
11326     std::swap(LHS, RHS);
11327     LLVM_FALLTHROUGH;
11328   case ICmpInst::ICMP_SLE:
11329     return
11330         // min(A, ...) <= A
11331         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11332         // A <= max(A, ...)
11333         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11334 
11335   case ICmpInst::ICMP_UGE:
11336     std::swap(LHS, RHS);
11337     LLVM_FALLTHROUGH;
11338   case ICmpInst::ICMP_ULE:
11339     return
11340         // min(A, ...) <= A
11341         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11342         // A <= max(A, ...)
11343         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11344   }
11345 
11346   llvm_unreachable("covered switch fell through?!");
11347 }
11348 
11349 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11350                                              const SCEV *LHS, const SCEV *RHS,
11351                                              const SCEV *FoundLHS,
11352                                              const SCEV *FoundRHS,
11353                                              unsigned Depth) {
11354   assert(getTypeSizeInBits(LHS->getType()) ==
11355              getTypeSizeInBits(RHS->getType()) &&
11356          "LHS and RHS have different sizes?");
11357   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11358              getTypeSizeInBits(FoundRHS->getType()) &&
11359          "FoundLHS and FoundRHS have different sizes?");
11360   // We want to avoid hurting the compile time with analysis of too big trees.
11361   if (Depth > MaxSCEVOperationsImplicationDepth)
11362     return false;
11363 
11364   // We only want to work with GT comparison so far.
11365   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11366     Pred = CmpInst::getSwappedPredicate(Pred);
11367     std::swap(LHS, RHS);
11368     std::swap(FoundLHS, FoundRHS);
11369   }
11370 
11371   // For unsigned, try to reduce it to corresponding signed comparison.
11372   if (Pred == ICmpInst::ICMP_UGT)
11373     // We can replace unsigned predicate with its signed counterpart if all
11374     // involved values are non-negative.
11375     // TODO: We could have better support for unsigned.
11376     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11377       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11378       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11379       // use this fact to prove that LHS and RHS are non-negative.
11380       const SCEV *MinusOne = getMinusOne(LHS->getType());
11381       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11382                                 FoundRHS) &&
11383           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11384                                 FoundRHS))
11385         Pred = ICmpInst::ICMP_SGT;
11386     }
11387 
11388   if (Pred != ICmpInst::ICMP_SGT)
11389     return false;
11390 
11391   auto GetOpFromSExt = [&](const SCEV *S) {
11392     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11393       return Ext->getOperand();
11394     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11395     // the constant in some cases.
11396     return S;
11397   };
11398 
11399   // Acquire values from extensions.
11400   auto *OrigLHS = LHS;
11401   auto *OrigFoundLHS = FoundLHS;
11402   LHS = GetOpFromSExt(LHS);
11403   FoundLHS = GetOpFromSExt(FoundLHS);
11404 
11405   // Is the SGT predicate can be proved trivially or using the found context.
11406   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11407     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11408            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11409                                   FoundRHS, Depth + 1);
11410   };
11411 
11412   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11413     // We want to avoid creation of any new non-constant SCEV. Since we are
11414     // going to compare the operands to RHS, we should be certain that we don't
11415     // need any size extensions for this. So let's decline all cases when the
11416     // sizes of types of LHS and RHS do not match.
11417     // TODO: Maybe try to get RHS from sext to catch more cases?
11418     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11419       return false;
11420 
11421     // Should not overflow.
11422     if (!LHSAddExpr->hasNoSignedWrap())
11423       return false;
11424 
11425     auto *LL = LHSAddExpr->getOperand(0);
11426     auto *LR = LHSAddExpr->getOperand(1);
11427     auto *MinusOne = getMinusOne(RHS->getType());
11428 
11429     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11430     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11431       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11432     };
11433     // Try to prove the following rule:
11434     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11435     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11436     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11437       return true;
11438   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11439     Value *LL, *LR;
11440     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11441 
11442     using namespace llvm::PatternMatch;
11443 
11444     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11445       // Rules for division.
11446       // We are going to perform some comparisons with Denominator and its
11447       // derivative expressions. In general case, creating a SCEV for it may
11448       // lead to a complex analysis of the entire graph, and in particular it
11449       // can request trip count recalculation for the same loop. This would
11450       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11451       // this, we only want to create SCEVs that are constants in this section.
11452       // So we bail if Denominator is not a constant.
11453       if (!isa<ConstantInt>(LR))
11454         return false;
11455 
11456       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11457 
11458       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11459       // then a SCEV for the numerator already exists and matches with FoundLHS.
11460       auto *Numerator = getExistingSCEV(LL);
11461       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11462         return false;
11463 
11464       // Make sure that the numerator matches with FoundLHS and the denominator
11465       // is positive.
11466       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11467         return false;
11468 
11469       auto *DTy = Denominator->getType();
11470       auto *FRHSTy = FoundRHS->getType();
11471       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11472         // One of types is a pointer and another one is not. We cannot extend
11473         // them properly to a wider type, so let us just reject this case.
11474         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11475         // to avoid this check.
11476         return false;
11477 
11478       // Given that:
11479       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11480       auto *WTy = getWiderType(DTy, FRHSTy);
11481       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11482       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11483 
11484       // Try to prove the following rule:
11485       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11486       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11487       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11488       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11489       if (isKnownNonPositive(RHS) &&
11490           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11491         return true;
11492 
11493       // Try to prove the following rule:
11494       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11495       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11496       // If we divide it by Denominator > 2, then:
11497       // 1. If FoundLHS is negative, then the result is 0.
11498       // 2. If FoundLHS is non-negative, then the result is non-negative.
11499       // Anyways, the result is non-negative.
11500       auto *MinusOne = getMinusOne(WTy);
11501       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11502       if (isKnownNegative(RHS) &&
11503           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11504         return true;
11505     }
11506   }
11507 
11508   // If our expression contained SCEVUnknown Phis, and we split it down and now
11509   // need to prove something for them, try to prove the predicate for every
11510   // possible incoming values of those Phis.
11511   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11512     return true;
11513 
11514   return false;
11515 }
11516 
11517 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11518                                         const SCEV *LHS, const SCEV *RHS) {
11519   // zext x u<= sext x, sext x s<= zext x
11520   switch (Pred) {
11521   case ICmpInst::ICMP_SGE:
11522     std::swap(LHS, RHS);
11523     LLVM_FALLTHROUGH;
11524   case ICmpInst::ICMP_SLE: {
11525     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11526     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11527     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11528     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11529       return true;
11530     break;
11531   }
11532   case ICmpInst::ICMP_UGE:
11533     std::swap(LHS, RHS);
11534     LLVM_FALLTHROUGH;
11535   case ICmpInst::ICMP_ULE: {
11536     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11537     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11538     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11539     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11540       return true;
11541     break;
11542   }
11543   default:
11544     break;
11545   };
11546   return false;
11547 }
11548 
11549 bool
11550 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11551                                            const SCEV *LHS, const SCEV *RHS) {
11552   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11553          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11554          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11555          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11556          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11557 }
11558 
11559 bool
11560 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11561                                              const SCEV *LHS, const SCEV *RHS,
11562                                              const SCEV *FoundLHS,
11563                                              const SCEV *FoundRHS) {
11564   switch (Pred) {
11565   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11566   case ICmpInst::ICMP_EQ:
11567   case ICmpInst::ICMP_NE:
11568     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11569       return true;
11570     break;
11571   case ICmpInst::ICMP_SLT:
11572   case ICmpInst::ICMP_SLE:
11573     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11574         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11575       return true;
11576     break;
11577   case ICmpInst::ICMP_SGT:
11578   case ICmpInst::ICMP_SGE:
11579     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11580         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11581       return true;
11582     break;
11583   case ICmpInst::ICMP_ULT:
11584   case ICmpInst::ICMP_ULE:
11585     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11586         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11587       return true;
11588     break;
11589   case ICmpInst::ICMP_UGT:
11590   case ICmpInst::ICMP_UGE:
11591     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11592         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11593       return true;
11594     break;
11595   }
11596 
11597   // Maybe it can be proved via operations?
11598   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11599     return true;
11600 
11601   return false;
11602 }
11603 
11604 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11605                                                      const SCEV *LHS,
11606                                                      const SCEV *RHS,
11607                                                      const SCEV *FoundLHS,
11608                                                      const SCEV *FoundRHS) {
11609   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11610     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11611     // reduce the compile time impact of this optimization.
11612     return false;
11613 
11614   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11615   if (!Addend)
11616     return false;
11617 
11618   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11619 
11620   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11621   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11622   ConstantRange FoundLHSRange =
11623       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
11624 
11625   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11626   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11627 
11628   // We can also compute the range of values for `LHS` that satisfy the
11629   // consequent, "`LHS` `Pred` `RHS`":
11630   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11631   // The antecedent implies the consequent if every value of `LHS` that
11632   // satisfies the antecedent also satisfies the consequent.
11633   return LHSRange.icmp(Pred, ConstRHS);
11634 }
11635 
11636 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11637                                         bool IsSigned) {
11638   assert(isKnownPositive(Stride) && "Positive stride expected!");
11639 
11640   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11641   const SCEV *One = getOne(Stride->getType());
11642 
11643   if (IsSigned) {
11644     APInt MaxRHS = getSignedRangeMax(RHS);
11645     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11646     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11647 
11648     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11649     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11650   }
11651 
11652   APInt MaxRHS = getUnsignedRangeMax(RHS);
11653   APInt MaxValue = APInt::getMaxValue(BitWidth);
11654   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11655 
11656   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11657   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11658 }
11659 
11660 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11661                                         bool IsSigned) {
11662 
11663   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11664   const SCEV *One = getOne(Stride->getType());
11665 
11666   if (IsSigned) {
11667     APInt MinRHS = getSignedRangeMin(RHS);
11668     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11669     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11670 
11671     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11672     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11673   }
11674 
11675   APInt MinRHS = getUnsignedRangeMin(RHS);
11676   APInt MinValue = APInt::getMinValue(BitWidth);
11677   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11678 
11679   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11680   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11681 }
11682 
11683 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
11684   // umin(N, 1) + floor((N - umin(N, 1)) / D)
11685   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
11686   // expression fixes the case of N=0.
11687   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
11688   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
11689   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
11690 }
11691 
11692 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11693                                                     const SCEV *Stride,
11694                                                     const SCEV *End,
11695                                                     unsigned BitWidth,
11696                                                     bool IsSigned) {
11697   // The logic in this function assumes we can represent a positive stride.
11698   // If we can't, the backedge-taken count must be zero.
11699   if (IsSigned && BitWidth == 1)
11700     return getZero(Stride->getType());
11701 
11702   // This code has only been closely audited for negative strides in the
11703   // unsigned comparison case, it may be correct for signed comparison, but
11704   // that needs to be established.
11705   assert((!IsSigned || !isKnownNonPositive(Stride)) &&
11706          "Stride is expected strictly positive for signed case!");
11707 
11708   // Calculate the maximum backedge count based on the range of values
11709   // permitted by Start, End, and Stride.
11710   APInt MinStart =
11711       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11712 
11713   APInt MinStride =
11714       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11715 
11716   // We assume either the stride is positive, or the backedge-taken count
11717   // is zero. So force StrideForMaxBECount to be at least one.
11718   APInt One(BitWidth, 1);
11719   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
11720                                        : APIntOps::umax(One, MinStride);
11721 
11722   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11723                             : APInt::getMaxValue(BitWidth);
11724   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11725 
11726   // Although End can be a MAX expression we estimate MaxEnd considering only
11727   // the case End = RHS of the loop termination condition. This is safe because
11728   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11729   // taken count.
11730   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11731                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11732 
11733   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
11734   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
11735                     : APIntOps::umax(MaxEnd, MinStart);
11736 
11737   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
11738                          getConstant(StrideForMaxBECount) /* Step */);
11739 }
11740 
11741 ScalarEvolution::ExitLimit
11742 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11743                                   const Loop *L, bool IsSigned,
11744                                   bool ControlsExit, bool AllowPredicates) {
11745   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11746 
11747   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11748   bool PredicatedIV = false;
11749 
11750   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
11751     // Can we prove this loop *must* be UB if overflow of IV occurs?
11752     // Reasoning goes as follows:
11753     // * Suppose the IV did self wrap.
11754     // * If Stride evenly divides the iteration space, then once wrap
11755     //   occurs, the loop must revisit the same values.
11756     // * We know that RHS is invariant, and that none of those values
11757     //   caused this exit to be taken previously.  Thus, this exit is
11758     //   dynamically dead.
11759     // * If this is the sole exit, then a dead exit implies the loop
11760     //   must be infinite if there are no abnormal exits.
11761     // * If the loop were infinite, then it must either not be mustprogress
11762     //   or have side effects. Otherwise, it must be UB.
11763     // * It can't (by assumption), be UB so we have contradicted our
11764     //   premise and can conclude the IV did not in fact self-wrap.
11765     if (!isLoopInvariant(RHS, L))
11766       return false;
11767 
11768     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
11769     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
11770       return false;
11771 
11772     if (!ControlsExit || !loopHasNoAbnormalExits(L))
11773       return false;
11774 
11775     return loopIsFiniteByAssumption(L);
11776   };
11777 
11778   if (!IV) {
11779     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
11780       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
11781       if (AR && AR->getLoop() == L && AR->isAffine()) {
11782         auto canProveNUW = [&]() {
11783           if (!isLoopInvariant(RHS, L))
11784             return false;
11785 
11786           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
11787             // We need the sequence defined by AR to strictly increase in the
11788             // unsigned integer domain for the logic below to hold.
11789             return false;
11790 
11791           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
11792           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
11793           // If RHS <=u Limit, then there must exist a value V in the sequence
11794           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
11795           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
11796           // overflow occurs.  This limit also implies that a signed comparison
11797           // (in the wide bitwidth) is equivalent to an unsigned comparison as
11798           // the high bits on both sides must be zero.
11799           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
11800           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
11801           Limit = Limit.zext(OuterBitWidth);
11802           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
11803         };
11804         auto Flags = AR->getNoWrapFlags();
11805         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
11806           Flags = setFlags(Flags, SCEV::FlagNUW);
11807 
11808         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
11809         if (AR->hasNoUnsignedWrap()) {
11810           // Emulate what getZeroExtendExpr would have done during construction
11811           // if we'd been able to infer the fact just above at that time.
11812           const SCEV *Step = AR->getStepRecurrence(*this);
11813           Type *Ty = ZExt->getType();
11814           auto *S = getAddRecExpr(
11815             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
11816             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
11817           IV = dyn_cast<SCEVAddRecExpr>(S);
11818         }
11819       }
11820     }
11821   }
11822 
11823 
11824   if (!IV && AllowPredicates) {
11825     // Try to make this an AddRec using runtime tests, in the first X
11826     // iterations of this loop, where X is the SCEV expression found by the
11827     // algorithm below.
11828     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11829     PredicatedIV = true;
11830   }
11831 
11832   // Avoid weird loops
11833   if (!IV || IV->getLoop() != L || !IV->isAffine())
11834     return getCouldNotCompute();
11835 
11836   // A precondition of this method is that the condition being analyzed
11837   // reaches an exiting branch which dominates the latch.  Given that, we can
11838   // assume that an increment which violates the nowrap specification and
11839   // produces poison must cause undefined behavior when the resulting poison
11840   // value is branched upon and thus we can conclude that the backedge is
11841   // taken no more often than would be required to produce that poison value.
11842   // Note that a well defined loop can exit on the iteration which violates
11843   // the nowrap specification if there is another exit (either explicit or
11844   // implicit/exceptional) which causes the loop to execute before the
11845   // exiting instruction we're analyzing would trigger UB.
11846   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11847   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11848   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
11849 
11850   const SCEV *Stride = IV->getStepRecurrence(*this);
11851 
11852   bool PositiveStride = isKnownPositive(Stride);
11853 
11854   // Avoid negative or zero stride values.
11855   if (!PositiveStride) {
11856     // We can compute the correct backedge taken count for loops with unknown
11857     // strides if we can prove that the loop is not an infinite loop with side
11858     // effects. Here's the loop structure we are trying to handle -
11859     //
11860     // i = start
11861     // do {
11862     //   A[i] = i;
11863     //   i += s;
11864     // } while (i < end);
11865     //
11866     // The backedge taken count for such loops is evaluated as -
11867     // (max(end, start + stride) - start - 1) /u stride
11868     //
11869     // The additional preconditions that we need to check to prove correctness
11870     // of the above formula is as follows -
11871     //
11872     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11873     //    NoWrap flag).
11874     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
11875     //    no side effects within the loop)
11876     // c) loop has a single static exit (with no abnormal exits)
11877     //
11878     // Precondition a) implies that if the stride is negative, this is a single
11879     // trip loop. The backedge taken count formula reduces to zero in this case.
11880     //
11881     // Precondition b) and c) combine to imply that if rhs is invariant in L,
11882     // then a zero stride means the backedge can't be taken without executing
11883     // undefined behavior.
11884     //
11885     // The positive stride case is the same as isKnownPositive(Stride) returning
11886     // true (original behavior of the function).
11887     //
11888     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
11889         !loopHasNoAbnormalExits(L))
11890       return getCouldNotCompute();
11891 
11892     // This bailout is protecting the logic in computeMaxBECountForLT which
11893     // has not yet been sufficiently auditted or tested with negative strides.
11894     // We used to filter out all known-non-positive cases here, we're in the
11895     // process of being less restrictive bit by bit.
11896     if (IsSigned && isKnownNonPositive(Stride))
11897       return getCouldNotCompute();
11898 
11899     if (!isKnownNonZero(Stride)) {
11900       // If we have a step of zero, and RHS isn't invariant in L, we don't know
11901       // if it might eventually be greater than start and if so, on which
11902       // iteration.  We can't even produce a useful upper bound.
11903       if (!isLoopInvariant(RHS, L))
11904         return getCouldNotCompute();
11905 
11906       // We allow a potentially zero stride, but we need to divide by stride
11907       // below.  Since the loop can't be infinite and this check must control
11908       // the sole exit, we can infer the exit must be taken on the first
11909       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
11910       // we know the numerator in the divides below must be zero, so we can
11911       // pick an arbitrary non-zero value for the denominator (e.g. stride)
11912       // and produce the right result.
11913       // FIXME: Handle the case where Stride is poison?
11914       auto wouldZeroStrideBeUB = [&]() {
11915         // Proof by contradiction.  Suppose the stride were zero.  If we can
11916         // prove that the backedge *is* taken on the first iteration, then since
11917         // we know this condition controls the sole exit, we must have an
11918         // infinite loop.  We can't have a (well defined) infinite loop per
11919         // check just above.
11920         // Note: The (Start - Stride) term is used to get the start' term from
11921         // (start' + stride,+,stride). Remember that we only care about the
11922         // result of this expression when stride == 0 at runtime.
11923         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
11924         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
11925       };
11926       if (!wouldZeroStrideBeUB()) {
11927         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
11928       }
11929     }
11930   } else if (!Stride->isOne() && !NoWrap) {
11931     auto isUBOnWrap = [&]() {
11932       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
11933       // follows trivially from the fact that every (un)signed-wrapped, but
11934       // not self-wrapped value must be LT than the last value before
11935       // (un)signed wrap.  Since we know that last value didn't exit, nor
11936       // will any smaller one.
11937       return canAssumeNoSelfWrap(IV);
11938     };
11939 
11940     // Avoid proven overflow cases: this will ensure that the backedge taken
11941     // count will not generate any unsigned overflow. Relaxed no-overflow
11942     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11943     // undefined behaviors like the case of C language.
11944     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
11945       return getCouldNotCompute();
11946   }
11947 
11948   // On all paths just preceeding, we established the following invariant:
11949   //   IV can be assumed not to overflow up to and including the exiting
11950   //   iteration.  We proved this in one of two ways:
11951   //   1) We can show overflow doesn't occur before the exiting iteration
11952   //      1a) canIVOverflowOnLT, and b) step of one
11953   //   2) We can show that if overflow occurs, the loop must execute UB
11954   //      before any possible exit.
11955   // Note that we have not yet proved RHS invariant (in general).
11956 
11957   const SCEV *Start = IV->getStart();
11958 
11959   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
11960   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
11961   // Use integer-typed versions for actual computation; we can't subtract
11962   // pointers in general.
11963   const SCEV *OrigStart = Start;
11964   const SCEV *OrigRHS = RHS;
11965   if (Start->getType()->isPointerTy()) {
11966     Start = getLosslessPtrToIntExpr(Start);
11967     if (isa<SCEVCouldNotCompute>(Start))
11968       return Start;
11969   }
11970   if (RHS->getType()->isPointerTy()) {
11971     RHS = getLosslessPtrToIntExpr(RHS);
11972     if (isa<SCEVCouldNotCompute>(RHS))
11973       return RHS;
11974   }
11975 
11976   // When the RHS is not invariant, we do not know the end bound of the loop and
11977   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11978   // calculate the MaxBECount, given the start, stride and max value for the end
11979   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11980   // checked above).
11981   if (!isLoopInvariant(RHS, L)) {
11982     const SCEV *MaxBECount = computeMaxBECountForLT(
11983         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11984     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11985                      false /*MaxOrZero*/, Predicates);
11986   }
11987 
11988   // We use the expression (max(End,Start)-Start)/Stride to describe the
11989   // backedge count, as if the backedge is taken at least once max(End,Start)
11990   // is End and so the result is as above, and if not max(End,Start) is Start
11991   // so we get a backedge count of zero.
11992   const SCEV *BECount = nullptr;
11993   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
11994   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
11995   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
11996   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
11997   // Can we prove (max(RHS,Start) > Start - Stride?
11998   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
11999       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12000     // In this case, we can use a refined formula for computing backedge taken
12001     // count.  The general formula remains:
12002     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12003     // We want to use the alternate formula:
12004     //   "((End - 1) - (Start - Stride)) /u Stride"
12005     // Let's do a quick case analysis to show these are equivalent under
12006     // our precondition that max(RHS,Start) > Start - Stride.
12007     // * For RHS <= Start, the backedge-taken count must be zero.
12008     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12009     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12010     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12011     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12012     //     this to the stride of 1 case.
12013     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12014     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12015     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12016     //   "((RHS - (Start - Stride) - 1) /u Stride".
12017     //   Our preconditions trivially imply no overflow in that form.
12018     const SCEV *MinusOne = getMinusOne(Stride->getType());
12019     const SCEV *Numerator =
12020         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12021     BECount = getUDivExpr(Numerator, Stride);
12022   }
12023 
12024   const SCEV *BECountIfBackedgeTaken = nullptr;
12025   if (!BECount) {
12026     auto canProveRHSGreaterThanEqualStart = [&]() {
12027       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12028       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12029         return true;
12030 
12031       // (RHS > Start - 1) implies RHS >= Start.
12032       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12033       //   "Start - 1" doesn't overflow.
12034       // * For signed comparison, if Start - 1 does overflow, it's equal
12035       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12036       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12037       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12038       //
12039       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12040       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12041       auto *StartMinusOne = getAddExpr(OrigStart,
12042                                        getMinusOne(OrigStart->getType()));
12043       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12044     };
12045 
12046     // If we know that RHS >= Start in the context of loop, then we know that
12047     // max(RHS, Start) = RHS at this point.
12048     const SCEV *End;
12049     if (canProveRHSGreaterThanEqualStart()) {
12050       End = RHS;
12051     } else {
12052       // If RHS < Start, the backedge will be taken zero times.  So in
12053       // general, we can write the backedge-taken count as:
12054       //
12055       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12056       //
12057       // We convert it to the following to make it more convenient for SCEV:
12058       //
12059       //     ceil(max(RHS, Start) - Start) / Stride
12060       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12061 
12062       // See what would happen if we assume the backedge is taken. This is
12063       // used to compute MaxBECount.
12064       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12065     }
12066 
12067     // At this point, we know:
12068     //
12069     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12070     // 2. The index variable doesn't overflow.
12071     //
12072     // Therefore, we know N exists such that
12073     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12074     // doesn't overflow.
12075     //
12076     // Using this information, try to prove whether the addition in
12077     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12078     const SCEV *One = getOne(Stride->getType());
12079     bool MayAddOverflow = [&] {
12080       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12081         if (StrideC->getAPInt().isPowerOf2()) {
12082           // Suppose Stride is a power of two, and Start/End are unsigned
12083           // integers.  Let UMAX be the largest representable unsigned
12084           // integer.
12085           //
12086           // By the preconditions of this function, we know
12087           // "(Start + Stride * N) >= End", and this doesn't overflow.
12088           // As a formula:
12089           //
12090           //   End <= (Start + Stride * N) <= UMAX
12091           //
12092           // Subtracting Start from all the terms:
12093           //
12094           //   End - Start <= Stride * N <= UMAX - Start
12095           //
12096           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12097           //
12098           //   End - Start <= Stride * N <= UMAX
12099           //
12100           // Stride * N is a multiple of Stride. Therefore,
12101           //
12102           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12103           //
12104           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12105           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12106           //
12107           //   End - Start <= Stride * N <= UMAX - Stride - 1
12108           //
12109           // Dropping the middle term:
12110           //
12111           //   End - Start <= UMAX - Stride - 1
12112           //
12113           // Adding Stride - 1 to both sides:
12114           //
12115           //   (End - Start) + (Stride - 1) <= UMAX
12116           //
12117           // In other words, the addition doesn't have unsigned overflow.
12118           //
12119           // A similar proof works if we treat Start/End as signed values.
12120           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12121           // use signed max instead of unsigned max. Note that we're trying
12122           // to prove a lack of unsigned overflow in either case.
12123           return false;
12124         }
12125       }
12126       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12127         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12128         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12129         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12130         //
12131         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12132         return false;
12133       }
12134       return true;
12135     }();
12136 
12137     const SCEV *Delta = getMinusSCEV(End, Start);
12138     if (!MayAddOverflow) {
12139       // floor((D + (S - 1)) / S)
12140       // We prefer this formulation if it's legal because it's fewer operations.
12141       BECount =
12142           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
12143     } else {
12144       BECount = getUDivCeilSCEV(Delta, Stride);
12145     }
12146   }
12147 
12148   const SCEV *MaxBECount;
12149   bool MaxOrZero = false;
12150   if (isa<SCEVConstant>(BECount)) {
12151     MaxBECount = BECount;
12152   } else if (BECountIfBackedgeTaken &&
12153              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
12154     // If we know exactly how many times the backedge will be taken if it's
12155     // taken at least once, then the backedge count will either be that or
12156     // zero.
12157     MaxBECount = BECountIfBackedgeTaken;
12158     MaxOrZero = true;
12159   } else {
12160     MaxBECount = computeMaxBECountForLT(
12161         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12162   }
12163 
12164   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
12165       !isa<SCEVCouldNotCompute>(BECount))
12166     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
12167 
12168   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
12169 }
12170 
12171 ScalarEvolution::ExitLimit
12172 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
12173                                      const Loop *L, bool IsSigned,
12174                                      bool ControlsExit, bool AllowPredicates) {
12175   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12176   // We handle only IV > Invariant
12177   if (!isLoopInvariant(RHS, L))
12178     return getCouldNotCompute();
12179 
12180   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12181   if (!IV && AllowPredicates)
12182     // Try to make this an AddRec using runtime tests, in the first X
12183     // iterations of this loop, where X is the SCEV expression found by the
12184     // algorithm below.
12185     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12186 
12187   // Avoid weird loops
12188   if (!IV || IV->getLoop() != L || !IV->isAffine())
12189     return getCouldNotCompute();
12190 
12191   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12192   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12193   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12194 
12195   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
12196 
12197   // Avoid negative or zero stride values
12198   if (!isKnownPositive(Stride))
12199     return getCouldNotCompute();
12200 
12201   // Avoid proven overflow cases: this will ensure that the backedge taken count
12202   // will not generate any unsigned overflow. Relaxed no-overflow conditions
12203   // exploit NoWrapFlags, allowing to optimize in presence of undefined
12204   // behaviors like the case of C language.
12205   if (!Stride->isOne() && !NoWrap)
12206     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
12207       return getCouldNotCompute();
12208 
12209   const SCEV *Start = IV->getStart();
12210   const SCEV *End = RHS;
12211   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
12212     // If we know that Start >= RHS in the context of loop, then we know that
12213     // min(RHS, Start) = RHS at this point.
12214     if (isLoopEntryGuardedByCond(
12215             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
12216       End = RHS;
12217     else
12218       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
12219   }
12220 
12221   if (Start->getType()->isPointerTy()) {
12222     Start = getLosslessPtrToIntExpr(Start);
12223     if (isa<SCEVCouldNotCompute>(Start))
12224       return Start;
12225   }
12226   if (End->getType()->isPointerTy()) {
12227     End = getLosslessPtrToIntExpr(End);
12228     if (isa<SCEVCouldNotCompute>(End))
12229       return End;
12230   }
12231 
12232   // Compute ((Start - End) + (Stride - 1)) / Stride.
12233   // FIXME: This can overflow. Holding off on fixing this for now;
12234   // howManyGreaterThans will hopefully be gone soon.
12235   const SCEV *One = getOne(Stride->getType());
12236   const SCEV *BECount = getUDivExpr(
12237       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
12238 
12239   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
12240                             : getUnsignedRangeMax(Start);
12241 
12242   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
12243                              : getUnsignedRangeMin(Stride);
12244 
12245   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
12246   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
12247                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
12248 
12249   // Although End can be a MIN expression we estimate MinEnd considering only
12250   // the case End = RHS. This is safe because in the other case (Start - End)
12251   // is zero, leading to a zero maximum backedge taken count.
12252   APInt MinEnd =
12253     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
12254              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
12255 
12256   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
12257                                ? BECount
12258                                : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
12259                                                  getConstant(MinStride));
12260 
12261   if (isa<SCEVCouldNotCompute>(MaxBECount))
12262     MaxBECount = BECount;
12263 
12264   return ExitLimit(BECount, MaxBECount, false, Predicates);
12265 }
12266 
12267 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
12268                                                     ScalarEvolution &SE) const {
12269   if (Range.isFullSet())  // Infinite loop.
12270     return SE.getCouldNotCompute();
12271 
12272   // If the start is a non-zero constant, shift the range to simplify things.
12273   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
12274     if (!SC->getValue()->isZero()) {
12275       SmallVector<const SCEV *, 4> Operands(operands());
12276       Operands[0] = SE.getZero(SC->getType());
12277       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
12278                                              getNoWrapFlags(FlagNW));
12279       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
12280         return ShiftedAddRec->getNumIterationsInRange(
12281             Range.subtract(SC->getAPInt()), SE);
12282       // This is strange and shouldn't happen.
12283       return SE.getCouldNotCompute();
12284     }
12285 
12286   // The only time we can solve this is when we have all constant indices.
12287   // Otherwise, we cannot determine the overflow conditions.
12288   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
12289     return SE.getCouldNotCompute();
12290 
12291   // Okay at this point we know that all elements of the chrec are constants and
12292   // that the start element is zero.
12293 
12294   // First check to see if the range contains zero.  If not, the first
12295   // iteration exits.
12296   unsigned BitWidth = SE.getTypeSizeInBits(getType());
12297   if (!Range.contains(APInt(BitWidth, 0)))
12298     return SE.getZero(getType());
12299 
12300   if (isAffine()) {
12301     // If this is an affine expression then we have this situation:
12302     //   Solve {0,+,A} in Range  ===  Ax in Range
12303 
12304     // We know that zero is in the range.  If A is positive then we know that
12305     // the upper value of the range must be the first possible exit value.
12306     // If A is negative then the lower of the range is the last possible loop
12307     // value.  Also note that we already checked for a full range.
12308     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
12309     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
12310 
12311     // The exit value should be (End+A)/A.
12312     APInt ExitVal = (End + A).udiv(A);
12313     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
12314 
12315     // Evaluate at the exit value.  If we really did fall out of the valid
12316     // range, then we computed our trip count, otherwise wrap around or other
12317     // things must have happened.
12318     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
12319     if (Range.contains(Val->getValue()))
12320       return SE.getCouldNotCompute();  // Something strange happened
12321 
12322     // Ensure that the previous value is in the range.
12323     assert(Range.contains(
12324            EvaluateConstantChrecAtConstant(this,
12325            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
12326            "Linear scev computation is off in a bad way!");
12327     return SE.getConstant(ExitValue);
12328   }
12329 
12330   if (isQuadratic()) {
12331     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
12332       return SE.getConstant(S.getValue());
12333   }
12334 
12335   return SE.getCouldNotCompute();
12336 }
12337 
12338 const SCEVAddRecExpr *
12339 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
12340   assert(getNumOperands() > 1 && "AddRec with zero step?");
12341   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
12342   // but in this case we cannot guarantee that the value returned will be an
12343   // AddRec because SCEV does not have a fixed point where it stops
12344   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
12345   // may happen if we reach arithmetic depth limit while simplifying. So we
12346   // construct the returned value explicitly.
12347   SmallVector<const SCEV *, 3> Ops;
12348   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
12349   // (this + Step) is {A+B,+,B+C,+...,+,N}.
12350   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
12351     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
12352   // We know that the last operand is not a constant zero (otherwise it would
12353   // have been popped out earlier). This guarantees us that if the result has
12354   // the same last operand, then it will also not be popped out, meaning that
12355   // the returned value will be an AddRec.
12356   const SCEV *Last = getOperand(getNumOperands() - 1);
12357   assert(!Last->isZero() && "Recurrency with zero step?");
12358   Ops.push_back(Last);
12359   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
12360                                                SCEV::FlagAnyWrap));
12361 }
12362 
12363 // Return true when S contains at least an undef value.
12364 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
12365   return SCEVExprContains(S, [](const SCEV *S) {
12366     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12367       return isa<UndefValue>(SU->getValue());
12368     return false;
12369   });
12370 }
12371 
12372 /// Return the size of an element read or written by Inst.
12373 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12374   Type *Ty;
12375   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12376     Ty = Store->getValueOperand()->getType();
12377   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12378     Ty = Load->getType();
12379   else
12380     return nullptr;
12381 
12382   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12383   return getSizeOfExpr(ETy, Ty);
12384 }
12385 
12386 //===----------------------------------------------------------------------===//
12387 //                   SCEVCallbackVH Class Implementation
12388 //===----------------------------------------------------------------------===//
12389 
12390 void ScalarEvolution::SCEVCallbackVH::deleted() {
12391   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12392   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12393     SE->ConstantEvolutionLoopExitValue.erase(PN);
12394   SE->eraseValueFromMap(getValPtr());
12395   // this now dangles!
12396 }
12397 
12398 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12399   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12400 
12401   // Forget all the expressions associated with users of the old value,
12402   // so that future queries will recompute the expressions using the new
12403   // value.
12404   Value *Old = getValPtr();
12405   SmallVector<User *, 16> Worklist(Old->users());
12406   SmallPtrSet<User *, 8> Visited;
12407   while (!Worklist.empty()) {
12408     User *U = Worklist.pop_back_val();
12409     // Deleting the Old value will cause this to dangle. Postpone
12410     // that until everything else is done.
12411     if (U == Old)
12412       continue;
12413     if (!Visited.insert(U).second)
12414       continue;
12415     if (PHINode *PN = dyn_cast<PHINode>(U))
12416       SE->ConstantEvolutionLoopExitValue.erase(PN);
12417     SE->eraseValueFromMap(U);
12418     llvm::append_range(Worklist, U->users());
12419   }
12420   // Delete the Old value.
12421   if (PHINode *PN = dyn_cast<PHINode>(Old))
12422     SE->ConstantEvolutionLoopExitValue.erase(PN);
12423   SE->eraseValueFromMap(Old);
12424   // this now dangles!
12425 }
12426 
12427 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12428   : CallbackVH(V), SE(se) {}
12429 
12430 //===----------------------------------------------------------------------===//
12431 //                   ScalarEvolution Class Implementation
12432 //===----------------------------------------------------------------------===//
12433 
12434 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12435                                  AssumptionCache &AC, DominatorTree &DT,
12436                                  LoopInfo &LI)
12437     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12438       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12439       LoopDispositions(64), BlockDispositions(64) {
12440   // To use guards for proving predicates, we need to scan every instruction in
12441   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12442   // time if the IR does not actually contain any calls to
12443   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12444   //
12445   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12446   // to _add_ guards to the module when there weren't any before, and wants
12447   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12448   // efficient in lieu of being smart in that rather obscure case.
12449 
12450   auto *GuardDecl = F.getParent()->getFunction(
12451       Intrinsic::getName(Intrinsic::experimental_guard));
12452   HasGuards = GuardDecl && !GuardDecl->use_empty();
12453 }
12454 
12455 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12456     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12457       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12458       ValueExprMap(std::move(Arg.ValueExprMap)),
12459       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12460       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12461       PendingMerges(std::move(Arg.PendingMerges)),
12462       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12463       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12464       PredicatedBackedgeTakenCounts(
12465           std::move(Arg.PredicatedBackedgeTakenCounts)),
12466       ConstantEvolutionLoopExitValue(
12467           std::move(Arg.ConstantEvolutionLoopExitValue)),
12468       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12469       LoopDispositions(std::move(Arg.LoopDispositions)),
12470       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12471       BlockDispositions(std::move(Arg.BlockDispositions)),
12472       SCEVUsers(std::move(Arg.SCEVUsers)),
12473       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12474       SignedRanges(std::move(Arg.SignedRanges)),
12475       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12476       UniquePreds(std::move(Arg.UniquePreds)),
12477       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12478       LoopUsers(std::move(Arg.LoopUsers)),
12479       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12480       FirstUnknown(Arg.FirstUnknown) {
12481   Arg.FirstUnknown = nullptr;
12482 }
12483 
12484 ScalarEvolution::~ScalarEvolution() {
12485   // Iterate through all the SCEVUnknown instances and call their
12486   // destructors, so that they release their references to their values.
12487   for (SCEVUnknown *U = FirstUnknown; U;) {
12488     SCEVUnknown *Tmp = U;
12489     U = U->Next;
12490     Tmp->~SCEVUnknown();
12491   }
12492   FirstUnknown = nullptr;
12493 
12494   ExprValueMap.clear();
12495   ValueExprMap.clear();
12496   HasRecMap.clear();
12497   BackedgeTakenCounts.clear();
12498   PredicatedBackedgeTakenCounts.clear();
12499 
12500   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12501   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12502   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12503   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12504   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12505 }
12506 
12507 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12508   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12509 }
12510 
12511 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12512                           const Loop *L) {
12513   // Print all inner loops first
12514   for (Loop *I : *L)
12515     PrintLoopInfo(OS, SE, I);
12516 
12517   OS << "Loop ";
12518   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12519   OS << ": ";
12520 
12521   SmallVector<BasicBlock *, 8> ExitingBlocks;
12522   L->getExitingBlocks(ExitingBlocks);
12523   if (ExitingBlocks.size() != 1)
12524     OS << "<multiple exits> ";
12525 
12526   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12527     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12528   else
12529     OS << "Unpredictable backedge-taken count.\n";
12530 
12531   if (ExitingBlocks.size() > 1)
12532     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12533       OS << "  exit count for " << ExitingBlock->getName() << ": "
12534          << *SE->getExitCount(L, ExitingBlock) << "\n";
12535     }
12536 
12537   OS << "Loop ";
12538   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12539   OS << ": ";
12540 
12541   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12542     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12543     if (SE->isBackedgeTakenCountMaxOrZero(L))
12544       OS << ", actual taken count either this or zero.";
12545   } else {
12546     OS << "Unpredictable max backedge-taken count. ";
12547   }
12548 
12549   OS << "\n"
12550         "Loop ";
12551   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12552   OS << ": ";
12553 
12554   SCEVUnionPredicate Pred;
12555   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12556   if (!isa<SCEVCouldNotCompute>(PBT)) {
12557     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12558     OS << " Predicates:\n";
12559     Pred.print(OS, 4);
12560   } else {
12561     OS << "Unpredictable predicated backedge-taken count. ";
12562   }
12563   OS << "\n";
12564 
12565   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12566     OS << "Loop ";
12567     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12568     OS << ": ";
12569     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12570   }
12571 }
12572 
12573 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12574   switch (LD) {
12575   case ScalarEvolution::LoopVariant:
12576     return "Variant";
12577   case ScalarEvolution::LoopInvariant:
12578     return "Invariant";
12579   case ScalarEvolution::LoopComputable:
12580     return "Computable";
12581   }
12582   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12583 }
12584 
12585 void ScalarEvolution::print(raw_ostream &OS) const {
12586   // ScalarEvolution's implementation of the print method is to print
12587   // out SCEV values of all instructions that are interesting. Doing
12588   // this potentially causes it to create new SCEV objects though,
12589   // which technically conflicts with the const qualifier. This isn't
12590   // observable from outside the class though, so casting away the
12591   // const isn't dangerous.
12592   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12593 
12594   if (ClassifyExpressions) {
12595     OS << "Classifying expressions for: ";
12596     F.printAsOperand(OS, /*PrintType=*/false);
12597     OS << "\n";
12598     for (Instruction &I : instructions(F))
12599       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12600         OS << I << '\n';
12601         OS << "  -->  ";
12602         const SCEV *SV = SE.getSCEV(&I);
12603         SV->print(OS);
12604         if (!isa<SCEVCouldNotCompute>(SV)) {
12605           OS << " U: ";
12606           SE.getUnsignedRange(SV).print(OS);
12607           OS << " S: ";
12608           SE.getSignedRange(SV).print(OS);
12609         }
12610 
12611         const Loop *L = LI.getLoopFor(I.getParent());
12612 
12613         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12614         if (AtUse != SV) {
12615           OS << "  -->  ";
12616           AtUse->print(OS);
12617           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12618             OS << " U: ";
12619             SE.getUnsignedRange(AtUse).print(OS);
12620             OS << " S: ";
12621             SE.getSignedRange(AtUse).print(OS);
12622           }
12623         }
12624 
12625         if (L) {
12626           OS << "\t\t" "Exits: ";
12627           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12628           if (!SE.isLoopInvariant(ExitValue, L)) {
12629             OS << "<<Unknown>>";
12630           } else {
12631             OS << *ExitValue;
12632           }
12633 
12634           bool First = true;
12635           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12636             if (First) {
12637               OS << "\t\t" "LoopDispositions: { ";
12638               First = false;
12639             } else {
12640               OS << ", ";
12641             }
12642 
12643             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12644             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12645           }
12646 
12647           for (auto *InnerL : depth_first(L)) {
12648             if (InnerL == L)
12649               continue;
12650             if (First) {
12651               OS << "\t\t" "LoopDispositions: { ";
12652               First = false;
12653             } else {
12654               OS << ", ";
12655             }
12656 
12657             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12658             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12659           }
12660 
12661           OS << " }";
12662         }
12663 
12664         OS << "\n";
12665       }
12666   }
12667 
12668   OS << "Determining loop execution counts for: ";
12669   F.printAsOperand(OS, /*PrintType=*/false);
12670   OS << "\n";
12671   for (Loop *I : LI)
12672     PrintLoopInfo(OS, &SE, I);
12673 }
12674 
12675 ScalarEvolution::LoopDisposition
12676 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12677   auto &Values = LoopDispositions[S];
12678   for (auto &V : Values) {
12679     if (V.getPointer() == L)
12680       return V.getInt();
12681   }
12682   Values.emplace_back(L, LoopVariant);
12683   LoopDisposition D = computeLoopDisposition(S, L);
12684   auto &Values2 = LoopDispositions[S];
12685   for (auto &V : llvm::reverse(Values2)) {
12686     if (V.getPointer() == L) {
12687       V.setInt(D);
12688       break;
12689     }
12690   }
12691   return D;
12692 }
12693 
12694 ScalarEvolution::LoopDisposition
12695 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12696   switch (S->getSCEVType()) {
12697   case scConstant:
12698     return LoopInvariant;
12699   case scPtrToInt:
12700   case scTruncate:
12701   case scZeroExtend:
12702   case scSignExtend:
12703     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12704   case scAddRecExpr: {
12705     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12706 
12707     // If L is the addrec's loop, it's computable.
12708     if (AR->getLoop() == L)
12709       return LoopComputable;
12710 
12711     // Add recurrences are never invariant in the function-body (null loop).
12712     if (!L)
12713       return LoopVariant;
12714 
12715     // Everything that is not defined at loop entry is variant.
12716     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12717       return LoopVariant;
12718     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12719            " dominate the contained loop's header?");
12720 
12721     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12722     if (AR->getLoop()->contains(L))
12723       return LoopInvariant;
12724 
12725     // This recurrence is variant w.r.t. L if any of its operands
12726     // are variant.
12727     for (auto *Op : AR->operands())
12728       if (!isLoopInvariant(Op, L))
12729         return LoopVariant;
12730 
12731     // Otherwise it's loop-invariant.
12732     return LoopInvariant;
12733   }
12734   case scAddExpr:
12735   case scMulExpr:
12736   case scUMaxExpr:
12737   case scSMaxExpr:
12738   case scUMinExpr:
12739   case scSMinExpr: {
12740     bool HasVarying = false;
12741     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12742       LoopDisposition D = getLoopDisposition(Op, L);
12743       if (D == LoopVariant)
12744         return LoopVariant;
12745       if (D == LoopComputable)
12746         HasVarying = true;
12747     }
12748     return HasVarying ? LoopComputable : LoopInvariant;
12749   }
12750   case scUDivExpr: {
12751     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12752     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12753     if (LD == LoopVariant)
12754       return LoopVariant;
12755     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12756     if (RD == LoopVariant)
12757       return LoopVariant;
12758     return (LD == LoopInvariant && RD == LoopInvariant) ?
12759            LoopInvariant : LoopComputable;
12760   }
12761   case scUnknown:
12762     // All non-instruction values are loop invariant.  All instructions are loop
12763     // invariant if they are not contained in the specified loop.
12764     // Instructions are never considered invariant in the function body
12765     // (null loop) because they are defined within the "loop".
12766     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12767       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12768     return LoopInvariant;
12769   case scCouldNotCompute:
12770     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12771   }
12772   llvm_unreachable("Unknown SCEV kind!");
12773 }
12774 
12775 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12776   return getLoopDisposition(S, L) == LoopInvariant;
12777 }
12778 
12779 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12780   return getLoopDisposition(S, L) == LoopComputable;
12781 }
12782 
12783 ScalarEvolution::BlockDisposition
12784 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12785   auto &Values = BlockDispositions[S];
12786   for (auto &V : Values) {
12787     if (V.getPointer() == BB)
12788       return V.getInt();
12789   }
12790   Values.emplace_back(BB, DoesNotDominateBlock);
12791   BlockDisposition D = computeBlockDisposition(S, BB);
12792   auto &Values2 = BlockDispositions[S];
12793   for (auto &V : llvm::reverse(Values2)) {
12794     if (V.getPointer() == BB) {
12795       V.setInt(D);
12796       break;
12797     }
12798   }
12799   return D;
12800 }
12801 
12802 ScalarEvolution::BlockDisposition
12803 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12804   switch (S->getSCEVType()) {
12805   case scConstant:
12806     return ProperlyDominatesBlock;
12807   case scPtrToInt:
12808   case scTruncate:
12809   case scZeroExtend:
12810   case scSignExtend:
12811     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12812   case scAddRecExpr: {
12813     // This uses a "dominates" query instead of "properly dominates" query
12814     // to test for proper dominance too, because the instruction which
12815     // produces the addrec's value is a PHI, and a PHI effectively properly
12816     // dominates its entire containing block.
12817     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12818     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12819       return DoesNotDominateBlock;
12820 
12821     // Fall through into SCEVNAryExpr handling.
12822     LLVM_FALLTHROUGH;
12823   }
12824   case scAddExpr:
12825   case scMulExpr:
12826   case scUMaxExpr:
12827   case scSMaxExpr:
12828   case scUMinExpr:
12829   case scSMinExpr: {
12830     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12831     bool Proper = true;
12832     for (const SCEV *NAryOp : NAry->operands()) {
12833       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12834       if (D == DoesNotDominateBlock)
12835         return DoesNotDominateBlock;
12836       if (D == DominatesBlock)
12837         Proper = false;
12838     }
12839     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12840   }
12841   case scUDivExpr: {
12842     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12843     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12844     BlockDisposition LD = getBlockDisposition(LHS, BB);
12845     if (LD == DoesNotDominateBlock)
12846       return DoesNotDominateBlock;
12847     BlockDisposition RD = getBlockDisposition(RHS, BB);
12848     if (RD == DoesNotDominateBlock)
12849       return DoesNotDominateBlock;
12850     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12851       ProperlyDominatesBlock : DominatesBlock;
12852   }
12853   case scUnknown:
12854     if (Instruction *I =
12855           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12856       if (I->getParent() == BB)
12857         return DominatesBlock;
12858       if (DT.properlyDominates(I->getParent(), BB))
12859         return ProperlyDominatesBlock;
12860       return DoesNotDominateBlock;
12861     }
12862     return ProperlyDominatesBlock;
12863   case scCouldNotCompute:
12864     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12865   }
12866   llvm_unreachable("Unknown SCEV kind!");
12867 }
12868 
12869 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12870   return getBlockDisposition(S, BB) >= DominatesBlock;
12871 }
12872 
12873 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12874   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12875 }
12876 
12877 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12878   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12879 }
12880 
12881 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
12882   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
12883   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
12884 
12885   while (!Worklist.empty()) {
12886     const SCEV *Curr = Worklist.pop_back_val();
12887     auto Users = SCEVUsers.find(Curr);
12888     if (Users != SCEVUsers.end())
12889       for (auto *User : Users->second)
12890         if (ToForget.insert(User).second)
12891           Worklist.push_back(User);
12892   }
12893 
12894   for (auto *S : ToForget)
12895     forgetMemoizedResultsImpl(S);
12896 
12897   for (auto I = PredicatedSCEVRewrites.begin();
12898        I != PredicatedSCEVRewrites.end();) {
12899     std::pair<const SCEV *, const Loop *> Entry = I->first;
12900     if (ToForget.count(Entry.first))
12901       PredicatedSCEVRewrites.erase(I++);
12902     else
12903       ++I;
12904   }
12905 
12906   auto RemoveSCEVFromBackedgeMap = [&ToForget](
12907       DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12908         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12909           BackedgeTakenInfo &BEInfo = I->second;
12910           if (any_of(ToForget,
12911                      [&BEInfo](const SCEV *S) { return BEInfo.hasOperand(S); }))
12912             Map.erase(I++);
12913           else
12914             ++I;
12915         }
12916   };
12917 
12918   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12919   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12920 }
12921 
12922 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
12923   ValuesAtScopes.erase(S);
12924   LoopDispositions.erase(S);
12925   BlockDispositions.erase(S);
12926   UnsignedRanges.erase(S);
12927   SignedRanges.erase(S);
12928   HasRecMap.erase(S);
12929   MinTrailingZerosCache.erase(S);
12930 
12931   auto ExprIt = ExprValueMap.find(S);
12932   if (ExprIt != ExprValueMap.end()) {
12933     for (auto &ValueAndOffset : ExprIt->second) {
12934       if (ValueAndOffset.second == nullptr) {
12935         auto ValueIt = ValueExprMap.find_as(ValueAndOffset.first);
12936         if (ValueIt != ValueExprMap.end())
12937           ValueExprMap.erase(ValueIt);
12938       }
12939     }
12940     ExprValueMap.erase(ExprIt);
12941   }
12942 }
12943 
12944 void
12945 ScalarEvolution::getUsedLoops(const SCEV *S,
12946                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12947   struct FindUsedLoops {
12948     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12949         : LoopsUsed(LoopsUsed) {}
12950     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12951     bool follow(const SCEV *S) {
12952       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12953         LoopsUsed.insert(AR->getLoop());
12954       return true;
12955     }
12956 
12957     bool isDone() const { return false; }
12958   };
12959 
12960   FindUsedLoops F(LoopsUsed);
12961   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12962 }
12963 
12964 void ScalarEvolution::verify() const {
12965   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12966   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12967 
12968   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12969 
12970   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12971   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12972     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12973 
12974     const SCEV *visitConstant(const SCEVConstant *Constant) {
12975       return SE.getConstant(Constant->getAPInt());
12976     }
12977 
12978     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12979       return SE.getUnknown(Expr->getValue());
12980     }
12981 
12982     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12983       return SE.getCouldNotCompute();
12984     }
12985   };
12986 
12987   SCEVMapper SCM(SE2);
12988 
12989   while (!LoopStack.empty()) {
12990     auto *L = LoopStack.pop_back_val();
12991     llvm::append_range(LoopStack, *L);
12992 
12993     auto *CurBECount = SCM.visit(
12994         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12995     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12996 
12997     if (CurBECount == SE2.getCouldNotCompute() ||
12998         NewBECount == SE2.getCouldNotCompute()) {
12999       // NB! This situation is legal, but is very suspicious -- whatever pass
13000       // change the loop to make a trip count go from could not compute to
13001       // computable or vice-versa *should have* invalidated SCEV.  However, we
13002       // choose not to assert here (for now) since we don't want false
13003       // positives.
13004       continue;
13005     }
13006 
13007     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
13008       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13009       // not propagate undef aggressively).  This means we can (and do) fail
13010       // verification in cases where a transform makes the trip count of a loop
13011       // go from "undef" to "undef+1" (say).  The transform is fine, since in
13012       // both cases the loop iterates "undef" times, but SCEV thinks we
13013       // increased the trip count of the loop by 1 incorrectly.
13014       continue;
13015     }
13016 
13017     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13018         SE.getTypeSizeInBits(NewBECount->getType()))
13019       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13020     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13021              SE.getTypeSizeInBits(NewBECount->getType()))
13022       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13023 
13024     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
13025 
13026     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13027     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
13028       dbgs() << "Trip Count for " << *L << " Changed!\n";
13029       dbgs() << "Old: " << *CurBECount << "\n";
13030       dbgs() << "New: " << *NewBECount << "\n";
13031       dbgs() << "Delta: " << *Delta << "\n";
13032       std::abort();
13033     }
13034   }
13035 
13036   // Collect all valid loops currently in LoopInfo.
13037   SmallPtrSet<Loop *, 32> ValidLoops;
13038   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13039   while (!Worklist.empty()) {
13040     Loop *L = Worklist.pop_back_val();
13041     if (ValidLoops.contains(L))
13042       continue;
13043     ValidLoops.insert(L);
13044     Worklist.append(L->begin(), L->end());
13045   }
13046   for (auto &KV : ValueExprMap) {
13047     // Check for SCEV expressions referencing invalid/deleted loops.
13048     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
13049       assert(ValidLoops.contains(AR->getLoop()) &&
13050              "AddRec references invalid loop");
13051     }
13052 
13053     // Check that the value is also part of the reverse map.
13054     auto It = ExprValueMap.find(KV.second);
13055     if (It == ExprValueMap.end() || !It->second.contains({KV.first, nullptr})) {
13056       dbgs() << "Value " << *KV.first
13057              << " is in ValueExprMap but not in ExprValueMap\n";
13058       std::abort();
13059     }
13060   }
13061 
13062   for (const auto &KV : ExprValueMap) {
13063     for (const auto &ValueAndOffset : KV.second) {
13064       if (ValueAndOffset.second != nullptr)
13065         continue;
13066 
13067       auto It = ValueExprMap.find_as(ValueAndOffset.first);
13068       if (It == ValueExprMap.end()) {
13069         dbgs() << "Value " << *ValueAndOffset.first
13070                << " is in ExprValueMap but not in ValueExprMap\n";
13071         std::abort();
13072       }
13073       if (It->second != KV.first) {
13074         dbgs() << "Value " << *ValueAndOffset.first
13075                << " mapped to " << *It->second
13076                << " rather than " << *KV.first << "\n";
13077         std::abort();
13078       }
13079     }
13080   }
13081 
13082   // Verify intergity of SCEV users.
13083   for (const auto &S : UniqueSCEVs) {
13084     SmallVector<const SCEV *, 4> Ops;
13085     collectUniqueOps(&S, Ops);
13086     for (const auto *Op : Ops) {
13087       // We do not store dependencies of constants.
13088       if (isa<SCEVConstant>(Op))
13089         continue;
13090       auto It = SCEVUsers.find(Op);
13091       if (It != SCEVUsers.end() && It->second.count(&S))
13092         continue;
13093       dbgs() << "Use of operand  " << *Op << " by user " << S
13094              << " is not being tracked!\n";
13095       std::abort();
13096     }
13097   }
13098 }
13099 
13100 bool ScalarEvolution::invalidate(
13101     Function &F, const PreservedAnalyses &PA,
13102     FunctionAnalysisManager::Invalidator &Inv) {
13103   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13104   // of its dependencies is invalidated.
13105   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13106   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13107          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13108          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13109          Inv.invalidate<LoopAnalysis>(F, PA);
13110 }
13111 
13112 AnalysisKey ScalarEvolutionAnalysis::Key;
13113 
13114 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13115                                              FunctionAnalysisManager &AM) {
13116   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13117                          AM.getResult<AssumptionAnalysis>(F),
13118                          AM.getResult<DominatorTreeAnalysis>(F),
13119                          AM.getResult<LoopAnalysis>(F));
13120 }
13121 
13122 PreservedAnalyses
13123 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13124   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13125   return PreservedAnalyses::all();
13126 }
13127 
13128 PreservedAnalyses
13129 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13130   // For compatibility with opt's -analyze feature under legacy pass manager
13131   // which was not ported to NPM. This keeps tests using
13132   // update_analyze_test_checks.py working.
13133   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13134      << F.getName() << "':\n";
13135   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13136   return PreservedAnalyses::all();
13137 }
13138 
13139 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13140                       "Scalar Evolution Analysis", false, true)
13141 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13142 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13143 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13144 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13145 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13146                     "Scalar Evolution Analysis", false, true)
13147 
13148 char ScalarEvolutionWrapperPass::ID = 0;
13149 
13150 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13151   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13152 }
13153 
13154 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13155   SE.reset(new ScalarEvolution(
13156       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13157       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13158       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13159       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13160   return false;
13161 }
13162 
13163 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13164 
13165 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13166   SE->print(OS);
13167 }
13168 
13169 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13170   if (!VerifySCEV)
13171     return;
13172 
13173   SE->verify();
13174 }
13175 
13176 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13177   AU.setPreservesAll();
13178   AU.addRequiredTransitive<AssumptionCacheTracker>();
13179   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13180   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13181   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13182 }
13183 
13184 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13185                                                         const SCEV *RHS) {
13186   FoldingSetNodeID ID;
13187   assert(LHS->getType() == RHS->getType() &&
13188          "Type mismatch between LHS and RHS");
13189   // Unique this node based on the arguments
13190   ID.AddInteger(SCEVPredicate::P_Equal);
13191   ID.AddPointer(LHS);
13192   ID.AddPointer(RHS);
13193   void *IP = nullptr;
13194   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13195     return S;
13196   SCEVEqualPredicate *Eq = new (SCEVAllocator)
13197       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
13198   UniquePreds.InsertNode(Eq, IP);
13199   return Eq;
13200 }
13201 
13202 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13203     const SCEVAddRecExpr *AR,
13204     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13205   FoldingSetNodeID ID;
13206   // Unique this node based on the arguments
13207   ID.AddInteger(SCEVPredicate::P_Wrap);
13208   ID.AddPointer(AR);
13209   ID.AddInteger(AddedFlags);
13210   void *IP = nullptr;
13211   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13212     return S;
13213   auto *OF = new (SCEVAllocator)
13214       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13215   UniquePreds.InsertNode(OF, IP);
13216   return OF;
13217 }
13218 
13219 namespace {
13220 
13221 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13222 public:
13223 
13224   /// Rewrites \p S in the context of a loop L and the SCEV predication
13225   /// infrastructure.
13226   ///
13227   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13228   /// equivalences present in \p Pred.
13229   ///
13230   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13231   /// \p NewPreds such that the result will be an AddRecExpr.
13232   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13233                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13234                              SCEVUnionPredicate *Pred) {
13235     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13236     return Rewriter.visit(S);
13237   }
13238 
13239   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13240     if (Pred) {
13241       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
13242       for (auto *Pred : ExprPreds)
13243         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
13244           if (IPred->getLHS() == Expr)
13245             return IPred->getRHS();
13246     }
13247     return convertToAddRecWithPreds(Expr);
13248   }
13249 
13250   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13251     const SCEV *Operand = visit(Expr->getOperand());
13252     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13253     if (AR && AR->getLoop() == L && AR->isAffine()) {
13254       // This couldn't be folded because the operand didn't have the nuw
13255       // flag. Add the nusw flag as an assumption that we could make.
13256       const SCEV *Step = AR->getStepRecurrence(SE);
13257       Type *Ty = Expr->getType();
13258       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13259         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13260                                 SE.getSignExtendExpr(Step, Ty), L,
13261                                 AR->getNoWrapFlags());
13262     }
13263     return SE.getZeroExtendExpr(Operand, Expr->getType());
13264   }
13265 
13266   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13267     const SCEV *Operand = visit(Expr->getOperand());
13268     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13269     if (AR && AR->getLoop() == L && AR->isAffine()) {
13270       // This couldn't be folded because the operand didn't have the nsw
13271       // flag. Add the nssw flag as an assumption that we could make.
13272       const SCEV *Step = AR->getStepRecurrence(SE);
13273       Type *Ty = Expr->getType();
13274       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13275         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13276                                 SE.getSignExtendExpr(Step, Ty), L,
13277                                 AR->getNoWrapFlags());
13278     }
13279     return SE.getSignExtendExpr(Operand, Expr->getType());
13280   }
13281 
13282 private:
13283   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13284                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13285                         SCEVUnionPredicate *Pred)
13286       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13287 
13288   bool addOverflowAssumption(const SCEVPredicate *P) {
13289     if (!NewPreds) {
13290       // Check if we've already made this assumption.
13291       return Pred && Pred->implies(P);
13292     }
13293     NewPreds->insert(P);
13294     return true;
13295   }
13296 
13297   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13298                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13299     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13300     return addOverflowAssumption(A);
13301   }
13302 
13303   // If \p Expr represents a PHINode, we try to see if it can be represented
13304   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13305   // to add this predicate as a runtime overflow check, we return the AddRec.
13306   // If \p Expr does not meet these conditions (is not a PHI node, or we
13307   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13308   // return \p Expr.
13309   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13310     if (!isa<PHINode>(Expr->getValue()))
13311       return Expr;
13312     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13313     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13314     if (!PredicatedRewrite)
13315       return Expr;
13316     for (auto *P : PredicatedRewrite->second){
13317       // Wrap predicates from outer loops are not supported.
13318       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13319         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
13320         if (L != AR->getLoop())
13321           return Expr;
13322       }
13323       if (!addOverflowAssumption(P))
13324         return Expr;
13325     }
13326     return PredicatedRewrite->first;
13327   }
13328 
13329   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13330   SCEVUnionPredicate *Pred;
13331   const Loop *L;
13332 };
13333 
13334 } // end anonymous namespace
13335 
13336 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13337                                                    SCEVUnionPredicate &Preds) {
13338   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13339 }
13340 
13341 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13342     const SCEV *S, const Loop *L,
13343     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13344   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13345   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13346   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13347 
13348   if (!AddRec)
13349     return nullptr;
13350 
13351   // Since the transformation was successful, we can now transfer the SCEV
13352   // predicates.
13353   for (auto *P : TransformPreds)
13354     Preds.insert(P);
13355 
13356   return AddRec;
13357 }
13358 
13359 /// SCEV predicates
13360 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13361                              SCEVPredicateKind Kind)
13362     : FastID(ID), Kind(Kind) {}
13363 
13364 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13365                                        const SCEV *LHS, const SCEV *RHS)
13366     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13367   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13368   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13369 }
13370 
13371 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13372   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13373 
13374   if (!Op)
13375     return false;
13376 
13377   return Op->LHS == LHS && Op->RHS == RHS;
13378 }
13379 
13380 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13381 
13382 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13383 
13384 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13385   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13386 }
13387 
13388 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13389                                      const SCEVAddRecExpr *AR,
13390                                      IncrementWrapFlags Flags)
13391     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13392 
13393 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13394 
13395 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13396   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13397 
13398   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13399 }
13400 
13401 bool SCEVWrapPredicate::isAlwaysTrue() const {
13402   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13403   IncrementWrapFlags IFlags = Flags;
13404 
13405   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13406     IFlags = clearFlags(IFlags, IncrementNSSW);
13407 
13408   return IFlags == IncrementAnyWrap;
13409 }
13410 
13411 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13412   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13413   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13414     OS << "<nusw>";
13415   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13416     OS << "<nssw>";
13417   OS << "\n";
13418 }
13419 
13420 SCEVWrapPredicate::IncrementWrapFlags
13421 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13422                                    ScalarEvolution &SE) {
13423   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13424   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13425 
13426   // We can safely transfer the NSW flag as NSSW.
13427   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13428     ImpliedFlags = IncrementNSSW;
13429 
13430   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13431     // If the increment is positive, the SCEV NUW flag will also imply the
13432     // WrapPredicate NUSW flag.
13433     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13434       if (Step->getValue()->getValue().isNonNegative())
13435         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13436   }
13437 
13438   return ImpliedFlags;
13439 }
13440 
13441 /// Union predicates don't get cached so create a dummy set ID for it.
13442 SCEVUnionPredicate::SCEVUnionPredicate()
13443     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13444 
13445 bool SCEVUnionPredicate::isAlwaysTrue() const {
13446   return all_of(Preds,
13447                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13448 }
13449 
13450 ArrayRef<const SCEVPredicate *>
13451 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13452   auto I = SCEVToPreds.find(Expr);
13453   if (I == SCEVToPreds.end())
13454     return ArrayRef<const SCEVPredicate *>();
13455   return I->second;
13456 }
13457 
13458 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13459   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13460     return all_of(Set->Preds,
13461                   [this](const SCEVPredicate *I) { return this->implies(I); });
13462 
13463   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13464   if (ScevPredsIt == SCEVToPreds.end())
13465     return false;
13466   auto &SCEVPreds = ScevPredsIt->second;
13467 
13468   return any_of(SCEVPreds,
13469                 [N](const SCEVPredicate *I) { return I->implies(N); });
13470 }
13471 
13472 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13473 
13474 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13475   for (auto Pred : Preds)
13476     Pred->print(OS, Depth);
13477 }
13478 
13479 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13480   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13481     for (auto Pred : Set->Preds)
13482       add(Pred);
13483     return;
13484   }
13485 
13486   if (implies(N))
13487     return;
13488 
13489   const SCEV *Key = N->getExpr();
13490   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13491                 " associated expression!");
13492 
13493   SCEVToPreds[Key].push_back(N);
13494   Preds.push_back(N);
13495 }
13496 
13497 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13498                                                      Loop &L)
13499     : SE(SE), L(L) {}
13500 
13501 void ScalarEvolution::registerUser(const SCEV *User,
13502                                    ArrayRef<const SCEV *> Ops) {
13503   for (auto *Op : Ops)
13504     // We do not expect that forgetting cached data for SCEVConstants will ever
13505     // open any prospects for sharpening or introduce any correctness issues,
13506     // so we don't bother storing their dependencies.
13507     if (!isa<SCEVConstant>(Op))
13508       SCEVUsers[Op].insert(User);
13509 }
13510 
13511 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13512   const SCEV *Expr = SE.getSCEV(V);
13513   RewriteEntry &Entry = RewriteMap[Expr];
13514 
13515   // If we already have an entry and the version matches, return it.
13516   if (Entry.second && Generation == Entry.first)
13517     return Entry.second;
13518 
13519   // We found an entry but it's stale. Rewrite the stale entry
13520   // according to the current predicate.
13521   if (Entry.second)
13522     Expr = Entry.second;
13523 
13524   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13525   Entry = {Generation, NewSCEV};
13526 
13527   return NewSCEV;
13528 }
13529 
13530 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13531   if (!BackedgeCount) {
13532     SCEVUnionPredicate BackedgePred;
13533     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13534     addPredicate(BackedgePred);
13535   }
13536   return BackedgeCount;
13537 }
13538 
13539 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13540   if (Preds.implies(&Pred))
13541     return;
13542   Preds.add(&Pred);
13543   updateGeneration();
13544 }
13545 
13546 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13547   return Preds;
13548 }
13549 
13550 void PredicatedScalarEvolution::updateGeneration() {
13551   // If the generation number wrapped recompute everything.
13552   if (++Generation == 0) {
13553     for (auto &II : RewriteMap) {
13554       const SCEV *Rewritten = II.second.second;
13555       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13556     }
13557   }
13558 }
13559 
13560 void PredicatedScalarEvolution::setNoOverflow(
13561     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13562   const SCEV *Expr = getSCEV(V);
13563   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13564 
13565   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13566 
13567   // Clear the statically implied flags.
13568   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13569   addPredicate(*SE.getWrapPredicate(AR, Flags));
13570 
13571   auto II = FlagsMap.insert({V, Flags});
13572   if (!II.second)
13573     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13574 }
13575 
13576 bool PredicatedScalarEvolution::hasNoOverflow(
13577     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13578   const SCEV *Expr = getSCEV(V);
13579   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13580 
13581   Flags = SCEVWrapPredicate::clearFlags(
13582       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13583 
13584   auto II = FlagsMap.find(V);
13585 
13586   if (II != FlagsMap.end())
13587     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13588 
13589   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13590 }
13591 
13592 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13593   const SCEV *Expr = this->getSCEV(V);
13594   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13595   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13596 
13597   if (!New)
13598     return nullptr;
13599 
13600   for (auto *P : NewPreds)
13601     Preds.add(P);
13602 
13603   updateGeneration();
13604   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13605   return New;
13606 }
13607 
13608 PredicatedScalarEvolution::PredicatedScalarEvolution(
13609     const PredicatedScalarEvolution &Init)
13610     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13611       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13612   for (auto I : Init.FlagsMap)
13613     FlagsMap.insert(I);
13614 }
13615 
13616 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13617   // For each block.
13618   for (auto *BB : L.getBlocks())
13619     for (auto &I : *BB) {
13620       if (!SE.isSCEVable(I.getType()))
13621         continue;
13622 
13623       auto *Expr = SE.getSCEV(&I);
13624       auto II = RewriteMap.find(Expr);
13625 
13626       if (II == RewriteMap.end())
13627         continue;
13628 
13629       // Don't print things that are not interesting.
13630       if (II->second.second == Expr)
13631         continue;
13632 
13633       OS.indent(Depth) << "[PSE]" << I << ":\n";
13634       OS.indent(Depth + 2) << *Expr << "\n";
13635       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13636     }
13637 }
13638 
13639 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13640 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13641 // for URem with constant power-of-2 second operands.
13642 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13643 // 4, A / B becomes X / 8).
13644 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13645                                 const SCEV *&RHS) {
13646   // Try to match 'zext (trunc A to iB) to iY', which is used
13647   // for URem with constant power-of-2 second operands. Make sure the size of
13648   // the operand A matches the size of the whole expressions.
13649   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13650     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13651       LHS = Trunc->getOperand();
13652       // Bail out if the type of the LHS is larger than the type of the
13653       // expression for now.
13654       if (getTypeSizeInBits(LHS->getType()) >
13655           getTypeSizeInBits(Expr->getType()))
13656         return false;
13657       if (LHS->getType() != Expr->getType())
13658         LHS = getZeroExtendExpr(LHS, Expr->getType());
13659       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13660                         << getTypeSizeInBits(Trunc->getType()));
13661       return true;
13662     }
13663   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13664   if (Add == nullptr || Add->getNumOperands() != 2)
13665     return false;
13666 
13667   const SCEV *A = Add->getOperand(1);
13668   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13669 
13670   if (Mul == nullptr)
13671     return false;
13672 
13673   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13674     // (SomeExpr + (-(SomeExpr / B) * B)).
13675     if (Expr == getURemExpr(A, B)) {
13676       LHS = A;
13677       RHS = B;
13678       return true;
13679     }
13680     return false;
13681   };
13682 
13683   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13684   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13685     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13686            MatchURemWithDivisor(Mul->getOperand(2));
13687 
13688   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13689   if (Mul->getNumOperands() == 2)
13690     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13691            MatchURemWithDivisor(Mul->getOperand(0)) ||
13692            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13693            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13694   return false;
13695 }
13696 
13697 const SCEV *
13698 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13699   SmallVector<BasicBlock*, 16> ExitingBlocks;
13700   L->getExitingBlocks(ExitingBlocks);
13701 
13702   // Form an expression for the maximum exit count possible for this loop. We
13703   // merge the max and exact information to approximate a version of
13704   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13705   SmallVector<const SCEV*, 4> ExitCounts;
13706   for (BasicBlock *ExitingBB : ExitingBlocks) {
13707     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13708     if (isa<SCEVCouldNotCompute>(ExitCount))
13709       ExitCount = getExitCount(L, ExitingBB,
13710                                   ScalarEvolution::ConstantMaximum);
13711     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13712       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13713              "We should only have known counts for exiting blocks that "
13714              "dominate latch!");
13715       ExitCounts.push_back(ExitCount);
13716     }
13717   }
13718   if (ExitCounts.empty())
13719     return getCouldNotCompute();
13720   return getUMinFromMismatchedTypes(ExitCounts);
13721 }
13722 
13723 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
13724 /// in the map. It skips AddRecExpr because we cannot guarantee that the
13725 /// replacement is loop invariant in the loop of the AddRec.
13726 ///
13727 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
13728 /// supported.
13729 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13730   const DenseMap<const SCEV *, const SCEV *> &Map;
13731 
13732 public:
13733   SCEVLoopGuardRewriter(ScalarEvolution &SE,
13734                         DenseMap<const SCEV *, const SCEV *> &M)
13735       : SCEVRewriteVisitor(SE), Map(M) {}
13736 
13737   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13738 
13739   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13740     auto I = Map.find(Expr);
13741     if (I == Map.end())
13742       return Expr;
13743     return I->second;
13744   }
13745 
13746   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13747     auto I = Map.find(Expr);
13748     if (I == Map.end())
13749       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
13750           Expr);
13751     return I->second;
13752   }
13753 };
13754 
13755 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13756   SmallVector<const SCEV *> ExprsToRewrite;
13757   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13758                               const SCEV *RHS,
13759                               DenseMap<const SCEV *, const SCEV *>
13760                                   &RewriteMap) {
13761     // WARNING: It is generally unsound to apply any wrap flags to the proposed
13762     // replacement SCEV which isn't directly implied by the structure of that
13763     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
13764     // legal.  See the scoping rules for flags in the header to understand why.
13765 
13766     // If LHS is a constant, apply information to the other expression.
13767     if (isa<SCEVConstant>(LHS)) {
13768       std::swap(LHS, RHS);
13769       Predicate = CmpInst::getSwappedPredicate(Predicate);
13770     }
13771 
13772     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
13773     // create this form when combining two checks of the form (X u< C2 + C1) and
13774     // (X >=u C1).
13775     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
13776                                  &ExprsToRewrite]() {
13777       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
13778       if (!AddExpr || AddExpr->getNumOperands() != 2)
13779         return false;
13780 
13781       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
13782       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
13783       auto *C2 = dyn_cast<SCEVConstant>(RHS);
13784       if (!C1 || !C2 || !LHSUnknown)
13785         return false;
13786 
13787       auto ExactRegion =
13788           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
13789               .sub(C1->getAPInt());
13790 
13791       // Bail out, unless we have a non-wrapping, monotonic range.
13792       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
13793         return false;
13794       auto I = RewriteMap.find(LHSUnknown);
13795       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
13796       RewriteMap[LHSUnknown] = getUMaxExpr(
13797           getConstant(ExactRegion.getUnsignedMin()),
13798           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
13799       ExprsToRewrite.push_back(LHSUnknown);
13800       return true;
13801     };
13802     if (MatchRangeCheckIdiom())
13803       return;
13804 
13805     // If we have LHS == 0, check if LHS is computing a property of some unknown
13806     // SCEV %v which we can rewrite %v to express explicitly.
13807     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13808     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13809         RHSC->getValue()->isNullValue()) {
13810       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13811       // explicitly express that.
13812       const SCEV *URemLHS = nullptr;
13813       const SCEV *URemRHS = nullptr;
13814       if (matchURem(LHS, URemLHS, URemRHS)) {
13815         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13816           auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
13817           RewriteMap[LHSUnknown] = Multiple;
13818           ExprsToRewrite.push_back(LHSUnknown);
13819           return;
13820         }
13821       }
13822     }
13823 
13824     // Do not apply information for constants or if RHS contains an AddRec.
13825     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
13826       return;
13827 
13828     // If RHS is SCEVUnknown, make sure the information is applied to it.
13829     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
13830       std::swap(LHS, RHS);
13831       Predicate = CmpInst::getSwappedPredicate(Predicate);
13832     }
13833 
13834     // Limit to expressions that can be rewritten.
13835     if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
13836       return;
13837 
13838     // Check whether LHS has already been rewritten. In that case we want to
13839     // chain further rewrites onto the already rewritten value.
13840     auto I = RewriteMap.find(LHS);
13841     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13842 
13843     const SCEV *RewrittenRHS = nullptr;
13844     switch (Predicate) {
13845     case CmpInst::ICMP_ULT:
13846       RewrittenRHS =
13847           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13848       break;
13849     case CmpInst::ICMP_SLT:
13850       RewrittenRHS =
13851           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13852       break;
13853     case CmpInst::ICMP_ULE:
13854       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
13855       break;
13856     case CmpInst::ICMP_SLE:
13857       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
13858       break;
13859     case CmpInst::ICMP_UGT:
13860       RewrittenRHS =
13861           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13862       break;
13863     case CmpInst::ICMP_SGT:
13864       RewrittenRHS =
13865           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13866       break;
13867     case CmpInst::ICMP_UGE:
13868       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
13869       break;
13870     case CmpInst::ICMP_SGE:
13871       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
13872       break;
13873     case CmpInst::ICMP_EQ:
13874       if (isa<SCEVConstant>(RHS))
13875         RewrittenRHS = RHS;
13876       break;
13877     case CmpInst::ICMP_NE:
13878       if (isa<SCEVConstant>(RHS) &&
13879           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13880         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
13881       break;
13882     default:
13883       break;
13884     }
13885 
13886     if (RewrittenRHS) {
13887       RewriteMap[LHS] = RewrittenRHS;
13888       if (LHS == RewrittenLHS)
13889         ExprsToRewrite.push_back(LHS);
13890     }
13891   };
13892   // Starting at the loop predecessor, climb up the predecessor chain, as long
13893   // as there are predecessors that can be found that have unique successors
13894   // leading to the original header.
13895   // TODO: share this logic with isLoopEntryGuardedByCond.
13896   DenseMap<const SCEV *, const SCEV *> RewriteMap;
13897   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13898            L->getLoopPredecessor(), L->getHeader());
13899        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13900 
13901     const BranchInst *LoopEntryPredicate =
13902         dyn_cast<BranchInst>(Pair.first->getTerminator());
13903     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13904       continue;
13905 
13906     bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second;
13907     SmallVector<Value *, 8> Worklist;
13908     SmallPtrSet<Value *, 8> Visited;
13909     Worklist.push_back(LoopEntryPredicate->getCondition());
13910     while (!Worklist.empty()) {
13911       Value *Cond = Worklist.pop_back_val();
13912       if (!Visited.insert(Cond).second)
13913         continue;
13914 
13915       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13916         auto Predicate =
13917             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
13918         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13919                          getSCEV(Cmp->getOperand(1)), RewriteMap);
13920         continue;
13921       }
13922 
13923       Value *L, *R;
13924       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
13925                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
13926         Worklist.push_back(L);
13927         Worklist.push_back(R);
13928       }
13929     }
13930   }
13931 
13932   // Also collect information from assumptions dominating the loop.
13933   for (auto &AssumeVH : AC.assumptions()) {
13934     if (!AssumeVH)
13935       continue;
13936     auto *AssumeI = cast<CallInst>(AssumeVH);
13937     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13938     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13939       continue;
13940     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13941                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13942   }
13943 
13944   if (RewriteMap.empty())
13945     return Expr;
13946 
13947   // Now that all rewrite information is collect, rewrite the collected
13948   // expressions with the information in the map. This applies information to
13949   // sub-expressions.
13950   if (ExprsToRewrite.size() > 1) {
13951     for (const SCEV *Expr : ExprsToRewrite) {
13952       const SCEV *RewriteTo = RewriteMap[Expr];
13953       RewriteMap.erase(Expr);
13954       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13955       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
13956     }
13957   }
13958 
13959   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13960   return Rewriter.visit(Expr);
13961 }
13962