]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Analysis/ScalarEvolution.cpp
Merge ^/head r317216 through r317280.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Analysis / ScalarEvolution.cpp
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/ScopeExit.h"
65 #include "llvm/ADT/Sequence.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/Statistic.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/InstructionSimplify.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
73 #include "llvm/Analysis/TargetLibraryInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/GlobalAlias.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/InstIterator.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/LLVMContext.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/Operator.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include "llvm/Support/MathExtras.h"
93 #include "llvm/Support/raw_ostream.h"
94 #include "llvm/Support/SaveAndRestore.h"
95 #include <algorithm>
96 using namespace llvm;
97
98 #define DEBUG_TYPE "scalar-evolution"
99
100 STATISTIC(NumArrayLenItCounts,
101           "Number of trip counts computed with array length");
102 STATISTIC(NumTripCountsComputed,
103           "Number of loops with predictable loop counts");
104 STATISTIC(NumTripCountsNotComputed,
105           "Number of loops without predictable loop counts");
106 STATISTIC(NumBruteForceTripCountsComputed,
107           "Number of loops with trip counts computed by force");
108
109 static cl::opt<unsigned>
110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
111                         cl::desc("Maximum number of iterations SCEV will "
112                                  "symbolically execute a constant "
113                                  "derived loop"),
114                         cl::init(100));
115
116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
117 static cl::opt<bool>
118 VerifySCEV("verify-scev",
119            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
120 static cl::opt<bool>
121     VerifySCEVMap("verify-scev-maps",
122                   cl::desc("Verify no dangling value in ScalarEvolution's "
123                            "ExprValueMap (slow)"));
124
125 static cl::opt<unsigned> MulOpsInlineThreshold(
126     "scev-mulops-inline-threshold", cl::Hidden,
127     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
128     cl::init(1000));
129
130 static cl::opt<unsigned> AddOpsInlineThreshold(
131     "scev-addops-inline-threshold", cl::Hidden,
132     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
133     cl::init(500));
134
135 static cl::opt<unsigned> MaxSCEVCompareDepth(
136     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
137     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
138     cl::init(32));
139
140 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
141     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
142     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
143     cl::init(2));
144
145 static cl::opt<unsigned> MaxValueCompareDepth(
146     "scalar-evolution-max-value-compare-depth", cl::Hidden,
147     cl::desc("Maximum depth of recursive value complexity comparisons"),
148     cl::init(2));
149
150 static cl::opt<unsigned>
151     MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
152                     cl::desc("Maximum depth of recursive AddExpr"),
153                     cl::init(32));
154
155 static cl::opt<unsigned> MaxConstantEvolvingDepth(
156     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
157     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
158
159 //===----------------------------------------------------------------------===//
160 //                           SCEV class definitions
161 //===----------------------------------------------------------------------===//
162
163 //===----------------------------------------------------------------------===//
164 // Implementation of the SCEV class.
165 //
166
167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168 LLVM_DUMP_METHOD void SCEV::dump() const {
169   print(dbgs());
170   dbgs() << '\n';
171 }
172 #endif
173
174 void SCEV::print(raw_ostream &OS) const {
175   switch (static_cast<SCEVTypes>(getSCEVType())) {
176   case scConstant:
177     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
178     return;
179   case scTruncate: {
180     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
181     const SCEV *Op = Trunc->getOperand();
182     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
183        << *Trunc->getType() << ")";
184     return;
185   }
186   case scZeroExtend: {
187     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
188     const SCEV *Op = ZExt->getOperand();
189     OS << "(zext " << *Op->getType() << " " << *Op << " to "
190        << *ZExt->getType() << ")";
191     return;
192   }
193   case scSignExtend: {
194     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
195     const SCEV *Op = SExt->getOperand();
196     OS << "(sext " << *Op->getType() << " " << *Op << " to "
197        << *SExt->getType() << ")";
198     return;
199   }
200   case scAddRecExpr: {
201     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
202     OS << "{" << *AR->getOperand(0);
203     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
204       OS << ",+," << *AR->getOperand(i);
205     OS << "}<";
206     if (AR->hasNoUnsignedWrap())
207       OS << "nuw><";
208     if (AR->hasNoSignedWrap())
209       OS << "nsw><";
210     if (AR->hasNoSelfWrap() &&
211         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
212       OS << "nw><";
213     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
214     OS << ">";
215     return;
216   }
217   case scAddExpr:
218   case scMulExpr:
219   case scUMaxExpr:
220   case scSMaxExpr: {
221     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
222     const char *OpStr = nullptr;
223     switch (NAry->getSCEVType()) {
224     case scAddExpr: OpStr = " + "; break;
225     case scMulExpr: OpStr = " * "; break;
226     case scUMaxExpr: OpStr = " umax "; break;
227     case scSMaxExpr: OpStr = " smax "; break;
228     }
229     OS << "(";
230     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
231          I != E; ++I) {
232       OS << **I;
233       if (std::next(I) != E)
234         OS << OpStr;
235     }
236     OS << ")";
237     switch (NAry->getSCEVType()) {
238     case scAddExpr:
239     case scMulExpr:
240       if (NAry->hasNoUnsignedWrap())
241         OS << "<nuw>";
242       if (NAry->hasNoSignedWrap())
243         OS << "<nsw>";
244     }
245     return;
246   }
247   case scUDivExpr: {
248     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
249     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
250     return;
251   }
252   case scUnknown: {
253     const SCEVUnknown *U = cast<SCEVUnknown>(this);
254     Type *AllocTy;
255     if (U->isSizeOf(AllocTy)) {
256       OS << "sizeof(" << *AllocTy << ")";
257       return;
258     }
259     if (U->isAlignOf(AllocTy)) {
260       OS << "alignof(" << *AllocTy << ")";
261       return;
262     }
263
264     Type *CTy;
265     Constant *FieldNo;
266     if (U->isOffsetOf(CTy, FieldNo)) {
267       OS << "offsetof(" << *CTy << ", ";
268       FieldNo->printAsOperand(OS, false);
269       OS << ")";
270       return;
271     }
272
273     // Otherwise just print it normally.
274     U->getValue()->printAsOperand(OS, false);
275     return;
276   }
277   case scCouldNotCompute:
278     OS << "***COULDNOTCOMPUTE***";
279     return;
280   }
281   llvm_unreachable("Unknown SCEV kind!");
282 }
283
284 Type *SCEV::getType() const {
285   switch (static_cast<SCEVTypes>(getSCEVType())) {
286   case scConstant:
287     return cast<SCEVConstant>(this)->getType();
288   case scTruncate:
289   case scZeroExtend:
290   case scSignExtend:
291     return cast<SCEVCastExpr>(this)->getType();
292   case scAddRecExpr:
293   case scMulExpr:
294   case scUMaxExpr:
295   case scSMaxExpr:
296     return cast<SCEVNAryExpr>(this)->getType();
297   case scAddExpr:
298     return cast<SCEVAddExpr>(this)->getType();
299   case scUDivExpr:
300     return cast<SCEVUDivExpr>(this)->getType();
301   case scUnknown:
302     return cast<SCEVUnknown>(this)->getType();
303   case scCouldNotCompute:
304     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
305   }
306   llvm_unreachable("Unknown SCEV kind!");
307 }
308
309 bool SCEV::isZero() const {
310   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
311     return SC->getValue()->isZero();
312   return false;
313 }
314
315 bool SCEV::isOne() const {
316   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
317     return SC->getValue()->isOne();
318   return false;
319 }
320
321 bool SCEV::isAllOnesValue() const {
322   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
323     return SC->getValue()->isAllOnesValue();
324   return false;
325 }
326
327 bool SCEV::isNonConstantNegative() const {
328   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
329   if (!Mul) return false;
330
331   // If there is a constant factor, it will be first.
332   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
333   if (!SC) return false;
334
335   // Return true if the value is negative, this matches things like (-42 * V).
336   return SC->getAPInt().isNegative();
337 }
338
339 SCEVCouldNotCompute::SCEVCouldNotCompute() :
340   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
341
342 bool SCEVCouldNotCompute::classof(const SCEV *S) {
343   return S->getSCEVType() == scCouldNotCompute;
344 }
345
346 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
347   FoldingSetNodeID ID;
348   ID.AddInteger(scConstant);
349   ID.AddPointer(V);
350   void *IP = nullptr;
351   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
352   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
353   UniqueSCEVs.InsertNode(S, IP);
354   return S;
355 }
356
357 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
358   return getConstant(ConstantInt::get(getContext(), Val));
359 }
360
361 const SCEV *
362 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
363   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
364   return getConstant(ConstantInt::get(ITy, V, isSigned));
365 }
366
367 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
368                            unsigned SCEVTy, const SCEV *op, Type *ty)
369   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
370
371 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
372                                    const SCEV *op, Type *ty)
373   : SCEVCastExpr(ID, scTruncate, op, ty) {
374   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
375          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
376          "Cannot truncate non-integer value!");
377 }
378
379 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
380                                        const SCEV *op, Type *ty)
381   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
382   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
383          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
384          "Cannot zero extend non-integer value!");
385 }
386
387 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
388                                        const SCEV *op, Type *ty)
389   : SCEVCastExpr(ID, scSignExtend, op, ty) {
390   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
391          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
392          "Cannot sign extend non-integer value!");
393 }
394
395 void SCEVUnknown::deleted() {
396   // Clear this SCEVUnknown from various maps.
397   SE->forgetMemoizedResults(this);
398
399   // Remove this SCEVUnknown from the uniquing map.
400   SE->UniqueSCEVs.RemoveNode(this);
401
402   // Release the value.
403   setValPtr(nullptr);
404 }
405
406 void SCEVUnknown::allUsesReplacedWith(Value *New) {
407   // Clear this SCEVUnknown from various maps.
408   SE->forgetMemoizedResults(this);
409
410   // Remove this SCEVUnknown from the uniquing map.
411   SE->UniqueSCEVs.RemoveNode(this);
412
413   // Update this SCEVUnknown to point to the new value. This is needed
414   // because there may still be outstanding SCEVs which still point to
415   // this SCEVUnknown.
416   setValPtr(New);
417 }
418
419 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
420   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
421     if (VCE->getOpcode() == Instruction::PtrToInt)
422       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
423         if (CE->getOpcode() == Instruction::GetElementPtr &&
424             CE->getOperand(0)->isNullValue() &&
425             CE->getNumOperands() == 2)
426           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
427             if (CI->isOne()) {
428               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
429                                  ->getElementType();
430               return true;
431             }
432
433   return false;
434 }
435
436 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
437   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
438     if (VCE->getOpcode() == Instruction::PtrToInt)
439       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440         if (CE->getOpcode() == Instruction::GetElementPtr &&
441             CE->getOperand(0)->isNullValue()) {
442           Type *Ty =
443             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
444           if (StructType *STy = dyn_cast<StructType>(Ty))
445             if (!STy->isPacked() &&
446                 CE->getNumOperands() == 3 &&
447                 CE->getOperand(1)->isNullValue()) {
448               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
449                 if (CI->isOne() &&
450                     STy->getNumElements() == 2 &&
451                     STy->getElementType(0)->isIntegerTy(1)) {
452                   AllocTy = STy->getElementType(1);
453                   return true;
454                 }
455             }
456         }
457
458   return false;
459 }
460
461 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
462   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
463     if (VCE->getOpcode() == Instruction::PtrToInt)
464       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
465         if (CE->getOpcode() == Instruction::GetElementPtr &&
466             CE->getNumOperands() == 3 &&
467             CE->getOperand(0)->isNullValue() &&
468             CE->getOperand(1)->isNullValue()) {
469           Type *Ty =
470             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
471           // Ignore vector types here so that ScalarEvolutionExpander doesn't
472           // emit getelementptrs that index into vectors.
473           if (Ty->isStructTy() || Ty->isArrayTy()) {
474             CTy = Ty;
475             FieldNo = CE->getOperand(2);
476             return true;
477           }
478         }
479
480   return false;
481 }
482
483 //===----------------------------------------------------------------------===//
484 //                               SCEV Utilities
485 //===----------------------------------------------------------------------===//
486
487 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
488 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
489 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
490 /// have been previously deemed to be "equally complex" by this routine.  It is
491 /// intended to avoid exponential time complexity in cases like:
492 ///
493 ///   %a = f(%x, %y)
494 ///   %b = f(%a, %a)
495 ///   %c = f(%b, %b)
496 ///
497 ///   %d = f(%x, %y)
498 ///   %e = f(%d, %d)
499 ///   %f = f(%e, %e)
500 ///
501 ///   CompareValueComplexity(%f, %c)
502 ///
503 /// Since we do not continue running this routine on expression trees once we
504 /// have seen unequal values, there is no need to track them in the cache.
505 static int
506 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
507                        const LoopInfo *const LI, Value *LV, Value *RV,
508                        unsigned Depth) {
509   if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
510     return 0;
511
512   // Order pointer values after integer values. This helps SCEVExpander form
513   // GEPs.
514   bool LIsPointer = LV->getType()->isPointerTy(),
515        RIsPointer = RV->getType()->isPointerTy();
516   if (LIsPointer != RIsPointer)
517     return (int)LIsPointer - (int)RIsPointer;
518
519   // Compare getValueID values.
520   unsigned LID = LV->getValueID(), RID = RV->getValueID();
521   if (LID != RID)
522     return (int)LID - (int)RID;
523
524   // Sort arguments by their position.
525   if (const auto *LA = dyn_cast<Argument>(LV)) {
526     const auto *RA = cast<Argument>(RV);
527     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
528     return (int)LArgNo - (int)RArgNo;
529   }
530
531   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
532     const auto *RGV = cast<GlobalValue>(RV);
533
534     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
535       auto LT = GV->getLinkage();
536       return !(GlobalValue::isPrivateLinkage(LT) ||
537                GlobalValue::isInternalLinkage(LT));
538     };
539
540     // Use the names to distinguish the two values, but only if the
541     // names are semantically important.
542     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
543       return LGV->getName().compare(RGV->getName());
544   }
545
546   // For instructions, compare their loop depth, and their operand count.  This
547   // is pretty loose.
548   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
549     const auto *RInst = cast<Instruction>(RV);
550
551     // Compare loop depths.
552     const BasicBlock *LParent = LInst->getParent(),
553                      *RParent = RInst->getParent();
554     if (LParent != RParent) {
555       unsigned LDepth = LI->getLoopDepth(LParent),
556                RDepth = LI->getLoopDepth(RParent);
557       if (LDepth != RDepth)
558         return (int)LDepth - (int)RDepth;
559     }
560
561     // Compare the number of operands.
562     unsigned LNumOps = LInst->getNumOperands(),
563              RNumOps = RInst->getNumOperands();
564     if (LNumOps != RNumOps)
565       return (int)LNumOps - (int)RNumOps;
566
567     for (unsigned Idx : seq(0u, LNumOps)) {
568       int Result =
569           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
570                                  RInst->getOperand(Idx), Depth + 1);
571       if (Result != 0)
572         return Result;
573     }
574   }
575
576   EqCache.insert({LV, RV});
577   return 0;
578 }
579
580 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
581 // than RHS, respectively. A three-way result allows recursive comparisons to be
582 // more efficient.
583 static int CompareSCEVComplexity(
584     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
585     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
586     unsigned Depth = 0) {
587   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
588   if (LHS == RHS)
589     return 0;
590
591   // Primarily, sort the SCEVs by their getSCEVType().
592   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
593   if (LType != RType)
594     return (int)LType - (int)RType;
595
596   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
597     return 0;
598   // Aside from the getSCEVType() ordering, the particular ordering
599   // isn't very important except that it's beneficial to be consistent,
600   // so that (a + b) and (b + a) don't end up as different expressions.
601   switch (static_cast<SCEVTypes>(LType)) {
602   case scUnknown: {
603     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
604     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
605
606     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
607     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
608                                    Depth + 1);
609     if (X == 0)
610       EqCacheSCEV.insert({LHS, RHS});
611     return X;
612   }
613
614   case scConstant: {
615     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
616     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
617
618     // Compare constant values.
619     const APInt &LA = LC->getAPInt();
620     const APInt &RA = RC->getAPInt();
621     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
622     if (LBitWidth != RBitWidth)
623       return (int)LBitWidth - (int)RBitWidth;
624     return LA.ult(RA) ? -1 : 1;
625   }
626
627   case scAddRecExpr: {
628     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
629     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
630
631     // Compare addrec loop depths.
632     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
633     if (LLoop != RLoop) {
634       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
635       if (LDepth != RDepth)
636         return (int)LDepth - (int)RDepth;
637     }
638
639     // Addrec complexity grows with operand count.
640     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
641     if (LNumOps != RNumOps)
642       return (int)LNumOps - (int)RNumOps;
643
644     // Lexicographically compare.
645     for (unsigned i = 0; i != LNumOps; ++i) {
646       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
647                                     RA->getOperand(i), Depth + 1);
648       if (X != 0)
649         return X;
650     }
651     EqCacheSCEV.insert({LHS, RHS});
652     return 0;
653   }
654
655   case scAddExpr:
656   case scMulExpr:
657   case scSMaxExpr:
658   case scUMaxExpr: {
659     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
660     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
661
662     // Lexicographically compare n-ary expressions.
663     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
664     if (LNumOps != RNumOps)
665       return (int)LNumOps - (int)RNumOps;
666
667     for (unsigned i = 0; i != LNumOps; ++i) {
668       if (i >= RNumOps)
669         return 1;
670       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
671                                     RC->getOperand(i), Depth + 1);
672       if (X != 0)
673         return X;
674     }
675     EqCacheSCEV.insert({LHS, RHS});
676     return 0;
677   }
678
679   case scUDivExpr: {
680     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
681     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
682
683     // Lexicographically compare udiv expressions.
684     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
685                                   Depth + 1);
686     if (X != 0)
687       return X;
688     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
689                               Depth + 1);
690     if (X == 0)
691       EqCacheSCEV.insert({LHS, RHS});
692     return X;
693   }
694
695   case scTruncate:
696   case scZeroExtend:
697   case scSignExtend: {
698     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
699     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
700
701     // Compare cast expressions by operand.
702     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
703                                   RC->getOperand(), Depth + 1);
704     if (X == 0)
705       EqCacheSCEV.insert({LHS, RHS});
706     return X;
707   }
708
709   case scCouldNotCompute:
710     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
711   }
712   llvm_unreachable("Unknown SCEV kind!");
713 }
714
715 /// Given a list of SCEV objects, order them by their complexity, and group
716 /// objects of the same complexity together by value.  When this routine is
717 /// finished, we know that any duplicates in the vector are consecutive and that
718 /// complexity is monotonically increasing.
719 ///
720 /// Note that we go take special precautions to ensure that we get deterministic
721 /// results from this routine.  In other words, we don't want the results of
722 /// this to depend on where the addresses of various SCEV objects happened to
723 /// land in memory.
724 ///
725 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
726                               LoopInfo *LI) {
727   if (Ops.size() < 2) return;  // Noop
728
729   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
730   if (Ops.size() == 2) {
731     // This is the common case, which also happens to be trivially simple.
732     // Special case it.
733     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
734     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
735       std::swap(LHS, RHS);
736     return;
737   }
738
739   // Do the rough sort by complexity.
740   std::stable_sort(Ops.begin(), Ops.end(),
741                    [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
742                      return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
743                    });
744
745   // Now that we are sorted by complexity, group elements of the same
746   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
747   // be extremely short in practice.  Note that we take this approach because we
748   // do not want to depend on the addresses of the objects we are grouping.
749   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
750     const SCEV *S = Ops[i];
751     unsigned Complexity = S->getSCEVType();
752
753     // If there are any objects of the same complexity and same value as this
754     // one, group them.
755     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
756       if (Ops[j] == S) { // Found a duplicate.
757         // Move it to immediately after i'th element.
758         std::swap(Ops[i+1], Ops[j]);
759         ++i;   // no need to rescan it.
760         if (i == e-2) return;  // Done!
761       }
762     }
763   }
764 }
765
766 // Returns the size of the SCEV S.
767 static inline int sizeOfSCEV(const SCEV *S) {
768   struct FindSCEVSize {
769     int Size;
770     FindSCEVSize() : Size(0) {}
771
772     bool follow(const SCEV *S) {
773       ++Size;
774       // Keep looking at all operands of S.
775       return true;
776     }
777     bool isDone() const {
778       return false;
779     }
780   };
781
782   FindSCEVSize F;
783   SCEVTraversal<FindSCEVSize> ST(F);
784   ST.visitAll(S);
785   return F.Size;
786 }
787
788 namespace {
789
790 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
791 public:
792   // Computes the Quotient and Remainder of the division of Numerator by
793   // Denominator.
794   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
795                      const SCEV *Denominator, const SCEV **Quotient,
796                      const SCEV **Remainder) {
797     assert(Numerator && Denominator && "Uninitialized SCEV");
798
799     SCEVDivision D(SE, Numerator, Denominator);
800
801     // Check for the trivial case here to avoid having to check for it in the
802     // rest of the code.
803     if (Numerator == Denominator) {
804       *Quotient = D.One;
805       *Remainder = D.Zero;
806       return;
807     }
808
809     if (Numerator->isZero()) {
810       *Quotient = D.Zero;
811       *Remainder = D.Zero;
812       return;
813     }
814
815     // A simple case when N/1. The quotient is N.
816     if (Denominator->isOne()) {
817       *Quotient = Numerator;
818       *Remainder = D.Zero;
819       return;
820     }
821
822     // Split the Denominator when it is a product.
823     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
824       const SCEV *Q, *R;
825       *Quotient = Numerator;
826       for (const SCEV *Op : T->operands()) {
827         divide(SE, *Quotient, Op, &Q, &R);
828         *Quotient = Q;
829
830         // Bail out when the Numerator is not divisible by one of the terms of
831         // the Denominator.
832         if (!R->isZero()) {
833           *Quotient = D.Zero;
834           *Remainder = Numerator;
835           return;
836         }
837       }
838       *Remainder = D.Zero;
839       return;
840     }
841
842     D.visit(Numerator);
843     *Quotient = D.Quotient;
844     *Remainder = D.Remainder;
845   }
846
847   // Except in the trivial case described above, we do not know how to divide
848   // Expr by Denominator for the following functions with empty implementation.
849   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
850   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
851   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
852   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
853   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
854   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
855   void visitUnknown(const SCEVUnknown *Numerator) {}
856   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
857
858   void visitConstant(const SCEVConstant *Numerator) {
859     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
860       APInt NumeratorVal = Numerator->getAPInt();
861       APInt DenominatorVal = D->getAPInt();
862       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
863       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
864
865       if (NumeratorBW > DenominatorBW)
866         DenominatorVal = DenominatorVal.sext(NumeratorBW);
867       else if (NumeratorBW < DenominatorBW)
868         NumeratorVal = NumeratorVal.sext(DenominatorBW);
869
870       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
871       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
872       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
873       Quotient = SE.getConstant(QuotientVal);
874       Remainder = SE.getConstant(RemainderVal);
875       return;
876     }
877   }
878
879   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
880     const SCEV *StartQ, *StartR, *StepQ, *StepR;
881     if (!Numerator->isAffine())
882       return cannotDivide(Numerator);
883     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
884     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
885     // Bail out if the types do not match.
886     Type *Ty = Denominator->getType();
887     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
888         Ty != StepQ->getType() || Ty != StepR->getType())
889       return cannotDivide(Numerator);
890     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
891                                 Numerator->getNoWrapFlags());
892     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
893                                  Numerator->getNoWrapFlags());
894   }
895
896   void visitAddExpr(const SCEVAddExpr *Numerator) {
897     SmallVector<const SCEV *, 2> Qs, Rs;
898     Type *Ty = Denominator->getType();
899
900     for (const SCEV *Op : Numerator->operands()) {
901       const SCEV *Q, *R;
902       divide(SE, Op, Denominator, &Q, &R);
903
904       // Bail out if types do not match.
905       if (Ty != Q->getType() || Ty != R->getType())
906         return cannotDivide(Numerator);
907
908       Qs.push_back(Q);
909       Rs.push_back(R);
910     }
911
912     if (Qs.size() == 1) {
913       Quotient = Qs[0];
914       Remainder = Rs[0];
915       return;
916     }
917
918     Quotient = SE.getAddExpr(Qs);
919     Remainder = SE.getAddExpr(Rs);
920   }
921
922   void visitMulExpr(const SCEVMulExpr *Numerator) {
923     SmallVector<const SCEV *, 2> Qs;
924     Type *Ty = Denominator->getType();
925
926     bool FoundDenominatorTerm = false;
927     for (const SCEV *Op : Numerator->operands()) {
928       // Bail out if types do not match.
929       if (Ty != Op->getType())
930         return cannotDivide(Numerator);
931
932       if (FoundDenominatorTerm) {
933         Qs.push_back(Op);
934         continue;
935       }
936
937       // Check whether Denominator divides one of the product operands.
938       const SCEV *Q, *R;
939       divide(SE, Op, Denominator, &Q, &R);
940       if (!R->isZero()) {
941         Qs.push_back(Op);
942         continue;
943       }
944
945       // Bail out if types do not match.
946       if (Ty != Q->getType())
947         return cannotDivide(Numerator);
948
949       FoundDenominatorTerm = true;
950       Qs.push_back(Q);
951     }
952
953     if (FoundDenominatorTerm) {
954       Remainder = Zero;
955       if (Qs.size() == 1)
956         Quotient = Qs[0];
957       else
958         Quotient = SE.getMulExpr(Qs);
959       return;
960     }
961
962     if (!isa<SCEVUnknown>(Denominator))
963       return cannotDivide(Numerator);
964
965     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
966     ValueToValueMap RewriteMap;
967     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
968         cast<SCEVConstant>(Zero)->getValue();
969     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
970
971     if (Remainder->isZero()) {
972       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
973       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
974           cast<SCEVConstant>(One)->getValue();
975       Quotient =
976           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
977       return;
978     }
979
980     // Quotient is (Numerator - Remainder) divided by Denominator.
981     const SCEV *Q, *R;
982     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
983     // This SCEV does not seem to simplify: fail the division here.
984     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
985       return cannotDivide(Numerator);
986     divide(SE, Diff, Denominator, &Q, &R);
987     if (R != Zero)
988       return cannotDivide(Numerator);
989     Quotient = Q;
990   }
991
992 private:
993   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
994                const SCEV *Denominator)
995       : SE(S), Denominator(Denominator) {
996     Zero = SE.getZero(Denominator->getType());
997     One = SE.getOne(Denominator->getType());
998
999     // We generally do not know how to divide Expr by Denominator. We
1000     // initialize the division to a "cannot divide" state to simplify the rest
1001     // of the code.
1002     cannotDivide(Numerator);
1003   }
1004
1005   // Convenience function for giving up on the division. We set the quotient to
1006   // be equal to zero and the remainder to be equal to the numerator.
1007   void cannotDivide(const SCEV *Numerator) {
1008     Quotient = Zero;
1009     Remainder = Numerator;
1010   }
1011
1012   ScalarEvolution &SE;
1013   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1014 };
1015
1016 }
1017
1018 //===----------------------------------------------------------------------===//
1019 //                      Simple SCEV method implementations
1020 //===----------------------------------------------------------------------===//
1021
1022 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1023 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1024                                        ScalarEvolution &SE,
1025                                        Type *ResultTy) {
1026   // Handle the simplest case efficiently.
1027   if (K == 1)
1028     return SE.getTruncateOrZeroExtend(It, ResultTy);
1029
1030   // We are using the following formula for BC(It, K):
1031   //
1032   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1033   //
1034   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1035   // overflow.  Hence, we must assure that the result of our computation is
1036   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1037   // safe in modular arithmetic.
1038   //
1039   // However, this code doesn't use exactly that formula; the formula it uses
1040   // is something like the following, where T is the number of factors of 2 in
1041   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1042   // exponentiation:
1043   //
1044   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1045   //
1046   // This formula is trivially equivalent to the previous formula.  However,
1047   // this formula can be implemented much more efficiently.  The trick is that
1048   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1049   // arithmetic.  To do exact division in modular arithmetic, all we have
1050   // to do is multiply by the inverse.  Therefore, this step can be done at
1051   // width W.
1052   //
1053   // The next issue is how to safely do the division by 2^T.  The way this
1054   // is done is by doing the multiplication step at a width of at least W + T
1055   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1056   // when we perform the division by 2^T (which is equivalent to a right shift
1057   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1058   // truncated out after the division by 2^T.
1059   //
1060   // In comparison to just directly using the first formula, this technique
1061   // is much more efficient; using the first formula requires W * K bits,
1062   // but this formula less than W + K bits. Also, the first formula requires
1063   // a division step, whereas this formula only requires multiplies and shifts.
1064   //
1065   // It doesn't matter whether the subtraction step is done in the calculation
1066   // width or the input iteration count's width; if the subtraction overflows,
1067   // the result must be zero anyway.  We prefer here to do it in the width of
1068   // the induction variable because it helps a lot for certain cases; CodeGen
1069   // isn't smart enough to ignore the overflow, which leads to much less
1070   // efficient code if the width of the subtraction is wider than the native
1071   // register width.
1072   //
1073   // (It's possible to not widen at all by pulling out factors of 2 before
1074   // the multiplication; for example, K=2 can be calculated as
1075   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1076   // extra arithmetic, so it's not an obvious win, and it gets
1077   // much more complicated for K > 3.)
1078
1079   // Protection from insane SCEVs; this bound is conservative,
1080   // but it probably doesn't matter.
1081   if (K > 1000)
1082     return SE.getCouldNotCompute();
1083
1084   unsigned W = SE.getTypeSizeInBits(ResultTy);
1085
1086   // Calculate K! / 2^T and T; we divide out the factors of two before
1087   // multiplying for calculating K! / 2^T to avoid overflow.
1088   // Other overflow doesn't matter because we only care about the bottom
1089   // W bits of the result.
1090   APInt OddFactorial(W, 1);
1091   unsigned T = 1;
1092   for (unsigned i = 3; i <= K; ++i) {
1093     APInt Mult(W, i);
1094     unsigned TwoFactors = Mult.countTrailingZeros();
1095     T += TwoFactors;
1096     Mult.lshrInPlace(TwoFactors);
1097     OddFactorial *= Mult;
1098   }
1099
1100   // We need at least W + T bits for the multiplication step
1101   unsigned CalculationBits = W + T;
1102
1103   // Calculate 2^T, at width T+W.
1104   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1105
1106   // Calculate the multiplicative inverse of K! / 2^T;
1107   // this multiplication factor will perform the exact division by
1108   // K! / 2^T.
1109   APInt Mod = APInt::getSignedMinValue(W+1);
1110   APInt MultiplyFactor = OddFactorial.zext(W+1);
1111   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1112   MultiplyFactor = MultiplyFactor.trunc(W);
1113
1114   // Calculate the product, at width T+W
1115   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1116                                                       CalculationBits);
1117   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1118   for (unsigned i = 1; i != K; ++i) {
1119     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1120     Dividend = SE.getMulExpr(Dividend,
1121                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1122   }
1123
1124   // Divide by 2^T
1125   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1126
1127   // Truncate the result, and divide by K! / 2^T.
1128
1129   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1130                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1131 }
1132
1133 /// Return the value of this chain of recurrences at the specified iteration
1134 /// number.  We can evaluate this recurrence by multiplying each element in the
1135 /// chain by the binomial coefficient corresponding to it.  In other words, we
1136 /// can evaluate {A,+,B,+,C,+,D} as:
1137 ///
1138 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1139 ///
1140 /// where BC(It, k) stands for binomial coefficient.
1141 ///
1142 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1143                                                 ScalarEvolution &SE) const {
1144   const SCEV *Result = getStart();
1145   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1146     // The computation is correct in the face of overflow provided that the
1147     // multiplication is performed _after_ the evaluation of the binomial
1148     // coefficient.
1149     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1150     if (isa<SCEVCouldNotCompute>(Coeff))
1151       return Coeff;
1152
1153     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1154   }
1155   return Result;
1156 }
1157
1158 //===----------------------------------------------------------------------===//
1159 //                    SCEV Expression folder implementations
1160 //===----------------------------------------------------------------------===//
1161
1162 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1163                                              Type *Ty) {
1164   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1165          "This is not a truncating conversion!");
1166   assert(isSCEVable(Ty) &&
1167          "This is not a conversion to a SCEVable type!");
1168   Ty = getEffectiveSCEVType(Ty);
1169
1170   FoldingSetNodeID ID;
1171   ID.AddInteger(scTruncate);
1172   ID.AddPointer(Op);
1173   ID.AddPointer(Ty);
1174   void *IP = nullptr;
1175   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1176
1177   // Fold if the operand is constant.
1178   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1179     return getConstant(
1180       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1181
1182   // trunc(trunc(x)) --> trunc(x)
1183   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1184     return getTruncateExpr(ST->getOperand(), Ty);
1185
1186   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1187   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1188     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1189
1190   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1191   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1192     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1193
1194   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1195   // eliminate all the truncates, or we replace other casts with truncates.
1196   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1197     SmallVector<const SCEV *, 4> Operands;
1198     bool hasTrunc = false;
1199     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1200       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1201       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1202         hasTrunc = isa<SCEVTruncateExpr>(S);
1203       Operands.push_back(S);
1204     }
1205     if (!hasTrunc)
1206       return getAddExpr(Operands);
1207     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1208   }
1209
1210   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1211   // eliminate all the truncates, or we replace other casts with truncates.
1212   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1213     SmallVector<const SCEV *, 4> Operands;
1214     bool hasTrunc = false;
1215     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1216       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1217       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1218         hasTrunc = isa<SCEVTruncateExpr>(S);
1219       Operands.push_back(S);
1220     }
1221     if (!hasTrunc)
1222       return getMulExpr(Operands);
1223     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1224   }
1225
1226   // If the input value is a chrec scev, truncate the chrec's operands.
1227   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1228     SmallVector<const SCEV *, 4> Operands;
1229     for (const SCEV *Op : AddRec->operands())
1230       Operands.push_back(getTruncateExpr(Op, Ty));
1231     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1232   }
1233
1234   // The cast wasn't folded; create an explicit cast node. We can reuse
1235   // the existing insert position since if we get here, we won't have
1236   // made any changes which would invalidate it.
1237   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1238                                                  Op, Ty);
1239   UniqueSCEVs.InsertNode(S, IP);
1240   return S;
1241 }
1242
1243 // Get the limit of a recurrence such that incrementing by Step cannot cause
1244 // signed overflow as long as the value of the recurrence within the
1245 // loop does not exceed this limit before incrementing.
1246 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1247                                                  ICmpInst::Predicate *Pred,
1248                                                  ScalarEvolution *SE) {
1249   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1250   if (SE->isKnownPositive(Step)) {
1251     *Pred = ICmpInst::ICMP_SLT;
1252     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1253                            SE->getSignedRange(Step).getSignedMax());
1254   }
1255   if (SE->isKnownNegative(Step)) {
1256     *Pred = ICmpInst::ICMP_SGT;
1257     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1258                            SE->getSignedRange(Step).getSignedMin());
1259   }
1260   return nullptr;
1261 }
1262
1263 // Get the limit of a recurrence such that incrementing by Step cannot cause
1264 // unsigned overflow as long as the value of the recurrence within the loop does
1265 // not exceed this limit before incrementing.
1266 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1267                                                    ICmpInst::Predicate *Pred,
1268                                                    ScalarEvolution *SE) {
1269   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1270   *Pred = ICmpInst::ICMP_ULT;
1271
1272   return SE->getConstant(APInt::getMinValue(BitWidth) -
1273                          SE->getUnsignedRange(Step).getUnsignedMax());
1274 }
1275
1276 namespace {
1277
1278 struct ExtendOpTraitsBase {
1279   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1280       const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
1281 };
1282
1283 // Used to make code generic over signed and unsigned overflow.
1284 template <typename ExtendOp> struct ExtendOpTraits {
1285   // Members present:
1286   //
1287   // static const SCEV::NoWrapFlags WrapType;
1288   //
1289   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1290   //
1291   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1292   //                                           ICmpInst::Predicate *Pred,
1293   //                                           ScalarEvolution *SE);
1294 };
1295
1296 template <>
1297 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1298   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1299
1300   static const GetExtendExprTy GetExtendExpr;
1301
1302   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303                                              ICmpInst::Predicate *Pred,
1304                                              ScalarEvolution *SE) {
1305     return getSignedOverflowLimitForStep(Step, Pred, SE);
1306   }
1307 };
1308
1309 const ExtendOpTraitsBase::GetExtendExprTy
1310     ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1311         &ScalarEvolution::getSignExtendExprCached;
1312
1313 template <>
1314 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1315   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1316
1317   static const GetExtendExprTy GetExtendExpr;
1318
1319   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1320                                              ICmpInst::Predicate *Pred,
1321                                              ScalarEvolution *SE) {
1322     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1323   }
1324 };
1325
1326 const ExtendOpTraitsBase::GetExtendExprTy
1327     ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1328         &ScalarEvolution::getZeroExtendExprCached;
1329 }
1330
1331 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1332 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1333 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1334 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1335 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1336 // expression "Step + sext/zext(PreIncAR)" is congruent with
1337 // "sext/zext(PostIncAR)"
1338 template <typename ExtendOpTy>
1339 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1340                                         ScalarEvolution *SE,
1341                                         ScalarEvolution::ExtendCacheTy &Cache) {
1342   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1343   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1344
1345   const Loop *L = AR->getLoop();
1346   const SCEV *Start = AR->getStart();
1347   const SCEV *Step = AR->getStepRecurrence(*SE);
1348
1349   // Check for a simple looking step prior to loop entry.
1350   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1351   if (!SA)
1352     return nullptr;
1353
1354   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1355   // subtraction is expensive. For this purpose, perform a quick and dirty
1356   // difference, by checking for Step in the operand list.
1357   SmallVector<const SCEV *, 4> DiffOps;
1358   for (const SCEV *Op : SA->operands())
1359     if (Op != Step)
1360       DiffOps.push_back(Op);
1361
1362   if (DiffOps.size() == SA->getNumOperands())
1363     return nullptr;
1364
1365   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1366   // `Step`:
1367
1368   // 1. NSW/NUW flags on the step increment.
1369   auto PreStartFlags =
1370     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1371   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1372   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1373       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1374
1375   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1376   // "S+X does not sign/unsign-overflow".
1377   //
1378
1379   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1380   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1381       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1382     return PreStart;
1383
1384   // 2. Direct overflow check on the step operation's expression.
1385   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1386   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1387   const SCEV *OperandExtendedStart =
1388       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1389                      (SE->*GetExtendExpr)(Step, WideTy, Cache));
1390   if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
1391     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1392       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1393       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1394       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1395       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1396     }
1397     return PreStart;
1398   }
1399
1400   // 3. Loop precondition.
1401   ICmpInst::Predicate Pred;
1402   const SCEV *OverflowLimit =
1403       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1404
1405   if (OverflowLimit &&
1406       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1407     return PreStart;
1408
1409   return nullptr;
1410 }
1411
1412 // Get the normalized zero or sign extended expression for this AddRec's Start.
1413 template <typename ExtendOpTy>
1414 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1415                                         ScalarEvolution *SE,
1416                                         ScalarEvolution::ExtendCacheTy &Cache) {
1417   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1418
1419   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
1420   if (!PreStart)
1421     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
1422
1423   return SE->getAddExpr(
1424       (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1425       (SE->*GetExtendExpr)(PreStart, Ty, Cache));
1426 }
1427
1428 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1429 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1430 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1431 //
1432 // Formally:
1433 //
1434 //     {S,+,X} == {S-T,+,X} + T
1435 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1436 //
1437 // If ({S-T,+,X} + T) does not overflow  ... (1)
1438 //
1439 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1440 //
1441 // If {S-T,+,X} does not overflow  ... (2)
1442 //
1443 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1444 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1445 //
1446 // If (S-T)+T does not overflow  ... (3)
1447 //
1448 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1449 //      == {Ext(S),+,Ext(X)} == LHS
1450 //
1451 // Thus, if (1), (2) and (3) are true for some T, then
1452 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1453 //
1454 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1455 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1456 // to check for (1) and (2).
1457 //
1458 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1459 // is `Delta` (defined below).
1460 //
1461 template <typename ExtendOpTy>
1462 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1463                                                 const SCEV *Step,
1464                                                 const Loop *L) {
1465   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1466
1467   // We restrict `Start` to a constant to prevent SCEV from spending too much
1468   // time here.  It is correct (but more expensive) to continue with a
1469   // non-constant `Start` and do a general SCEV subtraction to compute
1470   // `PreStart` below.
1471   //
1472   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1473   if (!StartC)
1474     return false;
1475
1476   APInt StartAI = StartC->getAPInt();
1477
1478   for (unsigned Delta : {-2, -1, 1, 2}) {
1479     const SCEV *PreStart = getConstant(StartAI - Delta);
1480
1481     FoldingSetNodeID ID;
1482     ID.AddInteger(scAddRecExpr);
1483     ID.AddPointer(PreStart);
1484     ID.AddPointer(Step);
1485     ID.AddPointer(L);
1486     void *IP = nullptr;
1487     const auto *PreAR =
1488       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1489
1490     // Give up if we don't already have the add recurrence we need because
1491     // actually constructing an add recurrence is relatively expensive.
1492     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1493       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1494       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1495       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1496           DeltaS, &Pred, this);
1497       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1498         return true;
1499     }
1500   }
1501
1502   return false;
1503 }
1504
1505 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1506   // Use the local cache to prevent exponential behavior of
1507   // getZeroExtendExprImpl.
1508   ExtendCacheTy Cache;
1509   return getZeroExtendExprCached(Op, Ty, Cache);
1510 }
1511
1512 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1513 /// related entry in the \p Cache, call getZeroExtendExprImpl and save
1514 /// the result in the \p Cache.
1515 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1516                                                      ExtendCacheTy &Cache) {
1517   auto It = Cache.find({Op, Ty});
1518   if (It != Cache.end())
1519     return It->second;
1520   const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1521   auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1522   assert(InsertResult.second && "Expect the key was not in the cache");
1523   (void)InsertResult;
1524   return ZExt;
1525 }
1526
1527 /// The real implementation of getZeroExtendExpr.
1528 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1529                                                    ExtendCacheTy &Cache) {
1530   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1531          "This is not an extending conversion!");
1532   assert(isSCEVable(Ty) &&
1533          "This is not a conversion to a SCEVable type!");
1534   Ty = getEffectiveSCEVType(Ty);
1535
1536   // Fold if the operand is constant.
1537   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1538     return getConstant(
1539         cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1540
1541   // zext(zext(x)) --> zext(x)
1542   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1543     return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
1544
1545   // Before doing any expensive analysis, check to see if we've already
1546   // computed a SCEV for this Op and Ty.
1547   FoldingSetNodeID ID;
1548   ID.AddInteger(scZeroExtend);
1549   ID.AddPointer(Op);
1550   ID.AddPointer(Ty);
1551   void *IP = nullptr;
1552   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1553
1554   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1555   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1556     // It's possible the bits taken off by the truncate were all zero bits. If
1557     // so, we should be able to simplify this further.
1558     const SCEV *X = ST->getOperand();
1559     ConstantRange CR = getUnsignedRange(X);
1560     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1561     unsigned NewBits = getTypeSizeInBits(Ty);
1562     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1563             CR.zextOrTrunc(NewBits)))
1564       return getTruncateOrZeroExtend(X, Ty);
1565   }
1566
1567   // If the input value is a chrec scev, and we can prove that the value
1568   // did not overflow the old, smaller, value, we can zero extend all of the
1569   // operands (often constants).  This allows analysis of something like
1570   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1571   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1572     if (AR->isAffine()) {
1573       const SCEV *Start = AR->getStart();
1574       const SCEV *Step = AR->getStepRecurrence(*this);
1575       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1576       const Loop *L = AR->getLoop();
1577
1578       if (!AR->hasNoUnsignedWrap()) {
1579         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1580         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1581       }
1582
1583       // If we have special knowledge that this addrec won't overflow,
1584       // we don't need to do any further analysis.
1585       if (AR->hasNoUnsignedWrap())
1586         return getAddRecExpr(
1587             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1588             getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1589
1590       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1591       // Note that this serves two purposes: It filters out loops that are
1592       // simply not analyzable, and it covers the case where this code is
1593       // being called from within backedge-taken count analysis, such that
1594       // attempting to ask for the backedge-taken count would likely result
1595       // in infinite recursion. In the later case, the analysis code will
1596       // cope with a conservative value, and it will take care to purge
1597       // that value once it has finished.
1598       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1599       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1600         // Manually compute the final value for AR, checking for
1601         // overflow.
1602
1603         // Check whether the backedge-taken count can be losslessly casted to
1604         // the addrec's type. The count is always unsigned.
1605         const SCEV *CastedMaxBECount =
1606           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1607         const SCEV *RecastedMaxBECount =
1608           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1609         if (MaxBECount == RecastedMaxBECount) {
1610           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1611           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1612           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1613           const SCEV *ZAdd =
1614               getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1615           const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
1616           const SCEV *WideMaxBECount =
1617               getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1618           const SCEV *OperandExtendedAdd = getAddExpr(
1619               WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1620                                                         Step, WideTy, Cache)));
1621           if (ZAdd == OperandExtendedAdd) {
1622             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1623             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1624             // Return the expression with the addrec on the outside.
1625             return getAddRecExpr(
1626                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1627                 getZeroExtendExprCached(Step, Ty, Cache), L,
1628                 AR->getNoWrapFlags());
1629           }
1630           // Similar to above, only this time treat the step value as signed.
1631           // This covers loops that count down.
1632           OperandExtendedAdd =
1633             getAddExpr(WideStart,
1634                        getMulExpr(WideMaxBECount,
1635                                   getSignExtendExpr(Step, WideTy)));
1636           if (ZAdd == OperandExtendedAdd) {
1637             // Cache knowledge of AR NW, which is propagated to this AddRec.
1638             // Negative step causes unsigned wrap, but it still can't self-wrap.
1639             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1640             // Return the expression with the addrec on the outside.
1641             return getAddRecExpr(
1642                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1643                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1644           }
1645         }
1646       }
1647
1648       // Normally, in the cases we can prove no-overflow via a
1649       // backedge guarding condition, we can also compute a backedge
1650       // taken count for the loop.  The exceptions are assumptions and
1651       // guards present in the loop -- SCEV is not great at exploiting
1652       // these to compute max backedge taken counts, but can still use
1653       // these to prove lack of overflow.  Use this fact to avoid
1654       // doing extra work that may not pay off.
1655       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1656           !AC.assumptions().empty()) {
1657         // If the backedge is guarded by a comparison with the pre-inc
1658         // value the addrec is safe. Also, if the entry is guarded by
1659         // a comparison with the start value and the backedge is
1660         // guarded by a comparison with the post-inc value, the addrec
1661         // is safe.
1662         if (isKnownPositive(Step)) {
1663           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1664                                       getUnsignedRange(Step).getUnsignedMax());
1665           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1666               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1667                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1668                                            AR->getPostIncExpr(*this), N))) {
1669             // Cache knowledge of AR NUW, which is propagated to this
1670             // AddRec.
1671             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1672             // Return the expression with the addrec on the outside.
1673             return getAddRecExpr(
1674                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1675                 getZeroExtendExprCached(Step, Ty, Cache), L,
1676                 AR->getNoWrapFlags());
1677           }
1678         } else if (isKnownNegative(Step)) {
1679           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1680                                       getSignedRange(Step).getSignedMin());
1681           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1682               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1683                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1684                                            AR->getPostIncExpr(*this), N))) {
1685             // Cache knowledge of AR NW, which is propagated to this
1686             // AddRec.  Negative step causes unsigned wrap, but it
1687             // still can't self-wrap.
1688             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1689             // Return the expression with the addrec on the outside.
1690             return getAddRecExpr(
1691                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1692                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1693           }
1694         }
1695       }
1696
1697       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1698         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1699         return getAddRecExpr(
1700             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1701             getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1702       }
1703     }
1704
1705   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1706     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1707     if (SA->hasNoUnsignedWrap()) {
1708       // If the addition does not unsign overflow then we can, by definition,
1709       // commute the zero extension with the addition operation.
1710       SmallVector<const SCEV *, 4> Ops;
1711       for (const auto *Op : SA->operands())
1712         Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
1713       return getAddExpr(Ops, SCEV::FlagNUW);
1714     }
1715   }
1716
1717   // The cast wasn't folded; create an explicit cast node.
1718   // Recompute the insert position, as it may have been invalidated.
1719   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1720   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1721                                                    Op, Ty);
1722   UniqueSCEVs.InsertNode(S, IP);
1723   return S;
1724 }
1725
1726 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1727   // Use the local cache to prevent exponential behavior of
1728   // getSignExtendExprImpl.
1729   ExtendCacheTy Cache;
1730   return getSignExtendExprCached(Op, Ty, Cache);
1731 }
1732
1733 /// Query \p Cache before calling getSignExtendExprImpl. If there is no
1734 /// related entry in the \p Cache, call getSignExtendExprImpl and save
1735 /// the result in the \p Cache.
1736 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1737                                                      ExtendCacheTy &Cache) {
1738   auto It = Cache.find({Op, Ty});
1739   if (It != Cache.end())
1740     return It->second;
1741   const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1742   auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1743   assert(InsertResult.second && "Expect the key was not in the cache");
1744   (void)InsertResult;
1745   return SExt;
1746 }
1747
1748 /// The real implementation of getSignExtendExpr.
1749 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1750                                                    ExtendCacheTy &Cache) {
1751   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1752          "This is not an extending conversion!");
1753   assert(isSCEVable(Ty) &&
1754          "This is not a conversion to a SCEVable type!");
1755   Ty = getEffectiveSCEVType(Ty);
1756
1757   // Fold if the operand is constant.
1758   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1759     return getConstant(
1760         cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1761
1762   // sext(sext(x)) --> sext(x)
1763   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1764     return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
1765
1766   // sext(zext(x)) --> zext(x)
1767   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1768     return getZeroExtendExpr(SZ->getOperand(), Ty);
1769
1770   // Before doing any expensive analysis, check to see if we've already
1771   // computed a SCEV for this Op and Ty.
1772   FoldingSetNodeID ID;
1773   ID.AddInteger(scSignExtend);
1774   ID.AddPointer(Op);
1775   ID.AddPointer(Ty);
1776   void *IP = nullptr;
1777   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1778
1779   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1780   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1781     // It's possible the bits taken off by the truncate were all sign bits. If
1782     // so, we should be able to simplify this further.
1783     const SCEV *X = ST->getOperand();
1784     ConstantRange CR = getSignedRange(X);
1785     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1786     unsigned NewBits = getTypeSizeInBits(Ty);
1787     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1788             CR.sextOrTrunc(NewBits)))
1789       return getTruncateOrSignExtend(X, Ty);
1790   }
1791
1792   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1793   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1794     if (SA->getNumOperands() == 2) {
1795       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1796       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1797       if (SMul && SC1) {
1798         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1799           const APInt &C1 = SC1->getAPInt();
1800           const APInt &C2 = SC2->getAPInt();
1801           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1802               C2.ugt(C1) && C2.isPowerOf2())
1803             return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1804                               getSignExtendExprCached(SMul, Ty, Cache));
1805         }
1806       }
1807     }
1808
1809     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1810     if (SA->hasNoSignedWrap()) {
1811       // If the addition does not sign overflow then we can, by definition,
1812       // commute the sign extension with the addition operation.
1813       SmallVector<const SCEV *, 4> Ops;
1814       for (const auto *Op : SA->operands())
1815         Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
1816       return getAddExpr(Ops, SCEV::FlagNSW);
1817     }
1818   }
1819   // If the input value is a chrec scev, and we can prove that the value
1820   // did not overflow the old, smaller, value, we can sign extend all of the
1821   // operands (often constants).  This allows analysis of something like
1822   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1823   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1824     if (AR->isAffine()) {
1825       const SCEV *Start = AR->getStart();
1826       const SCEV *Step = AR->getStepRecurrence(*this);
1827       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1828       const Loop *L = AR->getLoop();
1829
1830       if (!AR->hasNoSignedWrap()) {
1831         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1832         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1833       }
1834
1835       // If we have special knowledge that this addrec won't overflow,
1836       // we don't need to do any further analysis.
1837       if (AR->hasNoSignedWrap())
1838         return getAddRecExpr(
1839             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1840             getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
1841
1842       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1843       // Note that this serves two purposes: It filters out loops that are
1844       // simply not analyzable, and it covers the case where this code is
1845       // being called from within backedge-taken count analysis, such that
1846       // attempting to ask for the backedge-taken count would likely result
1847       // in infinite recursion. In the later case, the analysis code will
1848       // cope with a conservative value, and it will take care to purge
1849       // that value once it has finished.
1850       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1851       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1852         // Manually compute the final value for AR, checking for
1853         // overflow.
1854
1855         // Check whether the backedge-taken count can be losslessly casted to
1856         // the addrec's type. The count is always unsigned.
1857         const SCEV *CastedMaxBECount =
1858           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1859         const SCEV *RecastedMaxBECount =
1860           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1861         if (MaxBECount == RecastedMaxBECount) {
1862           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1863           // Check whether Start+Step*MaxBECount has no signed overflow.
1864           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1865           const SCEV *SAdd =
1866               getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1867           const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
1868           const SCEV *WideMaxBECount =
1869               getZeroExtendExpr(CastedMaxBECount, WideTy);
1870           const SCEV *OperandExtendedAdd = getAddExpr(
1871               WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1872                                                         Step, WideTy, Cache)));
1873           if (SAdd == OperandExtendedAdd) {
1874             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1875             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1876             // Return the expression with the addrec on the outside.
1877             return getAddRecExpr(
1878                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1879                 getSignExtendExprCached(Step, Ty, Cache), L,
1880                 AR->getNoWrapFlags());
1881           }
1882           // Similar to above, only this time treat the step value as unsigned.
1883           // This covers loops that count up with an unsigned step.
1884           OperandExtendedAdd =
1885             getAddExpr(WideStart,
1886                        getMulExpr(WideMaxBECount,
1887                                   getZeroExtendExpr(Step, WideTy)));
1888           if (SAdd == OperandExtendedAdd) {
1889             // If AR wraps around then
1890             //
1891             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1892             // => SAdd != OperandExtendedAdd
1893             //
1894             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1895             // (SAdd == OperandExtendedAdd => AR is NW)
1896
1897             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1898
1899             // Return the expression with the addrec on the outside.
1900             return getAddRecExpr(
1901                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1902                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1903           }
1904         }
1905       }
1906
1907       // Normally, in the cases we can prove no-overflow via a
1908       // backedge guarding condition, we can also compute a backedge
1909       // taken count for the loop.  The exceptions are assumptions and
1910       // guards present in the loop -- SCEV is not great at exploiting
1911       // these to compute max backedge taken counts, but can still use
1912       // these to prove lack of overflow.  Use this fact to avoid
1913       // doing extra work that may not pay off.
1914
1915       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1916           !AC.assumptions().empty()) {
1917         // If the backedge is guarded by a comparison with the pre-inc
1918         // value the addrec is safe. Also, if the entry is guarded by
1919         // a comparison with the start value and the backedge is
1920         // guarded by a comparison with the post-inc value, the addrec
1921         // is safe.
1922         ICmpInst::Predicate Pred;
1923         const SCEV *OverflowLimit =
1924             getSignedOverflowLimitForStep(Step, &Pred, this);
1925         if (OverflowLimit &&
1926             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1927              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1928               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1929                                           OverflowLimit)))) {
1930           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1931           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1932           return getAddRecExpr(
1933               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1934               getSignExtendExprCached(Step, Ty, Cache), L,
1935               AR->getNoWrapFlags());
1936         }
1937       }
1938
1939       // If Start and Step are constants, check if we can apply this
1940       // transformation:
1941       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1942       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1943       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1944       if (SC1 && SC2) {
1945         const APInt &C1 = SC1->getAPInt();
1946         const APInt &C2 = SC2->getAPInt();
1947         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1948             C2.isPowerOf2()) {
1949           Start = getSignExtendExprCached(Start, Ty, Cache);
1950           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1951                                             AR->getNoWrapFlags());
1952           return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
1953         }
1954       }
1955
1956       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1957         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1958         return getAddRecExpr(
1959             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1960             getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1961       }
1962     }
1963
1964   // If the input value is provably positive and we could not simplify
1965   // away the sext build a zext instead.
1966   if (isKnownNonNegative(Op))
1967     return getZeroExtendExpr(Op, Ty);
1968
1969   // The cast wasn't folded; create an explicit cast node.
1970   // Recompute the insert position, as it may have been invalidated.
1971   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1972   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1973                                                    Op, Ty);
1974   UniqueSCEVs.InsertNode(S, IP);
1975   return S;
1976 }
1977
1978 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1979 /// unspecified bits out to the given type.
1980 ///
1981 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1982                                               Type *Ty) {
1983   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1984          "This is not an extending conversion!");
1985   assert(isSCEVable(Ty) &&
1986          "This is not a conversion to a SCEVable type!");
1987   Ty = getEffectiveSCEVType(Ty);
1988
1989   // Sign-extend negative constants.
1990   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1991     if (SC->getAPInt().isNegative())
1992       return getSignExtendExpr(Op, Ty);
1993
1994   // Peel off a truncate cast.
1995   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1996     const SCEV *NewOp = T->getOperand();
1997     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1998       return getAnyExtendExpr(NewOp, Ty);
1999     return getTruncateOrNoop(NewOp, Ty);
2000   }
2001
2002   // Next try a zext cast. If the cast is folded, use it.
2003   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2004   if (!isa<SCEVZeroExtendExpr>(ZExt))
2005     return ZExt;
2006
2007   // Next try a sext cast. If the cast is folded, use it.
2008   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2009   if (!isa<SCEVSignExtendExpr>(SExt))
2010     return SExt;
2011
2012   // Force the cast to be folded into the operands of an addrec.
2013   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2014     SmallVector<const SCEV *, 4> Ops;
2015     for (const SCEV *Op : AR->operands())
2016       Ops.push_back(getAnyExtendExpr(Op, Ty));
2017     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2018   }
2019
2020   // If the expression is obviously signed, use the sext cast value.
2021   if (isa<SCEVSMaxExpr>(Op))
2022     return SExt;
2023
2024   // Absent any other information, use the zext cast value.
2025   return ZExt;
2026 }
2027
2028 /// Process the given Ops list, which is a list of operands to be added under
2029 /// the given scale, update the given map. This is a helper function for
2030 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2031 /// that would form an add expression like this:
2032 ///
2033 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2034 ///
2035 /// where A and B are constants, update the map with these values:
2036 ///
2037 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2038 ///
2039 /// and add 13 + A*B*29 to AccumulatedConstant.
2040 /// This will allow getAddRecExpr to produce this:
2041 ///
2042 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2043 ///
2044 /// This form often exposes folding opportunities that are hidden in
2045 /// the original operand list.
2046 ///
2047 /// Return true iff it appears that any interesting folding opportunities
2048 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2049 /// the common case where no interesting opportunities are present, and
2050 /// is also used as a check to avoid infinite recursion.
2051 ///
2052 static bool
2053 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2054                              SmallVectorImpl<const SCEV *> &NewOps,
2055                              APInt &AccumulatedConstant,
2056                              const SCEV *const *Ops, size_t NumOperands,
2057                              const APInt &Scale,
2058                              ScalarEvolution &SE) {
2059   bool Interesting = false;
2060
2061   // Iterate over the add operands. They are sorted, with constants first.
2062   unsigned i = 0;
2063   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2064     ++i;
2065     // Pull a buried constant out to the outside.
2066     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2067       Interesting = true;
2068     AccumulatedConstant += Scale * C->getAPInt();
2069   }
2070
2071   // Next comes everything else. We're especially interested in multiplies
2072   // here, but they're in the middle, so just visit the rest with one loop.
2073   for (; i != NumOperands; ++i) {
2074     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2075     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2076       APInt NewScale =
2077           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2078       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2079         // A multiplication of a constant with another add; recurse.
2080         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2081         Interesting |=
2082           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2083                                        Add->op_begin(), Add->getNumOperands(),
2084                                        NewScale, SE);
2085       } else {
2086         // A multiplication of a constant with some other value. Update
2087         // the map.
2088         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2089         const SCEV *Key = SE.getMulExpr(MulOps);
2090         auto Pair = M.insert({Key, NewScale});
2091         if (Pair.second) {
2092           NewOps.push_back(Pair.first->first);
2093         } else {
2094           Pair.first->second += NewScale;
2095           // The map already had an entry for this value, which may indicate
2096           // a folding opportunity.
2097           Interesting = true;
2098         }
2099       }
2100     } else {
2101       // An ordinary operand. Update the map.
2102       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2103           M.insert({Ops[i], Scale});
2104       if (Pair.second) {
2105         NewOps.push_back(Pair.first->first);
2106       } else {
2107         Pair.first->second += Scale;
2108         // The map already had an entry for this value, which may indicate
2109         // a folding opportunity.
2110         Interesting = true;
2111       }
2112     }
2113   }
2114
2115   return Interesting;
2116 }
2117
2118 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2119 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2120 // can't-overflow flags for the operation if possible.
2121 static SCEV::NoWrapFlags
2122 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2123                       const SmallVectorImpl<const SCEV *> &Ops,
2124                       SCEV::NoWrapFlags Flags) {
2125   using namespace std::placeholders;
2126   typedef OverflowingBinaryOperator OBO;
2127
2128   bool CanAnalyze =
2129       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2130   (void)CanAnalyze;
2131   assert(CanAnalyze && "don't call from other places!");
2132
2133   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2134   SCEV::NoWrapFlags SignOrUnsignWrap =
2135       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2136
2137   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2138   auto IsKnownNonNegative = [&](const SCEV *S) {
2139     return SE->isKnownNonNegative(S);
2140   };
2141
2142   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2143     Flags =
2144         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2145
2146   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2147
2148   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2149       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2150
2151     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2152     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2153
2154     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2155     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2156       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2157           Instruction::Add, C, OBO::NoSignedWrap);
2158       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2159         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2160     }
2161     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2162       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2163           Instruction::Add, C, OBO::NoUnsignedWrap);
2164       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2165         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2166     }
2167   }
2168
2169   return Flags;
2170 }
2171
2172 /// Get a canonical add expression, or something simpler if possible.
2173 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2174                                         SCEV::NoWrapFlags Flags,
2175                                         unsigned Depth) {
2176   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2177          "only nuw or nsw allowed");
2178   assert(!Ops.empty() && "Cannot get empty add!");
2179   if (Ops.size() == 1) return Ops[0];
2180 #ifndef NDEBUG
2181   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2182   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2183     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2184            "SCEVAddExpr operand types don't match!");
2185 #endif
2186
2187   // Sort by complexity, this groups all similar expression types together.
2188   GroupByComplexity(Ops, &LI);
2189
2190   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2191
2192   // If there are any constants, fold them together.
2193   unsigned Idx = 0;
2194   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2195     ++Idx;
2196     assert(Idx < Ops.size());
2197     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2198       // We found two constants, fold them together!
2199       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2200       if (Ops.size() == 2) return Ops[0];
2201       Ops.erase(Ops.begin()+1);  // Erase the folded element
2202       LHSC = cast<SCEVConstant>(Ops[0]);
2203     }
2204
2205     // If we are left with a constant zero being added, strip it off.
2206     if (LHSC->getValue()->isZero()) {
2207       Ops.erase(Ops.begin());
2208       --Idx;
2209     }
2210
2211     if (Ops.size() == 1) return Ops[0];
2212   }
2213
2214   // Limit recursion calls depth
2215   if (Depth > MaxAddExprDepth)
2216     return getOrCreateAddExpr(Ops, Flags);
2217
2218   // Okay, check to see if the same value occurs in the operand list more than
2219   // once.  If so, merge them together into an multiply expression.  Since we
2220   // sorted the list, these values are required to be adjacent.
2221   Type *Ty = Ops[0]->getType();
2222   bool FoundMatch = false;
2223   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2224     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2225       // Scan ahead to count how many equal operands there are.
2226       unsigned Count = 2;
2227       while (i+Count != e && Ops[i+Count] == Ops[i])
2228         ++Count;
2229       // Merge the values into a multiply.
2230       const SCEV *Scale = getConstant(Ty, Count);
2231       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2232       if (Ops.size() == Count)
2233         return Mul;
2234       Ops[i] = Mul;
2235       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2236       --i; e -= Count - 1;
2237       FoundMatch = true;
2238     }
2239   if (FoundMatch)
2240     return getAddExpr(Ops, Flags);
2241
2242   // Check for truncates. If all the operands are truncated from the same
2243   // type, see if factoring out the truncate would permit the result to be
2244   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2245   // if the contents of the resulting outer trunc fold to something simple.
2246   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2247     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2248     Type *DstType = Trunc->getType();
2249     Type *SrcType = Trunc->getOperand()->getType();
2250     SmallVector<const SCEV *, 8> LargeOps;
2251     bool Ok = true;
2252     // Check all the operands to see if they can be represented in the
2253     // source type of the truncate.
2254     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2255       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2256         if (T->getOperand()->getType() != SrcType) {
2257           Ok = false;
2258           break;
2259         }
2260         LargeOps.push_back(T->getOperand());
2261       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2262         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2263       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2264         SmallVector<const SCEV *, 8> LargeMulOps;
2265         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2266           if (const SCEVTruncateExpr *T =
2267                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2268             if (T->getOperand()->getType() != SrcType) {
2269               Ok = false;
2270               break;
2271             }
2272             LargeMulOps.push_back(T->getOperand());
2273           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2274             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2275           } else {
2276             Ok = false;
2277             break;
2278           }
2279         }
2280         if (Ok)
2281           LargeOps.push_back(getMulExpr(LargeMulOps));
2282       } else {
2283         Ok = false;
2284         break;
2285       }
2286     }
2287     if (Ok) {
2288       // Evaluate the expression in the larger type.
2289       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2290       // If it folds to something simple, use it. Otherwise, don't.
2291       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2292         return getTruncateExpr(Fold, DstType);
2293     }
2294   }
2295
2296   // Skip past any other cast SCEVs.
2297   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2298     ++Idx;
2299
2300   // If there are add operands they would be next.
2301   if (Idx < Ops.size()) {
2302     bool DeletedAdd = false;
2303     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2304       if (Ops.size() > AddOpsInlineThreshold ||
2305           Add->getNumOperands() > AddOpsInlineThreshold)
2306         break;
2307       // If we have an add, expand the add operands onto the end of the operands
2308       // list.
2309       Ops.erase(Ops.begin()+Idx);
2310       Ops.append(Add->op_begin(), Add->op_end());
2311       DeletedAdd = true;
2312     }
2313
2314     // If we deleted at least one add, we added operands to the end of the list,
2315     // and they are not necessarily sorted.  Recurse to resort and resimplify
2316     // any operands we just acquired.
2317     if (DeletedAdd)
2318       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2319   }
2320
2321   // Skip over the add expression until we get to a multiply.
2322   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2323     ++Idx;
2324
2325   // Check to see if there are any folding opportunities present with
2326   // operands multiplied by constant values.
2327   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2328     uint64_t BitWidth = getTypeSizeInBits(Ty);
2329     DenseMap<const SCEV *, APInt> M;
2330     SmallVector<const SCEV *, 8> NewOps;
2331     APInt AccumulatedConstant(BitWidth, 0);
2332     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2333                                      Ops.data(), Ops.size(),
2334                                      APInt(BitWidth, 1), *this)) {
2335       struct APIntCompare {
2336         bool operator()(const APInt &LHS, const APInt &RHS) const {
2337           return LHS.ult(RHS);
2338         }
2339       };
2340
2341       // Some interesting folding opportunity is present, so its worthwhile to
2342       // re-generate the operands list. Group the operands by constant scale,
2343       // to avoid multiplying by the same constant scale multiple times.
2344       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2345       for (const SCEV *NewOp : NewOps)
2346         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2347       // Re-generate the operands list.
2348       Ops.clear();
2349       if (AccumulatedConstant != 0)
2350         Ops.push_back(getConstant(AccumulatedConstant));
2351       for (auto &MulOp : MulOpLists)
2352         if (MulOp.first != 0)
2353           Ops.push_back(getMulExpr(
2354               getConstant(MulOp.first),
2355               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
2356       if (Ops.empty())
2357         return getZero(Ty);
2358       if (Ops.size() == 1)
2359         return Ops[0];
2360       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2361     }
2362   }
2363
2364   // If we are adding something to a multiply expression, make sure the
2365   // something is not already an operand of the multiply.  If so, merge it into
2366   // the multiply.
2367   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2368     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2369     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2370       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2371       if (isa<SCEVConstant>(MulOpSCEV))
2372         continue;
2373       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2374         if (MulOpSCEV == Ops[AddOp]) {
2375           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2376           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2377           if (Mul->getNumOperands() != 2) {
2378             // If the multiply has more than two operands, we must get the
2379             // Y*Z term.
2380             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2381                                                 Mul->op_begin()+MulOp);
2382             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2383             InnerMul = getMulExpr(MulOps);
2384           }
2385           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2386           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2387           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2388           if (Ops.size() == 2) return OuterMul;
2389           if (AddOp < Idx) {
2390             Ops.erase(Ops.begin()+AddOp);
2391             Ops.erase(Ops.begin()+Idx-1);
2392           } else {
2393             Ops.erase(Ops.begin()+Idx);
2394             Ops.erase(Ops.begin()+AddOp-1);
2395           }
2396           Ops.push_back(OuterMul);
2397           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2398         }
2399
2400       // Check this multiply against other multiplies being added together.
2401       for (unsigned OtherMulIdx = Idx+1;
2402            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2403            ++OtherMulIdx) {
2404         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2405         // If MulOp occurs in OtherMul, we can fold the two multiplies
2406         // together.
2407         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2408              OMulOp != e; ++OMulOp)
2409           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2410             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2411             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2412             if (Mul->getNumOperands() != 2) {
2413               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2414                                                   Mul->op_begin()+MulOp);
2415               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2416               InnerMul1 = getMulExpr(MulOps);
2417             }
2418             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2419             if (OtherMul->getNumOperands() != 2) {
2420               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2421                                                   OtherMul->op_begin()+OMulOp);
2422               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2423               InnerMul2 = getMulExpr(MulOps);
2424             }
2425             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2426             const SCEV *InnerMulSum =
2427                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2428             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2429             if (Ops.size() == 2) return OuterMul;
2430             Ops.erase(Ops.begin()+Idx);
2431             Ops.erase(Ops.begin()+OtherMulIdx-1);
2432             Ops.push_back(OuterMul);
2433             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2434           }
2435       }
2436     }
2437   }
2438
2439   // If there are any add recurrences in the operands list, see if any other
2440   // added values are loop invariant.  If so, we can fold them into the
2441   // recurrence.
2442   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2443     ++Idx;
2444
2445   // Scan over all recurrences, trying to fold loop invariants into them.
2446   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2447     // Scan all of the other operands to this add and add them to the vector if
2448     // they are loop invariant w.r.t. the recurrence.
2449     SmallVector<const SCEV *, 8> LIOps;
2450     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2451     const Loop *AddRecLoop = AddRec->getLoop();
2452     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2453       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2454         LIOps.push_back(Ops[i]);
2455         Ops.erase(Ops.begin()+i);
2456         --i; --e;
2457       }
2458
2459     // If we found some loop invariants, fold them into the recurrence.
2460     if (!LIOps.empty()) {
2461       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2462       LIOps.push_back(AddRec->getStart());
2463
2464       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2465                                              AddRec->op_end());
2466       // This follows from the fact that the no-wrap flags on the outer add
2467       // expression are applicable on the 0th iteration, when the add recurrence
2468       // will be equal to its start value.
2469       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2470
2471       // Build the new addrec. Propagate the NUW and NSW flags if both the
2472       // outer add and the inner addrec are guaranteed to have no overflow.
2473       // Always propagate NW.
2474       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2475       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2476
2477       // If all of the other operands were loop invariant, we are done.
2478       if (Ops.size() == 1) return NewRec;
2479
2480       // Otherwise, add the folded AddRec by the non-invariant parts.
2481       for (unsigned i = 0;; ++i)
2482         if (Ops[i] == AddRec) {
2483           Ops[i] = NewRec;
2484           break;
2485         }
2486       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2487     }
2488
2489     // Okay, if there weren't any loop invariants to be folded, check to see if
2490     // there are multiple AddRec's with the same loop induction variable being
2491     // added together.  If so, we can fold them.
2492     for (unsigned OtherIdx = Idx+1;
2493          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2494          ++OtherIdx)
2495       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2496         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2497         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2498                                                AddRec->op_end());
2499         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2500              ++OtherIdx)
2501           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2502             if (OtherAddRec->getLoop() == AddRecLoop) {
2503               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2504                    i != e; ++i) {
2505                 if (i >= AddRecOps.size()) {
2506                   AddRecOps.append(OtherAddRec->op_begin()+i,
2507                                    OtherAddRec->op_end());
2508                   break;
2509                 }
2510                 SmallVector<const SCEV *, 2> TwoOps = {
2511                     AddRecOps[i], OtherAddRec->getOperand(i)};
2512                 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2513               }
2514               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2515             }
2516         // Step size has changed, so we cannot guarantee no self-wraparound.
2517         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2518         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2519       }
2520
2521     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2522     // next one.
2523   }
2524
2525   // Okay, it looks like we really DO need an add expr.  Check to see if we
2526   // already have one, otherwise create a new one.
2527   return getOrCreateAddExpr(Ops, Flags);
2528 }
2529
2530 const SCEV *
2531 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2532                                     SCEV::NoWrapFlags Flags) {
2533   FoldingSetNodeID ID;
2534   ID.AddInteger(scAddExpr);
2535   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2536     ID.AddPointer(Ops[i]);
2537   void *IP = nullptr;
2538   SCEVAddExpr *S =
2539       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2540   if (!S) {
2541     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2542     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2543     S = new (SCEVAllocator)
2544         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2545     UniqueSCEVs.InsertNode(S, IP);
2546   }
2547   S->setNoWrapFlags(Flags);
2548   return S;
2549 }
2550
2551 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2552   uint64_t k = i*j;
2553   if (j > 1 && k / j != i) Overflow = true;
2554   return k;
2555 }
2556
2557 /// Compute the result of "n choose k", the binomial coefficient.  If an
2558 /// intermediate computation overflows, Overflow will be set and the return will
2559 /// be garbage. Overflow is not cleared on absence of overflow.
2560 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2561   // We use the multiplicative formula:
2562   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2563   // At each iteration, we take the n-th term of the numeral and divide by the
2564   // (k-n)th term of the denominator.  This division will always produce an
2565   // integral result, and helps reduce the chance of overflow in the
2566   // intermediate computations. However, we can still overflow even when the
2567   // final result would fit.
2568
2569   if (n == 0 || n == k) return 1;
2570   if (k > n) return 0;
2571
2572   if (k > n/2)
2573     k = n-k;
2574
2575   uint64_t r = 1;
2576   for (uint64_t i = 1; i <= k; ++i) {
2577     r = umul_ov(r, n-(i-1), Overflow);
2578     r /= i;
2579   }
2580   return r;
2581 }
2582
2583 /// Determine if any of the operands in this SCEV are a constant or if
2584 /// any of the add or multiply expressions in this SCEV contain a constant.
2585 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2586   SmallVector<const SCEV *, 4> Ops;
2587   Ops.push_back(StartExpr);
2588   while (!Ops.empty()) {
2589     const SCEV *CurrentExpr = Ops.pop_back_val();
2590     if (isa<SCEVConstant>(*CurrentExpr))
2591       return true;
2592
2593     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2594       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2595       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2596     }
2597   }
2598   return false;
2599 }
2600
2601 /// Get a canonical multiply expression, or something simpler if possible.
2602 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2603                                         SCEV::NoWrapFlags Flags) {
2604   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2605          "only nuw or nsw allowed");
2606   assert(!Ops.empty() && "Cannot get empty mul!");
2607   if (Ops.size() == 1) return Ops[0];
2608 #ifndef NDEBUG
2609   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2610   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2611     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2612            "SCEVMulExpr operand types don't match!");
2613 #endif
2614
2615   // Sort by complexity, this groups all similar expression types together.
2616   GroupByComplexity(Ops, &LI);
2617
2618   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2619
2620   // If there are any constants, fold them together.
2621   unsigned Idx = 0;
2622   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2623
2624     // C1*(C2+V) -> C1*C2 + C1*V
2625     if (Ops.size() == 2)
2626         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2627           // If any of Add's ops are Adds or Muls with a constant,
2628           // apply this transformation as well.
2629           if (Add->getNumOperands() == 2)
2630             if (containsConstantSomewhere(Add))
2631               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2632                                 getMulExpr(LHSC, Add->getOperand(1)));
2633
2634     ++Idx;
2635     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2636       // We found two constants, fold them together!
2637       ConstantInt *Fold =
2638           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2639       Ops[0] = getConstant(Fold);
2640       Ops.erase(Ops.begin()+1);  // Erase the folded element
2641       if (Ops.size() == 1) return Ops[0];
2642       LHSC = cast<SCEVConstant>(Ops[0]);
2643     }
2644
2645     // If we are left with a constant one being multiplied, strip it off.
2646     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2647       Ops.erase(Ops.begin());
2648       --Idx;
2649     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2650       // If we have a multiply of zero, it will always be zero.
2651       return Ops[0];
2652     } else if (Ops[0]->isAllOnesValue()) {
2653       // If we have a mul by -1 of an add, try distributing the -1 among the
2654       // add operands.
2655       if (Ops.size() == 2) {
2656         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2657           SmallVector<const SCEV *, 4> NewOps;
2658           bool AnyFolded = false;
2659           for (const SCEV *AddOp : Add->operands()) {
2660             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2661             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2662             NewOps.push_back(Mul);
2663           }
2664           if (AnyFolded)
2665             return getAddExpr(NewOps);
2666         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2667           // Negation preserves a recurrence's no self-wrap property.
2668           SmallVector<const SCEV *, 4> Operands;
2669           for (const SCEV *AddRecOp : AddRec->operands())
2670             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2671
2672           return getAddRecExpr(Operands, AddRec->getLoop(),
2673                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2674         }
2675       }
2676     }
2677
2678     if (Ops.size() == 1)
2679       return Ops[0];
2680   }
2681
2682   // Skip over the add expression until we get to a multiply.
2683   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2684     ++Idx;
2685
2686   // If there are mul operands inline them all into this expression.
2687   if (Idx < Ops.size()) {
2688     bool DeletedMul = false;
2689     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2690       if (Ops.size() > MulOpsInlineThreshold)
2691         break;
2692       // If we have an mul, expand the mul operands onto the end of the operands
2693       // list.
2694       Ops.erase(Ops.begin()+Idx);
2695       Ops.append(Mul->op_begin(), Mul->op_end());
2696       DeletedMul = true;
2697     }
2698
2699     // If we deleted at least one mul, we added operands to the end of the list,
2700     // and they are not necessarily sorted.  Recurse to resort and resimplify
2701     // any operands we just acquired.
2702     if (DeletedMul)
2703       return getMulExpr(Ops);
2704   }
2705
2706   // If there are any add recurrences in the operands list, see if any other
2707   // added values are loop invariant.  If so, we can fold them into the
2708   // recurrence.
2709   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2710     ++Idx;
2711
2712   // Scan over all recurrences, trying to fold loop invariants into them.
2713   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2714     // Scan all of the other operands to this mul and add them to the vector if
2715     // they are loop invariant w.r.t. the recurrence.
2716     SmallVector<const SCEV *, 8> LIOps;
2717     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2718     const Loop *AddRecLoop = AddRec->getLoop();
2719     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2720       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2721         LIOps.push_back(Ops[i]);
2722         Ops.erase(Ops.begin()+i);
2723         --i; --e;
2724       }
2725
2726     // If we found some loop invariants, fold them into the recurrence.
2727     if (!LIOps.empty()) {
2728       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2729       SmallVector<const SCEV *, 4> NewOps;
2730       NewOps.reserve(AddRec->getNumOperands());
2731       const SCEV *Scale = getMulExpr(LIOps);
2732       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2733         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2734
2735       // Build the new addrec. Propagate the NUW and NSW flags if both the
2736       // outer mul and the inner addrec are guaranteed to have no overflow.
2737       //
2738       // No self-wrap cannot be guaranteed after changing the step size, but
2739       // will be inferred if either NUW or NSW is true.
2740       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2741       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2742
2743       // If all of the other operands were loop invariant, we are done.
2744       if (Ops.size() == 1) return NewRec;
2745
2746       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2747       for (unsigned i = 0;; ++i)
2748         if (Ops[i] == AddRec) {
2749           Ops[i] = NewRec;
2750           break;
2751         }
2752       return getMulExpr(Ops);
2753     }
2754
2755     // Okay, if there weren't any loop invariants to be folded, check to see if
2756     // there are multiple AddRec's with the same loop induction variable being
2757     // multiplied together.  If so, we can fold them.
2758
2759     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2760     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2761     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2762     //   ]]],+,...up to x=2n}.
2763     // Note that the arguments to choose() are always integers with values
2764     // known at compile time, never SCEV objects.
2765     //
2766     // The implementation avoids pointless extra computations when the two
2767     // addrec's are of different length (mathematically, it's equivalent to
2768     // an infinite stream of zeros on the right).
2769     bool OpsModified = false;
2770     for (unsigned OtherIdx = Idx+1;
2771          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2772          ++OtherIdx) {
2773       const SCEVAddRecExpr *OtherAddRec =
2774         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2775       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2776         continue;
2777
2778       bool Overflow = false;
2779       Type *Ty = AddRec->getType();
2780       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2781       SmallVector<const SCEV*, 7> AddRecOps;
2782       for (int x = 0, xe = AddRec->getNumOperands() +
2783              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2784         const SCEV *Term = getZero(Ty);
2785         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2786           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2787           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2788                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2789                z < ze && !Overflow; ++z) {
2790             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2791             uint64_t Coeff;
2792             if (LargerThan64Bits)
2793               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2794             else
2795               Coeff = Coeff1*Coeff2;
2796             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2797             const SCEV *Term1 = AddRec->getOperand(y-z);
2798             const SCEV *Term2 = OtherAddRec->getOperand(z);
2799             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2800           }
2801         }
2802         AddRecOps.push_back(Term);
2803       }
2804       if (!Overflow) {
2805         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2806                                               SCEV::FlagAnyWrap);
2807         if (Ops.size() == 2) return NewAddRec;
2808         Ops[Idx] = NewAddRec;
2809         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2810         OpsModified = true;
2811         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2812         if (!AddRec)
2813           break;
2814       }
2815     }
2816     if (OpsModified)
2817       return getMulExpr(Ops);
2818
2819     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2820     // next one.
2821   }
2822
2823   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2824   // already have one, otherwise create a new one.
2825   FoldingSetNodeID ID;
2826   ID.AddInteger(scMulExpr);
2827   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2828     ID.AddPointer(Ops[i]);
2829   void *IP = nullptr;
2830   SCEVMulExpr *S =
2831     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2832   if (!S) {
2833     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2834     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2835     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2836                                         O, Ops.size());
2837     UniqueSCEVs.InsertNode(S, IP);
2838   }
2839   S->setNoWrapFlags(Flags);
2840   return S;
2841 }
2842
2843 /// Get a canonical unsigned division expression, or something simpler if
2844 /// possible.
2845 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2846                                          const SCEV *RHS) {
2847   assert(getEffectiveSCEVType(LHS->getType()) ==
2848          getEffectiveSCEVType(RHS->getType()) &&
2849          "SCEVUDivExpr operand types don't match!");
2850
2851   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2852     if (RHSC->getValue()->equalsInt(1))
2853       return LHS;                               // X udiv 1 --> x
2854     // If the denominator is zero, the result of the udiv is undefined. Don't
2855     // try to analyze it, because the resolution chosen here may differ from
2856     // the resolution chosen in other parts of the compiler.
2857     if (!RHSC->getValue()->isZero()) {
2858       // Determine if the division can be folded into the operands of
2859       // its operands.
2860       // TODO: Generalize this to non-constants by using known-bits information.
2861       Type *Ty = LHS->getType();
2862       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2863       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2864       // For non-power-of-two values, effectively round the value up to the
2865       // nearest power of two.
2866       if (!RHSC->getAPInt().isPowerOf2())
2867         ++MaxShiftAmt;
2868       IntegerType *ExtTy =
2869         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2870       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2871         if (const SCEVConstant *Step =
2872             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2873           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2874           const APInt &StepInt = Step->getAPInt();
2875           const APInt &DivInt = RHSC->getAPInt();
2876           if (!StepInt.urem(DivInt) &&
2877               getZeroExtendExpr(AR, ExtTy) ==
2878               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2879                             getZeroExtendExpr(Step, ExtTy),
2880                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2881             SmallVector<const SCEV *, 4> Operands;
2882             for (const SCEV *Op : AR->operands())
2883               Operands.push_back(getUDivExpr(Op, RHS));
2884             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2885           }
2886           /// Get a canonical UDivExpr for a recurrence.
2887           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2888           // We can currently only fold X%N if X is constant.
2889           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2890           if (StartC && !DivInt.urem(StepInt) &&
2891               getZeroExtendExpr(AR, ExtTy) ==
2892               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2893                             getZeroExtendExpr(Step, ExtTy),
2894                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2895             const APInt &StartInt = StartC->getAPInt();
2896             const APInt &StartRem = StartInt.urem(StepInt);
2897             if (StartRem != 0)
2898               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2899                                   AR->getLoop(), SCEV::FlagNW);
2900           }
2901         }
2902       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2903       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2904         SmallVector<const SCEV *, 4> Operands;
2905         for (const SCEV *Op : M->operands())
2906           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2907         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2908           // Find an operand that's safely divisible.
2909           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2910             const SCEV *Op = M->getOperand(i);
2911             const SCEV *Div = getUDivExpr(Op, RHSC);
2912             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2913               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2914                                                       M->op_end());
2915               Operands[i] = Div;
2916               return getMulExpr(Operands);
2917             }
2918           }
2919       }
2920       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2921       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2922         SmallVector<const SCEV *, 4> Operands;
2923         for (const SCEV *Op : A->operands())
2924           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2925         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2926           Operands.clear();
2927           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2928             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2929             if (isa<SCEVUDivExpr>(Op) ||
2930                 getMulExpr(Op, RHS) != A->getOperand(i))
2931               break;
2932             Operands.push_back(Op);
2933           }
2934           if (Operands.size() == A->getNumOperands())
2935             return getAddExpr(Operands);
2936         }
2937       }
2938
2939       // Fold if both operands are constant.
2940       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2941         Constant *LHSCV = LHSC->getValue();
2942         Constant *RHSCV = RHSC->getValue();
2943         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2944                                                                    RHSCV)));
2945       }
2946     }
2947   }
2948
2949   FoldingSetNodeID ID;
2950   ID.AddInteger(scUDivExpr);
2951   ID.AddPointer(LHS);
2952   ID.AddPointer(RHS);
2953   void *IP = nullptr;
2954   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2955   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2956                                              LHS, RHS);
2957   UniqueSCEVs.InsertNode(S, IP);
2958   return S;
2959 }
2960
2961 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2962   APInt A = C1->getAPInt().abs();
2963   APInt B = C2->getAPInt().abs();
2964   uint32_t ABW = A.getBitWidth();
2965   uint32_t BBW = B.getBitWidth();
2966
2967   if (ABW > BBW)
2968     B = B.zext(ABW);
2969   else if (ABW < BBW)
2970     A = A.zext(BBW);
2971
2972   return APIntOps::GreatestCommonDivisor(A, B);
2973 }
2974
2975 /// Get a canonical unsigned division expression, or something simpler if
2976 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2977 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2978 /// it's not exact because the udiv may be clearing bits.
2979 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2980                                               const SCEV *RHS) {
2981   // TODO: we could try to find factors in all sorts of things, but for now we
2982   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2983   // end of this file for inspiration.
2984
2985   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2986   if (!Mul || !Mul->hasNoUnsignedWrap())
2987     return getUDivExpr(LHS, RHS);
2988
2989   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2990     // If the mulexpr multiplies by a constant, then that constant must be the
2991     // first element of the mulexpr.
2992     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2993       if (LHSCst == RHSCst) {
2994         SmallVector<const SCEV *, 2> Operands;
2995         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2996         return getMulExpr(Operands);
2997       }
2998
2999       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3000       // that there's a factor provided by one of the other terms. We need to
3001       // check.
3002       APInt Factor = gcd(LHSCst, RHSCst);
3003       if (!Factor.isIntN(1)) {
3004         LHSCst =
3005             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3006         RHSCst =
3007             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3008         SmallVector<const SCEV *, 2> Operands;
3009         Operands.push_back(LHSCst);
3010         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3011         LHS = getMulExpr(Operands);
3012         RHS = RHSCst;
3013         Mul = dyn_cast<SCEVMulExpr>(LHS);
3014         if (!Mul)
3015           return getUDivExactExpr(LHS, RHS);
3016       }
3017     }
3018   }
3019
3020   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3021     if (Mul->getOperand(i) == RHS) {
3022       SmallVector<const SCEV *, 2> Operands;
3023       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3024       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3025       return getMulExpr(Operands);
3026     }
3027   }
3028
3029   return getUDivExpr(LHS, RHS);
3030 }
3031
3032 /// Get an add recurrence expression for the specified loop.  Simplify the
3033 /// expression as much as possible.
3034 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3035                                            const Loop *L,
3036                                            SCEV::NoWrapFlags Flags) {
3037   SmallVector<const SCEV *, 4> Operands;
3038   Operands.push_back(Start);
3039   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3040     if (StepChrec->getLoop() == L) {
3041       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3042       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3043     }
3044
3045   Operands.push_back(Step);
3046   return getAddRecExpr(Operands, L, Flags);
3047 }
3048
3049 /// Get an add recurrence expression for the specified loop.  Simplify the
3050 /// expression as much as possible.
3051 const SCEV *
3052 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3053                                const Loop *L, SCEV::NoWrapFlags Flags) {
3054   if (Operands.size() == 1) return Operands[0];
3055 #ifndef NDEBUG
3056   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3057   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3058     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3059            "SCEVAddRecExpr operand types don't match!");
3060   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3061     assert(isLoopInvariant(Operands[i], L) &&
3062            "SCEVAddRecExpr operand is not loop-invariant!");
3063 #endif
3064
3065   if (Operands.back()->isZero()) {
3066     Operands.pop_back();
3067     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3068   }
3069
3070   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3071   // use that information to infer NUW and NSW flags. However, computing a
3072   // BE count requires calling getAddRecExpr, so we may not yet have a
3073   // meaningful BE count at this point (and if we don't, we'd be stuck
3074   // with a SCEVCouldNotCompute as the cached BE count).
3075
3076   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3077
3078   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3079   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3080     const Loop *NestedLoop = NestedAR->getLoop();
3081     if (L->contains(NestedLoop)
3082             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3083             : (!NestedLoop->contains(L) &&
3084                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3085       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3086                                                   NestedAR->op_end());
3087       Operands[0] = NestedAR->getStart();
3088       // AddRecs require their operands be loop-invariant with respect to their
3089       // loops. Don't perform this transformation if it would break this
3090       // requirement.
3091       bool AllInvariant = all_of(
3092           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3093
3094       if (AllInvariant) {
3095         // Create a recurrence for the outer loop with the same step size.
3096         //
3097         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3098         // inner recurrence has the same property.
3099         SCEV::NoWrapFlags OuterFlags =
3100           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3101
3102         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3103         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3104           return isLoopInvariant(Op, NestedLoop);
3105         });
3106
3107         if (AllInvariant) {
3108           // Ok, both add recurrences are valid after the transformation.
3109           //
3110           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3111           // the outer recurrence has the same property.
3112           SCEV::NoWrapFlags InnerFlags =
3113             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3114           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3115         }
3116       }
3117       // Reset Operands to its original state.
3118       Operands[0] = NestedAR;
3119     }
3120   }
3121
3122   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3123   // already have one, otherwise create a new one.
3124   FoldingSetNodeID ID;
3125   ID.AddInteger(scAddRecExpr);
3126   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3127     ID.AddPointer(Operands[i]);
3128   ID.AddPointer(L);
3129   void *IP = nullptr;
3130   SCEVAddRecExpr *S =
3131     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3132   if (!S) {
3133     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3134     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3135     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3136                                            O, Operands.size(), L);
3137     UniqueSCEVs.InsertNode(S, IP);
3138   }
3139   S->setNoWrapFlags(Flags);
3140   return S;
3141 }
3142
3143 const SCEV *
3144 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3145                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3146   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3147   // getSCEV(Base)->getType() has the same address space as Base->getType()
3148   // because SCEV::getType() preserves the address space.
3149   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3150   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3151   // instruction to its SCEV, because the Instruction may be guarded by control
3152   // flow and the no-overflow bits may not be valid for the expression in any
3153   // context. This can be fixed similarly to how these flags are handled for
3154   // adds.
3155   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3156                                              : SCEV::FlagAnyWrap;
3157
3158   const SCEV *TotalOffset = getZero(IntPtrTy);
3159   // The array size is unimportant. The first thing we do on CurTy is getting
3160   // its element type.
3161   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3162   for (const SCEV *IndexExpr : IndexExprs) {
3163     // Compute the (potentially symbolic) offset in bytes for this index.
3164     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3165       // For a struct, add the member offset.
3166       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3167       unsigned FieldNo = Index->getZExtValue();
3168       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3169
3170       // Add the field offset to the running total offset.
3171       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3172
3173       // Update CurTy to the type of the field at Index.
3174       CurTy = STy->getTypeAtIndex(Index);
3175     } else {
3176       // Update CurTy to its element type.
3177       CurTy = cast<SequentialType>(CurTy)->getElementType();
3178       // For an array, add the element offset, explicitly scaled.
3179       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3180       // Getelementptr indices are signed.
3181       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3182
3183       // Multiply the index by the element size to compute the element offset.
3184       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3185
3186       // Add the element offset to the running total offset.
3187       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3188     }
3189   }
3190
3191   // Add the total offset from all the GEP indices to the base.
3192   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3193 }
3194
3195 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3196                                          const SCEV *RHS) {
3197   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3198   return getSMaxExpr(Ops);
3199 }
3200
3201 const SCEV *
3202 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3203   assert(!Ops.empty() && "Cannot get empty smax!");
3204   if (Ops.size() == 1) return Ops[0];
3205 #ifndef NDEBUG
3206   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3207   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3208     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3209            "SCEVSMaxExpr operand types don't match!");
3210 #endif
3211
3212   // Sort by complexity, this groups all similar expression types together.
3213   GroupByComplexity(Ops, &LI);
3214
3215   // If there are any constants, fold them together.
3216   unsigned Idx = 0;
3217   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3218     ++Idx;
3219     assert(Idx < Ops.size());
3220     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3221       // We found two constants, fold them together!
3222       ConstantInt *Fold = ConstantInt::get(
3223           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3224       Ops[0] = getConstant(Fold);
3225       Ops.erase(Ops.begin()+1);  // Erase the folded element
3226       if (Ops.size() == 1) return Ops[0];
3227       LHSC = cast<SCEVConstant>(Ops[0]);
3228     }
3229
3230     // If we are left with a constant minimum-int, strip it off.
3231     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3232       Ops.erase(Ops.begin());
3233       --Idx;
3234     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3235       // If we have an smax with a constant maximum-int, it will always be
3236       // maximum-int.
3237       return Ops[0];
3238     }
3239
3240     if (Ops.size() == 1) return Ops[0];
3241   }
3242
3243   // Find the first SMax
3244   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3245     ++Idx;
3246
3247   // Check to see if one of the operands is an SMax. If so, expand its operands
3248   // onto our operand list, and recurse to simplify.
3249   if (Idx < Ops.size()) {
3250     bool DeletedSMax = false;
3251     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3252       Ops.erase(Ops.begin()+Idx);
3253       Ops.append(SMax->op_begin(), SMax->op_end());
3254       DeletedSMax = true;
3255     }
3256
3257     if (DeletedSMax)
3258       return getSMaxExpr(Ops);
3259   }
3260
3261   // Okay, check to see if the same value occurs in the operand list twice.  If
3262   // so, delete one.  Since we sorted the list, these values are required to
3263   // be adjacent.
3264   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3265     //  X smax Y smax Y  -->  X smax Y
3266     //  X smax Y         -->  X, if X is always greater than Y
3267     if (Ops[i] == Ops[i+1] ||
3268         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3269       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3270       --i; --e;
3271     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3272       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3273       --i; --e;
3274     }
3275
3276   if (Ops.size() == 1) return Ops[0];
3277
3278   assert(!Ops.empty() && "Reduced smax down to nothing!");
3279
3280   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3281   // already have one, otherwise create a new one.
3282   FoldingSetNodeID ID;
3283   ID.AddInteger(scSMaxExpr);
3284   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3285     ID.AddPointer(Ops[i]);
3286   void *IP = nullptr;
3287   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3288   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3289   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3290   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3291                                              O, Ops.size());
3292   UniqueSCEVs.InsertNode(S, IP);
3293   return S;
3294 }
3295
3296 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3297                                          const SCEV *RHS) {
3298   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3299   return getUMaxExpr(Ops);
3300 }
3301
3302 const SCEV *
3303 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3304   assert(!Ops.empty() && "Cannot get empty umax!");
3305   if (Ops.size() == 1) return Ops[0];
3306 #ifndef NDEBUG
3307   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3308   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3309     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3310            "SCEVUMaxExpr operand types don't match!");
3311 #endif
3312
3313   // Sort by complexity, this groups all similar expression types together.
3314   GroupByComplexity(Ops, &LI);
3315
3316   // If there are any constants, fold them together.
3317   unsigned Idx = 0;
3318   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3319     ++Idx;
3320     assert(Idx < Ops.size());
3321     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3322       // We found two constants, fold them together!
3323       ConstantInt *Fold = ConstantInt::get(
3324           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3325       Ops[0] = getConstant(Fold);
3326       Ops.erase(Ops.begin()+1);  // Erase the folded element
3327       if (Ops.size() == 1) return Ops[0];
3328       LHSC = cast<SCEVConstant>(Ops[0]);
3329     }
3330
3331     // If we are left with a constant minimum-int, strip it off.
3332     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3333       Ops.erase(Ops.begin());
3334       --Idx;
3335     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3336       // If we have an umax with a constant maximum-int, it will always be
3337       // maximum-int.
3338       return Ops[0];
3339     }
3340
3341     if (Ops.size() == 1) return Ops[0];
3342   }
3343
3344   // Find the first UMax
3345   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3346     ++Idx;
3347
3348   // Check to see if one of the operands is a UMax. If so, expand its operands
3349   // onto our operand list, and recurse to simplify.
3350   if (Idx < Ops.size()) {
3351     bool DeletedUMax = false;
3352     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3353       Ops.erase(Ops.begin()+Idx);
3354       Ops.append(UMax->op_begin(), UMax->op_end());
3355       DeletedUMax = true;
3356     }
3357
3358     if (DeletedUMax)
3359       return getUMaxExpr(Ops);
3360   }
3361
3362   // Okay, check to see if the same value occurs in the operand list twice.  If
3363   // so, delete one.  Since we sorted the list, these values are required to
3364   // be adjacent.
3365   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3366     //  X umax Y umax Y  -->  X umax Y
3367     //  X umax Y         -->  X, if X is always greater than Y
3368     if (Ops[i] == Ops[i+1] ||
3369         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3370       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3371       --i; --e;
3372     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3373       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3374       --i; --e;
3375     }
3376
3377   if (Ops.size() == 1) return Ops[0];
3378
3379   assert(!Ops.empty() && "Reduced umax down to nothing!");
3380
3381   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3382   // already have one, otherwise create a new one.
3383   FoldingSetNodeID ID;
3384   ID.AddInteger(scUMaxExpr);
3385   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3386     ID.AddPointer(Ops[i]);
3387   void *IP = nullptr;
3388   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3389   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3390   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3391   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3392                                              O, Ops.size());
3393   UniqueSCEVs.InsertNode(S, IP);
3394   return S;
3395 }
3396
3397 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3398                                          const SCEV *RHS) {
3399   // ~smax(~x, ~y) == smin(x, y).
3400   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3401 }
3402
3403 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3404                                          const SCEV *RHS) {
3405   // ~umax(~x, ~y) == umin(x, y)
3406   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3407 }
3408
3409 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3410   // We can bypass creating a target-independent
3411   // constant expression and then folding it back into a ConstantInt.
3412   // This is just a compile-time optimization.
3413   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3414 }
3415
3416 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3417                                              StructType *STy,
3418                                              unsigned FieldNo) {
3419   // We can bypass creating a target-independent
3420   // constant expression and then folding it back into a ConstantInt.
3421   // This is just a compile-time optimization.
3422   return getConstant(
3423       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3424 }
3425
3426 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3427   // Don't attempt to do anything other than create a SCEVUnknown object
3428   // here.  createSCEV only calls getUnknown after checking for all other
3429   // interesting possibilities, and any other code that calls getUnknown
3430   // is doing so in order to hide a value from SCEV canonicalization.
3431
3432   FoldingSetNodeID ID;
3433   ID.AddInteger(scUnknown);
3434   ID.AddPointer(V);
3435   void *IP = nullptr;
3436   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3437     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3438            "Stale SCEVUnknown in uniquing map!");
3439     return S;
3440   }
3441   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3442                                             FirstUnknown);
3443   FirstUnknown = cast<SCEVUnknown>(S);
3444   UniqueSCEVs.InsertNode(S, IP);
3445   return S;
3446 }
3447
3448 //===----------------------------------------------------------------------===//
3449 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3450 //
3451
3452 /// Test if values of the given type are analyzable within the SCEV
3453 /// framework. This primarily includes integer types, and it can optionally
3454 /// include pointer types if the ScalarEvolution class has access to
3455 /// target-specific information.
3456 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3457   // Integers and pointers are always SCEVable.
3458   return Ty->isIntegerTy() || Ty->isPointerTy();
3459 }
3460
3461 /// Return the size in bits of the specified type, for which isSCEVable must
3462 /// return true.
3463 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3464   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3465   return getDataLayout().getTypeSizeInBits(Ty);
3466 }
3467
3468 /// Return a type with the same bitwidth as the given type and which represents
3469 /// how SCEV will treat the given type, for which isSCEVable must return
3470 /// true. For pointer types, this is the pointer-sized integer type.
3471 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3472   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3473
3474   if (Ty->isIntegerTy())
3475     return Ty;
3476
3477   // The only other support type is pointer.
3478   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3479   return getDataLayout().getIntPtrType(Ty);
3480 }
3481
3482 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3483   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3484 }
3485
3486 const SCEV *ScalarEvolution::getCouldNotCompute() {
3487   return CouldNotCompute.get();
3488 }
3489
3490 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3491   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3492     auto *SU = dyn_cast<SCEVUnknown>(S);
3493     return SU && SU->getValue() == nullptr;
3494   });
3495
3496   return !ContainsNulls;
3497 }
3498
3499 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3500   HasRecMapType::iterator I = HasRecMap.find(S);
3501   if (I != HasRecMap.end())
3502     return I->second;
3503
3504   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3505   HasRecMap.insert({S, FoundAddRec});
3506   return FoundAddRec;
3507 }
3508
3509 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3510 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3511 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3512 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3513   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3514   if (!Add)
3515     return {S, nullptr};
3516
3517   if (Add->getNumOperands() != 2)
3518     return {S, nullptr};
3519
3520   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3521   if (!ConstOp)
3522     return {S, nullptr};
3523
3524   return {Add->getOperand(1), ConstOp->getValue()};
3525 }
3526
3527 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3528 /// by the value and offset from any ValueOffsetPair in the set.
3529 SetVector<ScalarEvolution::ValueOffsetPair> *
3530 ScalarEvolution::getSCEVValues(const SCEV *S) {
3531   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3532   if (SI == ExprValueMap.end())
3533     return nullptr;
3534 #ifndef NDEBUG
3535   if (VerifySCEVMap) {
3536     // Check there is no dangling Value in the set returned.
3537     for (const auto &VE : SI->second)
3538       assert(ValueExprMap.count(VE.first));
3539   }
3540 #endif
3541   return &SI->second;
3542 }
3543
3544 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3545 /// cannot be used separately. eraseValueFromMap should be used to remove
3546 /// V from ValueExprMap and ExprValueMap at the same time.
3547 void ScalarEvolution::eraseValueFromMap(Value *V) {
3548   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3549   if (I != ValueExprMap.end()) {
3550     const SCEV *S = I->second;
3551     // Remove {V, 0} from the set of ExprValueMap[S]
3552     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3553       SV->remove({V, nullptr});
3554
3555     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3556     const SCEV *Stripped;
3557     ConstantInt *Offset;
3558     std::tie(Stripped, Offset) = splitAddExpr(S);
3559     if (Offset != nullptr) {
3560       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3561         SV->remove({V, Offset});
3562     }
3563     ValueExprMap.erase(V);
3564   }
3565 }
3566
3567 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3568 /// create a new one.
3569 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3570   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3571
3572   const SCEV *S = getExistingSCEV(V);
3573   if (S == nullptr) {
3574     S = createSCEV(V);
3575     // During PHI resolution, it is possible to create two SCEVs for the same
3576     // V, so it is needed to double check whether V->S is inserted into
3577     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3578     std::pair<ValueExprMapType::iterator, bool> Pair =
3579         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3580     if (Pair.second) {
3581       ExprValueMap[S].insert({V, nullptr});
3582
3583       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3584       // ExprValueMap.
3585       const SCEV *Stripped = S;
3586       ConstantInt *Offset = nullptr;
3587       std::tie(Stripped, Offset) = splitAddExpr(S);
3588       // If stripped is SCEVUnknown, don't bother to save
3589       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3590       // increase the complexity of the expansion code.
3591       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3592       // because it may generate add/sub instead of GEP in SCEV expansion.
3593       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3594           !isa<GetElementPtrInst>(V))
3595         ExprValueMap[Stripped].insert({V, Offset});
3596     }
3597   }
3598   return S;
3599 }
3600
3601 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3602   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3603
3604   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3605   if (I != ValueExprMap.end()) {
3606     const SCEV *S = I->second;
3607     if (checkValidity(S))
3608       return S;
3609     eraseValueFromMap(V);
3610     forgetMemoizedResults(S);
3611   }
3612   return nullptr;
3613 }
3614
3615 /// Return a SCEV corresponding to -V = -1*V
3616 ///
3617 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3618                                              SCEV::NoWrapFlags Flags) {
3619   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3620     return getConstant(
3621                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3622
3623   Type *Ty = V->getType();
3624   Ty = getEffectiveSCEVType(Ty);
3625   return getMulExpr(
3626       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3627 }
3628
3629 /// Return a SCEV corresponding to ~V = -1-V
3630 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3631   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3632     return getConstant(
3633                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3634
3635   Type *Ty = V->getType();
3636   Ty = getEffectiveSCEVType(Ty);
3637   const SCEV *AllOnes =
3638                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3639   return getMinusSCEV(AllOnes, V);
3640 }
3641
3642 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3643                                           SCEV::NoWrapFlags Flags) {
3644   // Fast path: X - X --> 0.
3645   if (LHS == RHS)
3646     return getZero(LHS->getType());
3647
3648   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3649   // makes it so that we cannot make much use of NUW.
3650   auto AddFlags = SCEV::FlagAnyWrap;
3651   const bool RHSIsNotMinSigned =
3652       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3653   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3654     // Let M be the minimum representable signed value. Then (-1)*RHS
3655     // signed-wraps if and only if RHS is M. That can happen even for
3656     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3657     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3658     // (-1)*RHS, we need to prove that RHS != M.
3659     //
3660     // If LHS is non-negative and we know that LHS - RHS does not
3661     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3662     // either by proving that RHS > M or that LHS >= 0.
3663     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3664       AddFlags = SCEV::FlagNSW;
3665     }
3666   }
3667
3668   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3669   // RHS is NSW and LHS >= 0.
3670   //
3671   // The difficulty here is that the NSW flag may have been proven
3672   // relative to a loop that is to be found in a recurrence in LHS and
3673   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3674   // larger scope than intended.
3675   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3676
3677   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3678 }
3679
3680 const SCEV *
3681 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3682   Type *SrcTy = V->getType();
3683   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3684          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3685          "Cannot truncate or zero extend with non-integer arguments!");
3686   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3687     return V;  // No conversion
3688   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3689     return getTruncateExpr(V, Ty);
3690   return getZeroExtendExpr(V, Ty);
3691 }
3692
3693 const SCEV *
3694 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3695                                          Type *Ty) {
3696   Type *SrcTy = V->getType();
3697   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3698          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3699          "Cannot truncate or zero extend with non-integer arguments!");
3700   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3701     return V;  // No conversion
3702   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3703     return getTruncateExpr(V, Ty);
3704   return getSignExtendExpr(V, Ty);
3705 }
3706
3707 const SCEV *
3708 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3709   Type *SrcTy = V->getType();
3710   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3711          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3712          "Cannot noop or zero extend with non-integer arguments!");
3713   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3714          "getNoopOrZeroExtend cannot truncate!");
3715   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3716     return V;  // No conversion
3717   return getZeroExtendExpr(V, Ty);
3718 }
3719
3720 const SCEV *
3721 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3722   Type *SrcTy = V->getType();
3723   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3724          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3725          "Cannot noop or sign extend with non-integer arguments!");
3726   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3727          "getNoopOrSignExtend cannot truncate!");
3728   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3729     return V;  // No conversion
3730   return getSignExtendExpr(V, Ty);
3731 }
3732
3733 const SCEV *
3734 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3735   Type *SrcTy = V->getType();
3736   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3737          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3738          "Cannot noop or any extend with non-integer arguments!");
3739   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3740          "getNoopOrAnyExtend cannot truncate!");
3741   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3742     return V;  // No conversion
3743   return getAnyExtendExpr(V, Ty);
3744 }
3745
3746 const SCEV *
3747 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3748   Type *SrcTy = V->getType();
3749   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3750          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3751          "Cannot truncate or noop with non-integer arguments!");
3752   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3753          "getTruncateOrNoop cannot extend!");
3754   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3755     return V;  // No conversion
3756   return getTruncateExpr(V, Ty);
3757 }
3758
3759 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3760                                                         const SCEV *RHS) {
3761   const SCEV *PromotedLHS = LHS;
3762   const SCEV *PromotedRHS = RHS;
3763
3764   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3765     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3766   else
3767     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3768
3769   return getUMaxExpr(PromotedLHS, PromotedRHS);
3770 }
3771
3772 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3773                                                         const SCEV *RHS) {
3774   const SCEV *PromotedLHS = LHS;
3775   const SCEV *PromotedRHS = RHS;
3776
3777   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3778     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3779   else
3780     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3781
3782   return getUMinExpr(PromotedLHS, PromotedRHS);
3783 }
3784
3785 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3786   // A pointer operand may evaluate to a nonpointer expression, such as null.
3787   if (!V->getType()->isPointerTy())
3788     return V;
3789
3790   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3791     return getPointerBase(Cast->getOperand());
3792   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3793     const SCEV *PtrOp = nullptr;
3794     for (const SCEV *NAryOp : NAry->operands()) {
3795       if (NAryOp->getType()->isPointerTy()) {
3796         // Cannot find the base of an expression with multiple pointer operands.
3797         if (PtrOp)
3798           return V;
3799         PtrOp = NAryOp;
3800       }
3801     }
3802     if (!PtrOp)
3803       return V;
3804     return getPointerBase(PtrOp);
3805   }
3806   return V;
3807 }
3808
3809 /// Push users of the given Instruction onto the given Worklist.
3810 static void
3811 PushDefUseChildren(Instruction *I,
3812                    SmallVectorImpl<Instruction *> &Worklist) {
3813   // Push the def-use children onto the Worklist stack.
3814   for (User *U : I->users())
3815     Worklist.push_back(cast<Instruction>(U));
3816 }
3817
3818 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3819   SmallVector<Instruction *, 16> Worklist;
3820   PushDefUseChildren(PN, Worklist);
3821
3822   SmallPtrSet<Instruction *, 8> Visited;
3823   Visited.insert(PN);
3824   while (!Worklist.empty()) {
3825     Instruction *I = Worklist.pop_back_val();
3826     if (!Visited.insert(I).second)
3827       continue;
3828
3829     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3830     if (It != ValueExprMap.end()) {
3831       const SCEV *Old = It->second;
3832
3833       // Short-circuit the def-use traversal if the symbolic name
3834       // ceases to appear in expressions.
3835       if (Old != SymName && !hasOperand(Old, SymName))
3836         continue;
3837
3838       // SCEVUnknown for a PHI either means that it has an unrecognized
3839       // structure, it's a PHI that's in the progress of being computed
3840       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3841       // additional loop trip count information isn't going to change anything.
3842       // In the second case, createNodeForPHI will perform the necessary
3843       // updates on its own when it gets to that point. In the third, we do
3844       // want to forget the SCEVUnknown.
3845       if (!isa<PHINode>(I) ||
3846           !isa<SCEVUnknown>(Old) ||
3847           (I != PN && Old == SymName)) {
3848         eraseValueFromMap(It->first);
3849         forgetMemoizedResults(Old);
3850       }
3851     }
3852
3853     PushDefUseChildren(I, Worklist);
3854   }
3855 }
3856
3857 namespace {
3858 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3859 public:
3860   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3861                              ScalarEvolution &SE) {
3862     SCEVInitRewriter Rewriter(L, SE);
3863     const SCEV *Result = Rewriter.visit(S);
3864     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3865   }
3866
3867   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3868       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3869
3870   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3871     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3872       Valid = false;
3873     return Expr;
3874   }
3875
3876   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3877     // Only allow AddRecExprs for this loop.
3878     if (Expr->getLoop() == L)
3879       return Expr->getStart();
3880     Valid = false;
3881     return Expr;
3882   }
3883
3884   bool isValid() { return Valid; }
3885
3886 private:
3887   const Loop *L;
3888   bool Valid;
3889 };
3890
3891 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3892 public:
3893   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3894                              ScalarEvolution &SE) {
3895     SCEVShiftRewriter Rewriter(L, SE);
3896     const SCEV *Result = Rewriter.visit(S);
3897     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3898   }
3899
3900   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3901       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3902
3903   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3904     // Only allow AddRecExprs for this loop.
3905     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3906       Valid = false;
3907     return Expr;
3908   }
3909
3910   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3911     if (Expr->getLoop() == L && Expr->isAffine())
3912       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3913     Valid = false;
3914     return Expr;
3915   }
3916   bool isValid() { return Valid; }
3917
3918 private:
3919   const Loop *L;
3920   bool Valid;
3921 };
3922 } // end anonymous namespace
3923
3924 SCEV::NoWrapFlags
3925 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3926   if (!AR->isAffine())
3927     return SCEV::FlagAnyWrap;
3928
3929   typedef OverflowingBinaryOperator OBO;
3930   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3931
3932   if (!AR->hasNoSignedWrap()) {
3933     ConstantRange AddRecRange = getSignedRange(AR);
3934     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3935
3936     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3937         Instruction::Add, IncRange, OBO::NoSignedWrap);
3938     if (NSWRegion.contains(AddRecRange))
3939       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3940   }
3941
3942   if (!AR->hasNoUnsignedWrap()) {
3943     ConstantRange AddRecRange = getUnsignedRange(AR);
3944     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3945
3946     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3947         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3948     if (NUWRegion.contains(AddRecRange))
3949       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3950   }
3951
3952   return Result;
3953 }
3954
3955 namespace {
3956 /// Represents an abstract binary operation.  This may exist as a
3957 /// normal instruction or constant expression, or may have been
3958 /// derived from an expression tree.
3959 struct BinaryOp {
3960   unsigned Opcode;
3961   Value *LHS;
3962   Value *RHS;
3963   bool IsNSW;
3964   bool IsNUW;
3965
3966   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3967   /// constant expression.
3968   Operator *Op;
3969
3970   explicit BinaryOp(Operator *Op)
3971       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3972         IsNSW(false), IsNUW(false), Op(Op) {
3973     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3974       IsNSW = OBO->hasNoSignedWrap();
3975       IsNUW = OBO->hasNoUnsignedWrap();
3976     }
3977   }
3978
3979   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3980                     bool IsNUW = false)
3981       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3982         Op(nullptr) {}
3983 };
3984 }
3985
3986
3987 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3988 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3989   auto *Op = dyn_cast<Operator>(V);
3990   if (!Op)
3991     return None;
3992
3993   // Implementation detail: all the cleverness here should happen without
3994   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3995   // SCEV expressions when possible, and we should not break that.
3996
3997   switch (Op->getOpcode()) {
3998   case Instruction::Add:
3999   case Instruction::Sub:
4000   case Instruction::Mul:
4001   case Instruction::UDiv:
4002   case Instruction::And:
4003   case Instruction::Or:
4004   case Instruction::AShr:
4005   case Instruction::Shl:
4006     return BinaryOp(Op);
4007
4008   case Instruction::Xor:
4009     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4010       // If the RHS of the xor is a signmask, then this is just an add.
4011       // Instcombine turns add of signmask into xor as a strength reduction step.
4012       if (RHSC->getValue().isSignMask())
4013         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4014     return BinaryOp(Op);
4015
4016   case Instruction::LShr:
4017     // Turn logical shift right of a constant into a unsigned divide.
4018     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4019       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4020
4021       // If the shift count is not less than the bitwidth, the result of
4022       // the shift is undefined. Don't try to analyze it, because the
4023       // resolution chosen here may differ from the resolution chosen in
4024       // other parts of the compiler.
4025       if (SA->getValue().ult(BitWidth)) {
4026         Constant *X =
4027             ConstantInt::get(SA->getContext(),
4028                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4029         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4030       }
4031     }
4032     return BinaryOp(Op);
4033
4034   case Instruction::ExtractValue: {
4035     auto *EVI = cast<ExtractValueInst>(Op);
4036     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4037       break;
4038
4039     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4040     if (!CI)
4041       break;
4042
4043     if (auto *F = CI->getCalledFunction())
4044       switch (F->getIntrinsicID()) {
4045       case Intrinsic::sadd_with_overflow:
4046       case Intrinsic::uadd_with_overflow: {
4047         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4048           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4049                           CI->getArgOperand(1));
4050
4051         // Now that we know that all uses of the arithmetic-result component of
4052         // CI are guarded by the overflow check, we can go ahead and pretend
4053         // that the arithmetic is non-overflowing.
4054         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4055           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4056                           CI->getArgOperand(1), /* IsNSW = */ true,
4057                           /* IsNUW = */ false);
4058         else
4059           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4060                           CI->getArgOperand(1), /* IsNSW = */ false,
4061                           /* IsNUW*/ true);
4062       }
4063
4064       case Intrinsic::ssub_with_overflow:
4065       case Intrinsic::usub_with_overflow:
4066         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4067                         CI->getArgOperand(1));
4068
4069       case Intrinsic::smul_with_overflow:
4070       case Intrinsic::umul_with_overflow:
4071         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4072                         CI->getArgOperand(1));
4073       default:
4074         break;
4075       }
4076   }
4077
4078   default:
4079     break;
4080   }
4081
4082   return None;
4083 }
4084
4085 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4086   const Loop *L = LI.getLoopFor(PN->getParent());
4087   if (!L || L->getHeader() != PN->getParent())
4088     return nullptr;
4089
4090   // The loop may have multiple entrances or multiple exits; we can analyze
4091   // this phi as an addrec if it has a unique entry value and a unique
4092   // backedge value.
4093   Value *BEValueV = nullptr, *StartValueV = nullptr;
4094   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4095     Value *V = PN->getIncomingValue(i);
4096     if (L->contains(PN->getIncomingBlock(i))) {
4097       if (!BEValueV) {
4098         BEValueV = V;
4099       } else if (BEValueV != V) {
4100         BEValueV = nullptr;
4101         break;
4102       }
4103     } else if (!StartValueV) {
4104       StartValueV = V;
4105     } else if (StartValueV != V) {
4106       StartValueV = nullptr;
4107       break;
4108     }
4109   }
4110   if (BEValueV && StartValueV) {
4111     // While we are analyzing this PHI node, handle its value symbolically.
4112     const SCEV *SymbolicName = getUnknown(PN);
4113     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4114            "PHI node already processed?");
4115     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4116
4117     // Using this symbolic name for the PHI, analyze the value coming around
4118     // the back-edge.
4119     const SCEV *BEValue = getSCEV(BEValueV);
4120
4121     // NOTE: If BEValue is loop invariant, we know that the PHI node just
4122     // has a special value for the first iteration of the loop.
4123
4124     // If the value coming around the backedge is an add with the symbolic
4125     // value we just inserted, then we found a simple induction variable!
4126     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4127       // If there is a single occurrence of the symbolic value, replace it
4128       // with a recurrence.
4129       unsigned FoundIndex = Add->getNumOperands();
4130       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4131         if (Add->getOperand(i) == SymbolicName)
4132           if (FoundIndex == e) {
4133             FoundIndex = i;
4134             break;
4135           }
4136
4137       if (FoundIndex != Add->getNumOperands()) {
4138         // Create an add with everything but the specified operand.
4139         SmallVector<const SCEV *, 8> Ops;
4140         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4141           if (i != FoundIndex)
4142             Ops.push_back(Add->getOperand(i));
4143         const SCEV *Accum = getAddExpr(Ops);
4144
4145         // This is not a valid addrec if the step amount is varying each
4146         // loop iteration, but is not itself an addrec in this loop.
4147         if (isLoopInvariant(Accum, L) ||
4148             (isa<SCEVAddRecExpr>(Accum) &&
4149              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4150           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4151
4152           if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4153             if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4154               if (BO->IsNUW)
4155                 Flags = setFlags(Flags, SCEV::FlagNUW);
4156               if (BO->IsNSW)
4157                 Flags = setFlags(Flags, SCEV::FlagNSW);
4158             }
4159           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4160             // If the increment is an inbounds GEP, then we know the address
4161             // space cannot be wrapped around. We cannot make any guarantee
4162             // about signed or unsigned overflow because pointers are
4163             // unsigned but we may have a negative index from the base
4164             // pointer. We can guarantee that no unsigned wrap occurs if the
4165             // indices form a positive value.
4166             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4167               Flags = setFlags(Flags, SCEV::FlagNW);
4168
4169               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4170               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4171                 Flags = setFlags(Flags, SCEV::FlagNUW);
4172             }
4173
4174             // We cannot transfer nuw and nsw flags from subtraction
4175             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4176             // for instance.
4177           }
4178
4179           const SCEV *StartVal = getSCEV(StartValueV);
4180           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4181
4182           // Okay, for the entire analysis of this edge we assumed the PHI
4183           // to be symbolic.  We now need to go back and purge all of the
4184           // entries for the scalars that use the symbolic expression.
4185           forgetSymbolicName(PN, SymbolicName);
4186           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4187
4188           // We can add Flags to the post-inc expression only if we
4189           // know that it us *undefined behavior* for BEValueV to
4190           // overflow.
4191           if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4192             if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4193               (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4194
4195           return PHISCEV;
4196         }
4197       }
4198     } else {
4199       // Otherwise, this could be a loop like this:
4200       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4201       // In this case, j = {1,+,1}  and BEValue is j.
4202       // Because the other in-value of i (0) fits the evolution of BEValue
4203       // i really is an addrec evolution.
4204       //
4205       // We can generalize this saying that i is the shifted value of BEValue
4206       // by one iteration:
4207       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4208       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4209       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4210       if (Shifted != getCouldNotCompute() &&
4211           Start != getCouldNotCompute()) {
4212         const SCEV *StartVal = getSCEV(StartValueV);
4213         if (Start == StartVal) {
4214           // Okay, for the entire analysis of this edge we assumed the PHI
4215           // to be symbolic.  We now need to go back and purge all of the
4216           // entries for the scalars that use the symbolic expression.
4217           forgetSymbolicName(PN, SymbolicName);
4218           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4219           return Shifted;
4220         }
4221       }
4222     }
4223
4224     // Remove the temporary PHI node SCEV that has been inserted while intending
4225     // to create an AddRecExpr for this PHI node. We can not keep this temporary
4226     // as it will prevent later (possibly simpler) SCEV expressions to be added
4227     // to the ValueExprMap.
4228     eraseValueFromMap(PN);
4229   }
4230
4231   return nullptr;
4232 }
4233
4234 // Checks if the SCEV S is available at BB.  S is considered available at BB
4235 // if S can be materialized at BB without introducing a fault.
4236 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4237                                BasicBlock *BB) {
4238   struct CheckAvailable {
4239     bool TraversalDone = false;
4240     bool Available = true;
4241
4242     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4243     BasicBlock *BB = nullptr;
4244     DominatorTree &DT;
4245
4246     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4247       : L(L), BB(BB), DT(DT) {}
4248
4249     bool setUnavailable() {
4250       TraversalDone = true;
4251       Available = false;
4252       return false;
4253     }
4254
4255     bool follow(const SCEV *S) {
4256       switch (S->getSCEVType()) {
4257       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4258       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4259         // These expressions are available if their operand(s) is/are.
4260         return true;
4261
4262       case scAddRecExpr: {
4263         // We allow add recurrences that are on the loop BB is in, or some
4264         // outer loop.  This guarantees availability because the value of the
4265         // add recurrence at BB is simply the "current" value of the induction
4266         // variable.  We can relax this in the future; for instance an add
4267         // recurrence on a sibling dominating loop is also available at BB.
4268         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4269         if (L && (ARLoop == L || ARLoop->contains(L)))
4270           return true;
4271
4272         return setUnavailable();
4273       }
4274
4275       case scUnknown: {
4276         // For SCEVUnknown, we check for simple dominance.
4277         const auto *SU = cast<SCEVUnknown>(S);
4278         Value *V = SU->getValue();
4279
4280         if (isa<Argument>(V))
4281           return false;
4282
4283         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4284           return false;
4285
4286         return setUnavailable();
4287       }
4288
4289       case scUDivExpr:
4290       case scCouldNotCompute:
4291         // We do not try to smart about these at all.
4292         return setUnavailable();
4293       }
4294       llvm_unreachable("switch should be fully covered!");
4295     }
4296
4297     bool isDone() { return TraversalDone; }
4298   };
4299
4300   CheckAvailable CA(L, BB, DT);
4301   SCEVTraversal<CheckAvailable> ST(CA);
4302
4303   ST.visitAll(S);
4304   return CA.Available;
4305 }
4306
4307 // Try to match a control flow sequence that branches out at BI and merges back
4308 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4309 // match.
4310 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4311                           Value *&C, Value *&LHS, Value *&RHS) {
4312   C = BI->getCondition();
4313
4314   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4315   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4316
4317   if (!LeftEdge.isSingleEdge())
4318     return false;
4319
4320   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4321
4322   Use &LeftUse = Merge->getOperandUse(0);
4323   Use &RightUse = Merge->getOperandUse(1);
4324
4325   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4326     LHS = LeftUse;
4327     RHS = RightUse;
4328     return true;
4329   }
4330
4331   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4332     LHS = RightUse;
4333     RHS = LeftUse;
4334     return true;
4335   }
4336
4337   return false;
4338 }
4339
4340 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4341   auto IsReachable =
4342       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4343   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4344     const Loop *L = LI.getLoopFor(PN->getParent());
4345
4346     // We don't want to break LCSSA, even in a SCEV expression tree.
4347     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4348       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4349         return nullptr;
4350
4351     // Try to match
4352     //
4353     //  br %cond, label %left, label %right
4354     // left:
4355     //  br label %merge
4356     // right:
4357     //  br label %merge
4358     // merge:
4359     //  V = phi [ %x, %left ], [ %y, %right ]
4360     //
4361     // as "select %cond, %x, %y"
4362
4363     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4364     assert(IDom && "At least the entry block should dominate PN");
4365
4366     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4367     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4368
4369     if (BI && BI->isConditional() &&
4370         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4371         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4372         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4373       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4374   }
4375
4376   return nullptr;
4377 }
4378
4379 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4380   if (const SCEV *S = createAddRecFromPHI(PN))
4381     return S;
4382
4383   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4384     return S;
4385
4386   // If the PHI has a single incoming value, follow that value, unless the
4387   // PHI's incoming blocks are in a different loop, in which case doing so
4388   // risks breaking LCSSA form. Instcombine would normally zap these, but
4389   // it doesn't have DominatorTree information, so it may miss cases.
4390   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4391     if (LI.replacementPreservesLCSSAForm(PN, V))
4392       return getSCEV(V);
4393
4394   // If it's not a loop phi, we can't handle it yet.
4395   return getUnknown(PN);
4396 }
4397
4398 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4399                                                       Value *Cond,
4400                                                       Value *TrueVal,
4401                                                       Value *FalseVal) {
4402   // Handle "constant" branch or select. This can occur for instance when a
4403   // loop pass transforms an inner loop and moves on to process the outer loop.
4404   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4405     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4406
4407   // Try to match some simple smax or umax patterns.
4408   auto *ICI = dyn_cast<ICmpInst>(Cond);
4409   if (!ICI)
4410     return getUnknown(I);
4411
4412   Value *LHS = ICI->getOperand(0);
4413   Value *RHS = ICI->getOperand(1);
4414
4415   switch (ICI->getPredicate()) {
4416   case ICmpInst::ICMP_SLT:
4417   case ICmpInst::ICMP_SLE:
4418     std::swap(LHS, RHS);
4419     LLVM_FALLTHROUGH;
4420   case ICmpInst::ICMP_SGT:
4421   case ICmpInst::ICMP_SGE:
4422     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4423     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4424     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4425       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4426       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4427       const SCEV *LA = getSCEV(TrueVal);
4428       const SCEV *RA = getSCEV(FalseVal);
4429       const SCEV *LDiff = getMinusSCEV(LA, LS);
4430       const SCEV *RDiff = getMinusSCEV(RA, RS);
4431       if (LDiff == RDiff)
4432         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4433       LDiff = getMinusSCEV(LA, RS);
4434       RDiff = getMinusSCEV(RA, LS);
4435       if (LDiff == RDiff)
4436         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4437     }
4438     break;
4439   case ICmpInst::ICMP_ULT:
4440   case ICmpInst::ICMP_ULE:
4441     std::swap(LHS, RHS);
4442     LLVM_FALLTHROUGH;
4443   case ICmpInst::ICMP_UGT:
4444   case ICmpInst::ICMP_UGE:
4445     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4446     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4447     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4448       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4449       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4450       const SCEV *LA = getSCEV(TrueVal);
4451       const SCEV *RA = getSCEV(FalseVal);
4452       const SCEV *LDiff = getMinusSCEV(LA, LS);
4453       const SCEV *RDiff = getMinusSCEV(RA, RS);
4454       if (LDiff == RDiff)
4455         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4456       LDiff = getMinusSCEV(LA, RS);
4457       RDiff = getMinusSCEV(RA, LS);
4458       if (LDiff == RDiff)
4459         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4460     }
4461     break;
4462   case ICmpInst::ICMP_NE:
4463     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4464     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4465         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4466       const SCEV *One = getOne(I->getType());
4467       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4468       const SCEV *LA = getSCEV(TrueVal);
4469       const SCEV *RA = getSCEV(FalseVal);
4470       const SCEV *LDiff = getMinusSCEV(LA, LS);
4471       const SCEV *RDiff = getMinusSCEV(RA, One);
4472       if (LDiff == RDiff)
4473         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4474     }
4475     break;
4476   case ICmpInst::ICMP_EQ:
4477     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4478     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4479         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4480       const SCEV *One = getOne(I->getType());
4481       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4482       const SCEV *LA = getSCEV(TrueVal);
4483       const SCEV *RA = getSCEV(FalseVal);
4484       const SCEV *LDiff = getMinusSCEV(LA, One);
4485       const SCEV *RDiff = getMinusSCEV(RA, LS);
4486       if (LDiff == RDiff)
4487         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4488     }
4489     break;
4490   default:
4491     break;
4492   }
4493
4494   return getUnknown(I);
4495 }
4496
4497 /// Expand GEP instructions into add and multiply operations. This allows them
4498 /// to be analyzed by regular SCEV code.
4499 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4500   // Don't attempt to analyze GEPs over unsized objects.
4501   if (!GEP->getSourceElementType()->isSized())
4502     return getUnknown(GEP);
4503
4504   SmallVector<const SCEV *, 4> IndexExprs;
4505   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4506     IndexExprs.push_back(getSCEV(*Index));
4507   return getGEPExpr(GEP, IndexExprs);
4508 }
4509
4510 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4511   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4512     return C->getAPInt().countTrailingZeros();
4513
4514   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4515     return std::min(GetMinTrailingZeros(T->getOperand()),
4516                     (uint32_t)getTypeSizeInBits(T->getType()));
4517
4518   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4519     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4520     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4521                ? getTypeSizeInBits(E->getType())
4522                : OpRes;
4523   }
4524
4525   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4526     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4527     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4528                ? getTypeSizeInBits(E->getType())
4529                : OpRes;
4530   }
4531
4532   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4533     // The result is the min of all operands results.
4534     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4535     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4536       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4537     return MinOpRes;
4538   }
4539
4540   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4541     // The result is the sum of all operands results.
4542     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4543     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4544     for (unsigned i = 1, e = M->getNumOperands();
4545          SumOpRes != BitWidth && i != e; ++i)
4546       SumOpRes =
4547           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
4548     return SumOpRes;
4549   }
4550
4551   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4552     // The result is the min of all operands results.
4553     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4554     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4555       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4556     return MinOpRes;
4557   }
4558
4559   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4560     // The result is the min of all operands results.
4561     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4562     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4563       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4564     return MinOpRes;
4565   }
4566
4567   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4568     // The result is the min of all operands results.
4569     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4570     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4571       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4572     return MinOpRes;
4573   }
4574
4575   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4576     // For a SCEVUnknown, ask ValueTracking.
4577     unsigned BitWidth = getTypeSizeInBits(U->getType());
4578     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4579     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4580                      nullptr, &DT);
4581     return Zeros.countTrailingOnes();
4582   }
4583
4584   // SCEVUDivExpr
4585   return 0;
4586 }
4587
4588 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4589   auto I = MinTrailingZerosCache.find(S);
4590   if (I != MinTrailingZerosCache.end())
4591     return I->second;
4592
4593   uint32_t Result = GetMinTrailingZerosImpl(S);
4594   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4595   assert(InsertPair.second && "Should insert a new key");
4596   return InsertPair.first->second;
4597 }
4598
4599 /// Helper method to assign a range to V from metadata present in the IR.
4600 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4601   if (Instruction *I = dyn_cast<Instruction>(V))
4602     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4603       return getConstantRangeFromMetadata(*MD);
4604
4605   return None;
4606 }
4607
4608 /// Determine the range for a particular SCEV.  If SignHint is
4609 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4610 /// with a "cleaner" unsigned (resp. signed) representation.
4611 ConstantRange
4612 ScalarEvolution::getRange(const SCEV *S,
4613                           ScalarEvolution::RangeSignHint SignHint) {
4614   DenseMap<const SCEV *, ConstantRange> &Cache =
4615       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4616                                                        : SignedRanges;
4617
4618   // See if we've computed this range already.
4619   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4620   if (I != Cache.end())
4621     return I->second;
4622
4623   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4624     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4625
4626   unsigned BitWidth = getTypeSizeInBits(S->getType());
4627   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4628
4629   // If the value has known zeros, the maximum value will have those known zeros
4630   // as well.
4631   uint32_t TZ = GetMinTrailingZeros(S);
4632   if (TZ != 0) {
4633     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4634       ConservativeResult =
4635           ConstantRange(APInt::getMinValue(BitWidth),
4636                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4637     else
4638       ConservativeResult = ConstantRange(
4639           APInt::getSignedMinValue(BitWidth),
4640           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4641   }
4642
4643   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4644     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4645     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4646       X = X.add(getRange(Add->getOperand(i), SignHint));
4647     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4648   }
4649
4650   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4651     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4652     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4653       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4654     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4655   }
4656
4657   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4658     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4659     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4660       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4661     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4662   }
4663
4664   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4665     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4666     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4667       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4668     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4669   }
4670
4671   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4672     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4673     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4674     return setRange(UDiv, SignHint,
4675                     ConservativeResult.intersectWith(X.udiv(Y)));
4676   }
4677
4678   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4679     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4680     return setRange(ZExt, SignHint,
4681                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4682   }
4683
4684   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4685     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4686     return setRange(SExt, SignHint,
4687                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4688   }
4689
4690   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4691     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4692     return setRange(Trunc, SignHint,
4693                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4694   }
4695
4696   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4697     // If there's no unsigned wrap, the value will never be less than its
4698     // initial value.
4699     if (AddRec->hasNoUnsignedWrap())
4700       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4701         if (!C->getValue()->isZero())
4702           ConservativeResult = ConservativeResult.intersectWith(
4703               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4704
4705     // If there's no signed wrap, and all the operands have the same sign or
4706     // zero, the value won't ever change sign.
4707     if (AddRec->hasNoSignedWrap()) {
4708       bool AllNonNeg = true;
4709       bool AllNonPos = true;
4710       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4711         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4712         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4713       }
4714       if (AllNonNeg)
4715         ConservativeResult = ConservativeResult.intersectWith(
4716           ConstantRange(APInt(BitWidth, 0),
4717                         APInt::getSignedMinValue(BitWidth)));
4718       else if (AllNonPos)
4719         ConservativeResult = ConservativeResult.intersectWith(
4720           ConstantRange(APInt::getSignedMinValue(BitWidth),
4721                         APInt(BitWidth, 1)));
4722     }
4723
4724     // TODO: non-affine addrec
4725     if (AddRec->isAffine()) {
4726       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4727       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4728           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4729         auto RangeFromAffine = getRangeForAffineAR(
4730             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4731             BitWidth);
4732         if (!RangeFromAffine.isFullSet())
4733           ConservativeResult =
4734               ConservativeResult.intersectWith(RangeFromAffine);
4735
4736         auto RangeFromFactoring = getRangeViaFactoring(
4737             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4738             BitWidth);
4739         if (!RangeFromFactoring.isFullSet())
4740           ConservativeResult =
4741               ConservativeResult.intersectWith(RangeFromFactoring);
4742       }
4743     }
4744
4745     return setRange(AddRec, SignHint, ConservativeResult);
4746   }
4747
4748   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4749     // Check if the IR explicitly contains !range metadata.
4750     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4751     if (MDRange.hasValue())
4752       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4753
4754     // Split here to avoid paying the compile-time cost of calling both
4755     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4756     // if needed.
4757     const DataLayout &DL = getDataLayout();
4758     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4759       // For a SCEVUnknown, ask ValueTracking.
4760       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4761       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4762       if (Ones != ~Zeros + 1)
4763         ConservativeResult =
4764             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4765     } else {
4766       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4767              "generalize as needed!");
4768       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4769       if (NS > 1)
4770         ConservativeResult = ConservativeResult.intersectWith(
4771             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4772                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4773     }
4774
4775     return setRange(U, SignHint, ConservativeResult);
4776   }
4777
4778   return setRange(S, SignHint, ConservativeResult);
4779 }
4780
4781 // Given a StartRange, Step and MaxBECount for an expression compute a range of
4782 // values that the expression can take. Initially, the expression has a value
4783 // from StartRange and then is changed by Step up to MaxBECount times. Signed
4784 // argument defines if we treat Step as signed or unsigned.
4785 static ConstantRange getRangeForAffineARHelper(APInt Step,
4786                                                ConstantRange StartRange,
4787                                                APInt MaxBECount,
4788                                                unsigned BitWidth, bool Signed) {
4789   // If either Step or MaxBECount is 0, then the expression won't change, and we
4790   // just need to return the initial range.
4791   if (Step == 0 || MaxBECount == 0)
4792     return StartRange;
4793
4794   // If we don't know anything about the initial value (i.e. StartRange is
4795   // FullRange), then we don't know anything about the final range either.
4796   // Return FullRange.
4797   if (StartRange.isFullSet())
4798     return ConstantRange(BitWidth, /* isFullSet = */ true);
4799
4800   // If Step is signed and negative, then we use its absolute value, but we also
4801   // note that we're moving in the opposite direction.
4802   bool Descending = Signed && Step.isNegative();
4803
4804   if (Signed)
4805     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4806     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4807     // This equations hold true due to the well-defined wrap-around behavior of
4808     // APInt.
4809     Step = Step.abs();
4810
4811   // Check if Offset is more than full span of BitWidth. If it is, the
4812   // expression is guaranteed to overflow.
4813   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4814     return ConstantRange(BitWidth, /* isFullSet = */ true);
4815
4816   // Offset is by how much the expression can change. Checks above guarantee no
4817   // overflow here.
4818   APInt Offset = Step * MaxBECount;
4819
4820   // Minimum value of the final range will match the minimal value of StartRange
4821   // if the expression is increasing and will be decreased by Offset otherwise.
4822   // Maximum value of the final range will match the maximal value of StartRange
4823   // if the expression is decreasing and will be increased by Offset otherwise.
4824   APInt StartLower = StartRange.getLower();
4825   APInt StartUpper = StartRange.getUpper() - 1;
4826   APInt MovedBoundary =
4827       Descending ? (StartLower - Offset) : (StartUpper + Offset);
4828
4829   // It's possible that the new minimum/maximum value will fall into the initial
4830   // range (due to wrap around). This means that the expression can take any
4831   // value in this bitwidth, and we have to return full range.
4832   if (StartRange.contains(MovedBoundary))
4833     return ConstantRange(BitWidth, /* isFullSet = */ true);
4834
4835   APInt NewLower, NewUpper;
4836   if (Descending) {
4837     NewLower = MovedBoundary;
4838     NewUpper = StartUpper;
4839   } else {
4840     NewLower = StartLower;
4841     NewUpper = MovedBoundary;
4842   }
4843
4844   // If we end up with full range, return a proper full range.
4845   if (NewLower == NewUpper + 1)
4846     return ConstantRange(BitWidth, /* isFullSet = */ true);
4847
4848   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4849   return ConstantRange(NewLower, NewUpper + 1);
4850 }
4851
4852 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4853                                                    const SCEV *Step,
4854                                                    const SCEV *MaxBECount,
4855                                                    unsigned BitWidth) {
4856   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4857          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4858          "Precondition!");
4859
4860   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4861   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4862   APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
4863
4864   // First, consider step signed.
4865   ConstantRange StartSRange = getSignedRange(Start);
4866   ConstantRange StepSRange = getSignedRange(Step);
4867
4868   // If Step can be both positive and negative, we need to find ranges for the
4869   // maximum absolute step values in both directions and union them.
4870   ConstantRange SR =
4871       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4872                                 MaxBECountValue, BitWidth, /* Signed = */ true);
4873   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4874                                               StartSRange, MaxBECountValue,
4875                                               BitWidth, /* Signed = */ true));
4876
4877   // Next, consider step unsigned.
4878   ConstantRange UR = getRangeForAffineARHelper(
4879       getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4880       MaxBECountValue, BitWidth, /* Signed = */ false);
4881
4882   // Finally, intersect signed and unsigned ranges.
4883   return SR.intersectWith(UR);
4884 }
4885
4886 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4887                                                     const SCEV *Step,
4888                                                     const SCEV *MaxBECount,
4889                                                     unsigned BitWidth) {
4890   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4891   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4892
4893   struct SelectPattern {
4894     Value *Condition = nullptr;
4895     APInt TrueValue;
4896     APInt FalseValue;
4897
4898     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4899                            const SCEV *S) {
4900       Optional<unsigned> CastOp;
4901       APInt Offset(BitWidth, 0);
4902
4903       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4904              "Should be!");
4905
4906       // Peel off a constant offset:
4907       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4908         // In the future we could consider being smarter here and handle
4909         // {Start+Step,+,Step} too.
4910         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4911           return;
4912
4913         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4914         S = SA->getOperand(1);
4915       }
4916
4917       // Peel off a cast operation
4918       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4919         CastOp = SCast->getSCEVType();
4920         S = SCast->getOperand();
4921       }
4922
4923       using namespace llvm::PatternMatch;
4924
4925       auto *SU = dyn_cast<SCEVUnknown>(S);
4926       const APInt *TrueVal, *FalseVal;
4927       if (!SU ||
4928           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4929                                           m_APInt(FalseVal)))) {
4930         Condition = nullptr;
4931         return;
4932       }
4933
4934       TrueValue = *TrueVal;
4935       FalseValue = *FalseVal;
4936
4937       // Re-apply the cast we peeled off earlier
4938       if (CastOp.hasValue())
4939         switch (*CastOp) {
4940         default:
4941           llvm_unreachable("Unknown SCEV cast type!");
4942
4943         case scTruncate:
4944           TrueValue = TrueValue.trunc(BitWidth);
4945           FalseValue = FalseValue.trunc(BitWidth);
4946           break;
4947         case scZeroExtend:
4948           TrueValue = TrueValue.zext(BitWidth);
4949           FalseValue = FalseValue.zext(BitWidth);
4950           break;
4951         case scSignExtend:
4952           TrueValue = TrueValue.sext(BitWidth);
4953           FalseValue = FalseValue.sext(BitWidth);
4954           break;
4955         }
4956
4957       // Re-apply the constant offset we peeled off earlier
4958       TrueValue += Offset;
4959       FalseValue += Offset;
4960     }
4961
4962     bool isRecognized() { return Condition != nullptr; }
4963   };
4964
4965   SelectPattern StartPattern(*this, BitWidth, Start);
4966   if (!StartPattern.isRecognized())
4967     return ConstantRange(BitWidth, /* isFullSet = */ true);
4968
4969   SelectPattern StepPattern(*this, BitWidth, Step);
4970   if (!StepPattern.isRecognized())
4971     return ConstantRange(BitWidth, /* isFullSet = */ true);
4972
4973   if (StartPattern.Condition != StepPattern.Condition) {
4974     // We don't handle this case today; but we could, by considering four
4975     // possibilities below instead of two. I'm not sure if there are cases where
4976     // that will help over what getRange already does, though.
4977     return ConstantRange(BitWidth, /* isFullSet = */ true);
4978   }
4979
4980   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4981   // construct arbitrary general SCEV expressions here.  This function is called
4982   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4983   // say) can end up caching a suboptimal value.
4984
4985   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4986   // C2352 and C2512 (otherwise it isn't needed).
4987
4988   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4989   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4990   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4991   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4992
4993   ConstantRange TrueRange =
4994       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4995   ConstantRange FalseRange =
4996       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4997
4998   return TrueRange.unionWith(FalseRange);
4999 }
5000
5001 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5002   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5003   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5004
5005   // Return early if there are no flags to propagate to the SCEV.
5006   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5007   if (BinOp->hasNoUnsignedWrap())
5008     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5009   if (BinOp->hasNoSignedWrap())
5010     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5011   if (Flags == SCEV::FlagAnyWrap)
5012     return SCEV::FlagAnyWrap;
5013
5014   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5015 }
5016
5017 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5018   // Here we check that I is in the header of the innermost loop containing I,
5019   // since we only deal with instructions in the loop header. The actual loop we
5020   // need to check later will come from an add recurrence, but getting that
5021   // requires computing the SCEV of the operands, which can be expensive. This
5022   // check we can do cheaply to rule out some cases early.
5023   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5024   if (InnermostContainingLoop == nullptr ||
5025       InnermostContainingLoop->getHeader() != I->getParent())
5026     return false;
5027
5028   // Only proceed if we can prove that I does not yield poison.
5029   if (!isKnownNotFullPoison(I)) return false;
5030
5031   // At this point we know that if I is executed, then it does not wrap
5032   // according to at least one of NSW or NUW. If I is not executed, then we do
5033   // not know if the calculation that I represents would wrap. Multiple
5034   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5035   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5036   // derived from other instructions that map to the same SCEV. We cannot make
5037   // that guarantee for cases where I is not executed. So we need to find the
5038   // loop that I is considered in relation to and prove that I is executed for
5039   // every iteration of that loop. That implies that the value that I
5040   // calculates does not wrap anywhere in the loop, so then we can apply the
5041   // flags to the SCEV.
5042   //
5043   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5044   // from different loops, so that we know which loop to prove that I is
5045   // executed in.
5046   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5047     // I could be an extractvalue from a call to an overflow intrinsic.
5048     // TODO: We can do better here in some cases.
5049     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5050       return false;
5051     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5052     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5053       bool AllOtherOpsLoopInvariant = true;
5054       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5055            ++OtherOpIndex) {
5056         if (OtherOpIndex != OpIndex) {
5057           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5058           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5059             AllOtherOpsLoopInvariant = false;
5060             break;
5061           }
5062         }
5063       }
5064       if (AllOtherOpsLoopInvariant &&
5065           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5066         return true;
5067     }
5068   }
5069   return false;
5070 }
5071
5072 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5073   // If we know that \c I can never be poison period, then that's enough.
5074   if (isSCEVExprNeverPoison(I))
5075     return true;
5076
5077   // For an add recurrence specifically, we assume that infinite loops without
5078   // side effects are undefined behavior, and then reason as follows:
5079   //
5080   // If the add recurrence is poison in any iteration, it is poison on all
5081   // future iterations (since incrementing poison yields poison). If the result
5082   // of the add recurrence is fed into the loop latch condition and the loop
5083   // does not contain any throws or exiting blocks other than the latch, we now
5084   // have the ability to "choose" whether the backedge is taken or not (by
5085   // choosing a sufficiently evil value for the poison feeding into the branch)
5086   // for every iteration including and after the one in which \p I first became
5087   // poison.  There are two possibilities (let's call the iteration in which \p
5088   // I first became poison as K):
5089   //
5090   //  1. In the set of iterations including and after K, the loop body executes
5091   //     no side effects.  In this case executing the backege an infinte number
5092   //     of times will yield undefined behavior.
5093   //
5094   //  2. In the set of iterations including and after K, the loop body executes
5095   //     at least one side effect.  In this case, that specific instance of side
5096   //     effect is control dependent on poison, which also yields undefined
5097   //     behavior.
5098
5099   auto *ExitingBB = L->getExitingBlock();
5100   auto *LatchBB = L->getLoopLatch();
5101   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5102     return false;
5103
5104   SmallPtrSet<const Instruction *, 16> Pushed;
5105   SmallVector<const Instruction *, 8> PoisonStack;
5106
5107   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5108   // things that are known to be fully poison under that assumption go on the
5109   // PoisonStack.
5110   Pushed.insert(I);
5111   PoisonStack.push_back(I);
5112
5113   bool LatchControlDependentOnPoison = false;
5114   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5115     const Instruction *Poison = PoisonStack.pop_back_val();
5116
5117     for (auto *PoisonUser : Poison->users()) {
5118       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5119         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5120           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5121       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5122         assert(BI->isConditional() && "Only possibility!");
5123         if (BI->getParent() == LatchBB) {
5124           LatchControlDependentOnPoison = true;
5125           break;
5126         }
5127       }
5128     }
5129   }
5130
5131   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5132 }
5133
5134 ScalarEvolution::LoopProperties
5135 ScalarEvolution::getLoopProperties(const Loop *L) {
5136   typedef ScalarEvolution::LoopProperties LoopProperties;
5137
5138   auto Itr = LoopPropertiesCache.find(L);
5139   if (Itr == LoopPropertiesCache.end()) {
5140     auto HasSideEffects = [](Instruction *I) {
5141       if (auto *SI = dyn_cast<StoreInst>(I))
5142         return !SI->isSimple();
5143
5144       return I->mayHaveSideEffects();
5145     };
5146
5147     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5148                          /*HasNoSideEffects*/ true};
5149
5150     for (auto *BB : L->getBlocks())
5151       for (auto &I : *BB) {
5152         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5153           LP.HasNoAbnormalExits = false;
5154         if (HasSideEffects(&I))
5155           LP.HasNoSideEffects = false;
5156         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5157           break; // We're already as pessimistic as we can get.
5158       }
5159
5160     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5161     assert(InsertPair.second && "We just checked!");
5162     Itr = InsertPair.first;
5163   }
5164
5165   return Itr->second;
5166 }
5167
5168 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5169   if (!isSCEVable(V->getType()))
5170     return getUnknown(V);
5171
5172   if (Instruction *I = dyn_cast<Instruction>(V)) {
5173     // Don't attempt to analyze instructions in blocks that aren't
5174     // reachable. Such instructions don't matter, and they aren't required
5175     // to obey basic rules for definitions dominating uses which this
5176     // analysis depends on.
5177     if (!DT.isReachableFromEntry(I->getParent()))
5178       return getUnknown(V);
5179   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5180     return getConstant(CI);
5181   else if (isa<ConstantPointerNull>(V))
5182     return getZero(V->getType());
5183   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5184     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5185   else if (!isa<ConstantExpr>(V))
5186     return getUnknown(V);
5187
5188   Operator *U = cast<Operator>(V);
5189   if (auto BO = MatchBinaryOp(U, DT)) {
5190     switch (BO->Opcode) {
5191     case Instruction::Add: {
5192       // The simple thing to do would be to just call getSCEV on both operands
5193       // and call getAddExpr with the result. However if we're looking at a
5194       // bunch of things all added together, this can be quite inefficient,
5195       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5196       // Instead, gather up all the operands and make a single getAddExpr call.
5197       // LLVM IR canonical form means we need only traverse the left operands.
5198       SmallVector<const SCEV *, 4> AddOps;
5199       do {
5200         if (BO->Op) {
5201           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5202             AddOps.push_back(OpSCEV);
5203             break;
5204           }
5205
5206           // If a NUW or NSW flag can be applied to the SCEV for this
5207           // addition, then compute the SCEV for this addition by itself
5208           // with a separate call to getAddExpr. We need to do that
5209           // instead of pushing the operands of the addition onto AddOps,
5210           // since the flags are only known to apply to this particular
5211           // addition - they may not apply to other additions that can be
5212           // formed with operands from AddOps.
5213           const SCEV *RHS = getSCEV(BO->RHS);
5214           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5215           if (Flags != SCEV::FlagAnyWrap) {
5216             const SCEV *LHS = getSCEV(BO->LHS);
5217             if (BO->Opcode == Instruction::Sub)
5218               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5219             else
5220               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5221             break;
5222           }
5223         }
5224
5225         if (BO->Opcode == Instruction::Sub)
5226           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5227         else
5228           AddOps.push_back(getSCEV(BO->RHS));
5229
5230         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5231         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5232                        NewBO->Opcode != Instruction::Sub)) {
5233           AddOps.push_back(getSCEV(BO->LHS));
5234           break;
5235         }
5236         BO = NewBO;
5237       } while (true);
5238
5239       return getAddExpr(AddOps);
5240     }
5241
5242     case Instruction::Mul: {
5243       SmallVector<const SCEV *, 4> MulOps;
5244       do {
5245         if (BO->Op) {
5246           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5247             MulOps.push_back(OpSCEV);
5248             break;
5249           }
5250
5251           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5252           if (Flags != SCEV::FlagAnyWrap) {
5253             MulOps.push_back(
5254                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5255             break;
5256           }
5257         }
5258
5259         MulOps.push_back(getSCEV(BO->RHS));
5260         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5261         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5262           MulOps.push_back(getSCEV(BO->LHS));
5263           break;
5264         }
5265         BO = NewBO;
5266       } while (true);
5267
5268       return getMulExpr(MulOps);
5269     }
5270     case Instruction::UDiv:
5271       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5272     case Instruction::Sub: {
5273       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5274       if (BO->Op)
5275         Flags = getNoWrapFlagsFromUB(BO->Op);
5276       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5277     }
5278     case Instruction::And:
5279       // For an expression like x&255 that merely masks off the high bits,
5280       // use zext(trunc(x)) as the SCEV expression.
5281       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5282         if (CI->isNullValue())
5283           return getSCEV(BO->RHS);
5284         if (CI->isAllOnesValue())
5285           return getSCEV(BO->LHS);
5286         const APInt &A = CI->getValue();
5287
5288         // Instcombine's ShrinkDemandedConstant may strip bits out of
5289         // constants, obscuring what would otherwise be a low-bits mask.
5290         // Use computeKnownBits to compute what ShrinkDemandedConstant
5291         // knew about to reconstruct a low-bits mask value.
5292         unsigned LZ = A.countLeadingZeros();
5293         unsigned TZ = A.countTrailingZeros();
5294         unsigned BitWidth = A.getBitWidth();
5295         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5296         computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5297                          0, &AC, nullptr, &DT);
5298
5299         APInt EffectiveMask =
5300             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5301         if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5302           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5303           const SCEV *LHS = getSCEV(BO->LHS);
5304           const SCEV *ShiftedLHS = nullptr;
5305           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5306             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5307               // For an expression like (x * 8) & 8, simplify the multiply.
5308               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5309               unsigned GCD = std::min(MulZeros, TZ);
5310               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5311               SmallVector<const SCEV*, 4> MulOps;
5312               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5313               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5314               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5315               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5316             }
5317           }
5318           if (!ShiftedLHS)
5319             ShiftedLHS = getUDivExpr(LHS, MulCount);
5320           return getMulExpr(
5321               getZeroExtendExpr(
5322                   getTruncateExpr(ShiftedLHS,
5323                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5324                   BO->LHS->getType()),
5325               MulCount);
5326         }
5327       }
5328       break;
5329
5330     case Instruction::Or:
5331       // Use ValueTracking to check whether this is actually an add.
5332       if (haveNoCommonBitsSet(BO->LHS, BO->RHS, getDataLayout(), &AC,
5333                               nullptr, &DT)) {
5334         // There aren't any common bits set, so the add can't wrap.
5335         auto Flags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNSW);
5336         return getAddExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5337       }
5338       break;
5339
5340     case Instruction::Xor:
5341       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5342         // If the RHS of xor is -1, then this is a not operation.
5343         if (CI->isAllOnesValue())
5344           return getNotSCEV(getSCEV(BO->LHS));
5345
5346         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5347         // This is a variant of the check for xor with -1, and it handles
5348         // the case where instcombine has trimmed non-demanded bits out
5349         // of an xor with -1.
5350         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5351           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5352             if (LBO->getOpcode() == Instruction::And &&
5353                 LCI->getValue() == CI->getValue())
5354               if (const SCEVZeroExtendExpr *Z =
5355                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5356                 Type *UTy = BO->LHS->getType();
5357                 const SCEV *Z0 = Z->getOperand();
5358                 Type *Z0Ty = Z0->getType();
5359                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5360
5361                 // If C is a low-bits mask, the zero extend is serving to
5362                 // mask off the high bits. Complement the operand and
5363                 // re-apply the zext.
5364                 if (CI->getValue().isMask(Z0TySize))
5365                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5366
5367                 // If C is a single bit, it may be in the sign-bit position
5368                 // before the zero-extend. In this case, represent the xor
5369                 // using an add, which is equivalent, and re-apply the zext.
5370                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5371                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5372                     Trunc.isSignMask())
5373                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5374                                            UTy);
5375               }
5376       }
5377       break;
5378
5379   case Instruction::Shl:
5380     // Turn shift left of a constant amount into a multiply.
5381     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5382       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5383
5384       // If the shift count is not less than the bitwidth, the result of
5385       // the shift is undefined. Don't try to analyze it, because the
5386       // resolution chosen here may differ from the resolution chosen in
5387       // other parts of the compiler.
5388       if (SA->getValue().uge(BitWidth))
5389         break;
5390
5391       // It is currently not resolved how to interpret NSW for left
5392       // shift by BitWidth - 1, so we avoid applying flags in that
5393       // case. Remove this check (or this comment) once the situation
5394       // is resolved. See
5395       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5396       // and http://reviews.llvm.org/D8890 .
5397       auto Flags = SCEV::FlagAnyWrap;
5398       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5399         Flags = getNoWrapFlagsFromUB(BO->Op);
5400
5401       Constant *X = ConstantInt::get(getContext(),
5402         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5403       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5404     }
5405     break;
5406
5407     case Instruction::AShr:
5408       // AShr X, C, where C is a constant.
5409       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5410       if (!CI)
5411         break;
5412
5413       Type *OuterTy = BO->LHS->getType();
5414       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5415       // If the shift count is not less than the bitwidth, the result of
5416       // the shift is undefined. Don't try to analyze it, because the
5417       // resolution chosen here may differ from the resolution chosen in
5418       // other parts of the compiler.
5419       if (CI->getValue().uge(BitWidth))
5420         break;
5421
5422       if (CI->isNullValue())
5423         return getSCEV(BO->LHS); // shift by zero --> noop
5424
5425       uint64_t AShrAmt = CI->getZExtValue();
5426       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5427
5428       Operator *L = dyn_cast<Operator>(BO->LHS);
5429       if (L && L->getOpcode() == Instruction::Shl) {
5430         // X = Shl A, n
5431         // Y = AShr X, m
5432         // Both n and m are constant.
5433
5434         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5435         if (L->getOperand(1) == BO->RHS)
5436           // For a two-shift sext-inreg, i.e. n = m,
5437           // use sext(trunc(x)) as the SCEV expression.
5438           return getSignExtendExpr(
5439               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5440
5441         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5442         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5443           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5444           if (ShlAmt > AShrAmt) {
5445             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5446             // expression. We already checked that ShlAmt < BitWidth, so
5447             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5448             // ShlAmt - AShrAmt < Amt.
5449             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5450                                             ShlAmt - AShrAmt);
5451             return getSignExtendExpr(
5452                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5453                 getConstant(Mul)), OuterTy);
5454           }
5455         }
5456       }
5457       break;
5458     }
5459   }
5460
5461   switch (U->getOpcode()) {
5462   case Instruction::Trunc:
5463     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5464
5465   case Instruction::ZExt:
5466     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5467
5468   case Instruction::SExt:
5469     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5470
5471   case Instruction::BitCast:
5472     // BitCasts are no-op casts so we just eliminate the cast.
5473     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5474       return getSCEV(U->getOperand(0));
5475     break;
5476
5477   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5478   // lead to pointer expressions which cannot safely be expanded to GEPs,
5479   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5480   // simplifying integer expressions.
5481
5482   case Instruction::GetElementPtr:
5483     return createNodeForGEP(cast<GEPOperator>(U));
5484
5485   case Instruction::PHI:
5486     return createNodeForPHI(cast<PHINode>(U));
5487
5488   case Instruction::Select:
5489     // U can also be a select constant expr, which let fall through.  Since
5490     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5491     // constant expressions cannot have instructions as operands, we'd have
5492     // returned getUnknown for a select constant expressions anyway.
5493     if (isa<Instruction>(U))
5494       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5495                                       U->getOperand(1), U->getOperand(2));
5496     break;
5497
5498   case Instruction::Call:
5499   case Instruction::Invoke:
5500     if (Value *RV = CallSite(U).getReturnedArgOperand())
5501       return getSCEV(RV);
5502     break;
5503   }
5504
5505   return getUnknown(V);
5506 }
5507
5508
5509
5510 //===----------------------------------------------------------------------===//
5511 //                   Iteration Count Computation Code
5512 //
5513
5514 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5515   if (!ExitCount)
5516     return 0;
5517
5518   ConstantInt *ExitConst = ExitCount->getValue();
5519
5520   // Guard against huge trip counts.
5521   if (ExitConst->getValue().getActiveBits() > 32)
5522     return 0;
5523
5524   // In case of integer overflow, this returns 0, which is correct.
5525   return ((unsigned)ExitConst->getZExtValue()) + 1;
5526 }
5527
5528 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
5529   if (BasicBlock *ExitingBB = L->getExitingBlock())
5530     return getSmallConstantTripCount(L, ExitingBB);
5531
5532   // No trip count information for multiple exits.
5533   return 0;
5534 }
5535
5536 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
5537                                                     BasicBlock *ExitingBlock) {
5538   assert(ExitingBlock && "Must pass a non-null exiting block!");
5539   assert(L->isLoopExiting(ExitingBlock) &&
5540          "Exiting block must actually branch out of the loop!");
5541   const SCEVConstant *ExitCount =
5542       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5543   return getConstantTripCount(ExitCount);
5544 }
5545
5546 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
5547   const auto *MaxExitCount =
5548       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5549   return getConstantTripCount(MaxExitCount);
5550 }
5551
5552 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
5553   if (BasicBlock *ExitingBB = L->getExitingBlock())
5554     return getSmallConstantTripMultiple(L, ExitingBB);
5555
5556   // No trip multiple information for multiple exits.
5557   return 0;
5558 }
5559
5560 /// Returns the largest constant divisor of the trip count of this loop as a
5561 /// normal unsigned value, if possible. This means that the actual trip count is
5562 /// always a multiple of the returned value (don't forget the trip count could
5563 /// very well be zero as well!).
5564 ///
5565 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5566 /// multiple of a constant (which is also the case if the trip count is simply
5567 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5568 /// if the trip count is very large (>= 2^32).
5569 ///
5570 /// As explained in the comments for getSmallConstantTripCount, this assumes
5571 /// that control exits the loop via ExitingBlock.
5572 unsigned
5573 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
5574                                               BasicBlock *ExitingBlock) {
5575   assert(ExitingBlock && "Must pass a non-null exiting block!");
5576   assert(L->isLoopExiting(ExitingBlock) &&
5577          "Exiting block must actually branch out of the loop!");
5578   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5579   if (ExitCount == getCouldNotCompute())
5580     return 1;
5581
5582   // Get the trip count from the BE count by adding 1.
5583   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5584
5585   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5586   if (!TC)
5587     // Attempt to factor more general cases. Returns the greatest power of
5588     // two divisor. If overflow happens, the trip count expression is still
5589     // divisible by the greatest power of 2 divisor returned.
5590     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
5591
5592   ConstantInt *Result = TC->getValue();
5593
5594   // Guard against huge trip counts (this requires checking
5595   // for zero to handle the case where the trip count == -1 and the
5596   // addition wraps).
5597   if (!Result || Result->getValue().getActiveBits() > 32 ||
5598       Result->getValue().getActiveBits() == 0)
5599     return 1;
5600
5601   return (unsigned)Result->getZExtValue();
5602 }
5603
5604 /// Get the expression for the number of loop iterations for which this loop is
5605 /// guaranteed not to exit via ExitingBlock. Otherwise return
5606 /// SCEVCouldNotCompute.
5607 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5608                                           BasicBlock *ExitingBlock) {
5609   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5610 }
5611
5612 const SCEV *
5613 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5614                                                  SCEVUnionPredicate &Preds) {
5615   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5616 }
5617
5618 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5619   return getBackedgeTakenInfo(L).getExact(this);
5620 }
5621
5622 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5623 /// known never to be less than the actual backedge taken count.
5624 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5625   return getBackedgeTakenInfo(L).getMax(this);
5626 }
5627
5628 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5629   return getBackedgeTakenInfo(L).isMaxOrZero(this);
5630 }
5631
5632 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5633 static void
5634 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5635   BasicBlock *Header = L->getHeader();
5636
5637   // Push all Loop-header PHIs onto the Worklist stack.
5638   for (BasicBlock::iterator I = Header->begin();
5639        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5640     Worklist.push_back(PN);
5641 }
5642
5643 const ScalarEvolution::BackedgeTakenInfo &
5644 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5645   auto &BTI = getBackedgeTakenInfo(L);
5646   if (BTI.hasFullInfo())
5647     return BTI;
5648
5649   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5650
5651   if (!Pair.second)
5652     return Pair.first->second;
5653
5654   BackedgeTakenInfo Result =
5655       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5656
5657   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5658 }
5659
5660 const ScalarEvolution::BackedgeTakenInfo &
5661 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5662   // Initially insert an invalid entry for this loop. If the insertion
5663   // succeeds, proceed to actually compute a backedge-taken count and
5664   // update the value. The temporary CouldNotCompute value tells SCEV
5665   // code elsewhere that it shouldn't attempt to request a new
5666   // backedge-taken count, which could result in infinite recursion.
5667   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5668       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5669   if (!Pair.second)
5670     return Pair.first->second;
5671
5672   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5673   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5674   // must be cleared in this scope.
5675   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5676
5677   if (Result.getExact(this) != getCouldNotCompute()) {
5678     assert(isLoopInvariant(Result.getExact(this), L) &&
5679            isLoopInvariant(Result.getMax(this), L) &&
5680            "Computed backedge-taken count isn't loop invariant for loop!");
5681     ++NumTripCountsComputed;
5682   }
5683   else if (Result.getMax(this) == getCouldNotCompute() &&
5684            isa<PHINode>(L->getHeader()->begin())) {
5685     // Only count loops that have phi nodes as not being computable.
5686     ++NumTripCountsNotComputed;
5687   }
5688
5689   // Now that we know more about the trip count for this loop, forget any
5690   // existing SCEV values for PHI nodes in this loop since they are only
5691   // conservative estimates made without the benefit of trip count
5692   // information. This is similar to the code in forgetLoop, except that
5693   // it handles SCEVUnknown PHI nodes specially.
5694   if (Result.hasAnyInfo()) {
5695     SmallVector<Instruction *, 16> Worklist;
5696     PushLoopPHIs(L, Worklist);
5697
5698     SmallPtrSet<Instruction *, 8> Visited;
5699     while (!Worklist.empty()) {
5700       Instruction *I = Worklist.pop_back_val();
5701       if (!Visited.insert(I).second)
5702         continue;
5703
5704       ValueExprMapType::iterator It =
5705         ValueExprMap.find_as(static_cast<Value *>(I));
5706       if (It != ValueExprMap.end()) {
5707         const SCEV *Old = It->second;
5708
5709         // SCEVUnknown for a PHI either means that it has an unrecognized
5710         // structure, or it's a PHI that's in the progress of being computed
5711         // by createNodeForPHI.  In the former case, additional loop trip
5712         // count information isn't going to change anything. In the later
5713         // case, createNodeForPHI will perform the necessary updates on its
5714         // own when it gets to that point.
5715         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5716           eraseValueFromMap(It->first);
5717           forgetMemoizedResults(Old);
5718         }
5719         if (PHINode *PN = dyn_cast<PHINode>(I))
5720           ConstantEvolutionLoopExitValue.erase(PN);
5721       }
5722
5723       PushDefUseChildren(I, Worklist);
5724     }
5725   }
5726
5727   // Re-lookup the insert position, since the call to
5728   // computeBackedgeTakenCount above could result in a
5729   // recusive call to getBackedgeTakenInfo (on a different
5730   // loop), which would invalidate the iterator computed
5731   // earlier.
5732   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5733 }
5734
5735 void ScalarEvolution::forgetLoop(const Loop *L) {
5736   // Drop any stored trip count value.
5737   auto RemoveLoopFromBackedgeMap =
5738       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5739         auto BTCPos = Map.find(L);
5740         if (BTCPos != Map.end()) {
5741           BTCPos->second.clear();
5742           Map.erase(BTCPos);
5743         }
5744       };
5745
5746   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5747   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5748
5749   // Drop information about expressions based on loop-header PHIs.
5750   SmallVector<Instruction *, 16> Worklist;
5751   PushLoopPHIs(L, Worklist);
5752
5753   SmallPtrSet<Instruction *, 8> Visited;
5754   while (!Worklist.empty()) {
5755     Instruction *I = Worklist.pop_back_val();
5756     if (!Visited.insert(I).second)
5757       continue;
5758
5759     ValueExprMapType::iterator It =
5760       ValueExprMap.find_as(static_cast<Value *>(I));
5761     if (It != ValueExprMap.end()) {
5762       eraseValueFromMap(It->first);
5763       forgetMemoizedResults(It->second);
5764       if (PHINode *PN = dyn_cast<PHINode>(I))
5765         ConstantEvolutionLoopExitValue.erase(PN);
5766     }
5767
5768     PushDefUseChildren(I, Worklist);
5769   }
5770
5771   // Forget all contained loops too, to avoid dangling entries in the
5772   // ValuesAtScopes map.
5773   for (Loop *I : *L)
5774     forgetLoop(I);
5775
5776   LoopPropertiesCache.erase(L);
5777 }
5778
5779 void ScalarEvolution::forgetValue(Value *V) {
5780   Instruction *I = dyn_cast<Instruction>(V);
5781   if (!I) return;
5782
5783   // Drop information about expressions based on loop-header PHIs.
5784   SmallVector<Instruction *, 16> Worklist;
5785   Worklist.push_back(I);
5786
5787   SmallPtrSet<Instruction *, 8> Visited;
5788   while (!Worklist.empty()) {
5789     I = Worklist.pop_back_val();
5790     if (!Visited.insert(I).second)
5791       continue;
5792
5793     ValueExprMapType::iterator It =
5794       ValueExprMap.find_as(static_cast<Value *>(I));
5795     if (It != ValueExprMap.end()) {
5796       eraseValueFromMap(It->first);
5797       forgetMemoizedResults(It->second);
5798       if (PHINode *PN = dyn_cast<PHINode>(I))
5799         ConstantEvolutionLoopExitValue.erase(PN);
5800     }
5801
5802     PushDefUseChildren(I, Worklist);
5803   }
5804 }
5805
5806 /// Get the exact loop backedge taken count considering all loop exits. A
5807 /// computable result can only be returned for loops with a single exit.
5808 /// Returning the minimum taken count among all exits is incorrect because one
5809 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5810 /// the limit of each loop test is never skipped. This is a valid assumption as
5811 /// long as the loop exits via that test. For precise results, it is the
5812 /// caller's responsibility to specify the relevant loop exit using
5813 /// getExact(ExitingBlock, SE).
5814 const SCEV *
5815 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5816                                              SCEVUnionPredicate *Preds) const {
5817   // If any exits were not computable, the loop is not computable.
5818   if (!isComplete() || ExitNotTaken.empty())
5819     return SE->getCouldNotCompute();
5820
5821   const SCEV *BECount = nullptr;
5822   for (auto &ENT : ExitNotTaken) {
5823     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5824
5825     if (!BECount)
5826       BECount = ENT.ExactNotTaken;
5827     else if (BECount != ENT.ExactNotTaken)
5828       return SE->getCouldNotCompute();
5829     if (Preds && !ENT.hasAlwaysTruePredicate())
5830       Preds->add(ENT.Predicate.get());
5831
5832     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5833            "Predicate should be always true!");
5834   }
5835
5836   assert(BECount && "Invalid not taken count for loop exit");
5837   return BECount;
5838 }
5839
5840 /// Get the exact not taken count for this loop exit.
5841 const SCEV *
5842 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5843                                              ScalarEvolution *SE) const {
5844   for (auto &ENT : ExitNotTaken)
5845     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5846       return ENT.ExactNotTaken;
5847
5848   return SE->getCouldNotCompute();
5849 }
5850
5851 /// getMax - Get the max backedge taken count for the loop.
5852 const SCEV *
5853 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5854   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5855     return !ENT.hasAlwaysTruePredicate();
5856   };
5857
5858   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5859     return SE->getCouldNotCompute();
5860
5861   return getMax();
5862 }
5863
5864 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5865   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5866     return !ENT.hasAlwaysTruePredicate();
5867   };
5868   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5869 }
5870
5871 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5872                                                     ScalarEvolution *SE) const {
5873   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5874       SE->hasOperand(getMax(), S))
5875     return true;
5876
5877   for (auto &ENT : ExitNotTaken)
5878     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5879         SE->hasOperand(ENT.ExactNotTaken, S))
5880       return true;
5881
5882   return false;
5883 }
5884
5885 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5886 /// computable exit into a persistent ExitNotTakenInfo array.
5887 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5888     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5889         &&ExitCounts,
5890     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5891     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
5892   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5893   ExitNotTaken.reserve(ExitCounts.size());
5894   std::transform(
5895       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5896       [&](const EdgeExitInfo &EEI) {
5897         BasicBlock *ExitBB = EEI.first;
5898         const ExitLimit &EL = EEI.second;
5899         if (EL.Predicates.empty())
5900           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5901
5902         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5903         for (auto *Pred : EL.Predicates)
5904           Predicate->add(Pred);
5905
5906         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5907       });
5908 }
5909
5910 /// Invalidate this result and free the ExitNotTakenInfo array.
5911 void ScalarEvolution::BackedgeTakenInfo::clear() {
5912   ExitNotTaken.clear();
5913 }
5914
5915 /// Compute the number of times the backedge of the specified loop will execute.
5916 ScalarEvolution::BackedgeTakenInfo
5917 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5918                                            bool AllowPredicates) {
5919   SmallVector<BasicBlock *, 8> ExitingBlocks;
5920   L->getExitingBlocks(ExitingBlocks);
5921
5922   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5923
5924   SmallVector<EdgeExitInfo, 4> ExitCounts;
5925   bool CouldComputeBECount = true;
5926   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5927   const SCEV *MustExitMaxBECount = nullptr;
5928   const SCEV *MayExitMaxBECount = nullptr;
5929   bool MustExitMaxOrZero = false;
5930
5931   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5932   // and compute maxBECount.
5933   // Do a union of all the predicates here.
5934   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5935     BasicBlock *ExitBB = ExitingBlocks[i];
5936     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5937
5938     assert((AllowPredicates || EL.Predicates.empty()) &&
5939            "Predicated exit limit when predicates are not allowed!");
5940
5941     // 1. For each exit that can be computed, add an entry to ExitCounts.
5942     // CouldComputeBECount is true only if all exits can be computed.
5943     if (EL.ExactNotTaken == getCouldNotCompute())
5944       // We couldn't compute an exact value for this exit, so
5945       // we won't be able to compute an exact value for the loop.
5946       CouldComputeBECount = false;
5947     else
5948       ExitCounts.emplace_back(ExitBB, EL);
5949
5950     // 2. Derive the loop's MaxBECount from each exit's max number of
5951     // non-exiting iterations. Partition the loop exits into two kinds:
5952     // LoopMustExits and LoopMayExits.
5953     //
5954     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5955     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5956     // MaxBECount is the minimum EL.MaxNotTaken of computable
5957     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5958     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5959     // computable EL.MaxNotTaken.
5960     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5961         DT.dominates(ExitBB, Latch)) {
5962       if (!MustExitMaxBECount) {
5963         MustExitMaxBECount = EL.MaxNotTaken;
5964         MustExitMaxOrZero = EL.MaxOrZero;
5965       } else {
5966         MustExitMaxBECount =
5967             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5968       }
5969     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5970       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5971         MayExitMaxBECount = EL.MaxNotTaken;
5972       else {
5973         MayExitMaxBECount =
5974             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5975       }
5976     }
5977   }
5978   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5979     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5980   // The loop backedge will be taken the maximum or zero times if there's
5981   // a single exit that must be taken the maximum or zero times.
5982   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
5983   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
5984                            MaxBECount, MaxOrZero);
5985 }
5986
5987 ScalarEvolution::ExitLimit
5988 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5989                                   bool AllowPredicates) {
5990
5991   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5992   // at this block and remember the exit block and whether all other targets
5993   // lead to the loop header.
5994   bool MustExecuteLoopHeader = true;
5995   BasicBlock *Exit = nullptr;
5996   for (auto *SBB : successors(ExitingBlock))
5997     if (!L->contains(SBB)) {
5998       if (Exit) // Multiple exit successors.
5999         return getCouldNotCompute();
6000       Exit = SBB;
6001     } else if (SBB != L->getHeader()) {
6002       MustExecuteLoopHeader = false;
6003     }
6004
6005   // At this point, we know we have a conditional branch that determines whether
6006   // the loop is exited.  However, we don't know if the branch is executed each
6007   // time through the loop.  If not, then the execution count of the branch will
6008   // not be equal to the trip count of the loop.
6009   //
6010   // Currently we check for this by checking to see if the Exit branch goes to
6011   // the loop header.  If so, we know it will always execute the same number of
6012   // times as the loop.  We also handle the case where the exit block *is* the
6013   // loop header.  This is common for un-rotated loops.
6014   //
6015   // If both of those tests fail, walk up the unique predecessor chain to the
6016   // header, stopping if there is an edge that doesn't exit the loop. If the
6017   // header is reached, the execution count of the branch will be equal to the
6018   // trip count of the loop.
6019   //
6020   //  More extensive analysis could be done to handle more cases here.
6021   //
6022   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6023     // The simple checks failed, try climbing the unique predecessor chain
6024     // up to the header.
6025     bool Ok = false;
6026     for (BasicBlock *BB = ExitingBlock; BB; ) {
6027       BasicBlock *Pred = BB->getUniquePredecessor();
6028       if (!Pred)
6029         return getCouldNotCompute();
6030       TerminatorInst *PredTerm = Pred->getTerminator();
6031       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6032         if (PredSucc == BB)
6033           continue;
6034         // If the predecessor has a successor that isn't BB and isn't
6035         // outside the loop, assume the worst.
6036         if (L->contains(PredSucc))
6037           return getCouldNotCompute();
6038       }
6039       if (Pred == L->getHeader()) {
6040         Ok = true;
6041         break;
6042       }
6043       BB = Pred;
6044     }
6045     if (!Ok)
6046       return getCouldNotCompute();
6047   }
6048
6049   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6050   TerminatorInst *Term = ExitingBlock->getTerminator();
6051   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6052     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6053     // Proceed to the next level to examine the exit condition expression.
6054     return computeExitLimitFromCond(
6055         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6056         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6057   }
6058
6059   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6060     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6061                                                 /*ControlsExit=*/IsOnlyExit);
6062
6063   return getCouldNotCompute();
6064 }
6065
6066 ScalarEvolution::ExitLimit
6067 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
6068                                           Value *ExitCond,
6069                                           BasicBlock *TBB,
6070                                           BasicBlock *FBB,
6071                                           bool ControlsExit,
6072                                           bool AllowPredicates) {
6073   // Check if the controlling expression for this loop is an And or Or.
6074   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6075     if (BO->getOpcode() == Instruction::And) {
6076       // Recurse on the operands of the and.
6077       bool EitherMayExit = L->contains(TBB);
6078       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
6079                                                ControlsExit && !EitherMayExit,
6080                                                AllowPredicates);
6081       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
6082                                                ControlsExit && !EitherMayExit,
6083                                                AllowPredicates);
6084       const SCEV *BECount = getCouldNotCompute();
6085       const SCEV *MaxBECount = getCouldNotCompute();
6086       if (EitherMayExit) {
6087         // Both conditions must be true for the loop to continue executing.
6088         // Choose the less conservative count.
6089         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6090             EL1.ExactNotTaken == getCouldNotCompute())
6091           BECount = getCouldNotCompute();
6092         else
6093           BECount =
6094               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6095         if (EL0.MaxNotTaken == getCouldNotCompute())
6096           MaxBECount = EL1.MaxNotTaken;
6097         else if (EL1.MaxNotTaken == getCouldNotCompute())
6098           MaxBECount = EL0.MaxNotTaken;
6099         else
6100           MaxBECount =
6101               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6102       } else {
6103         // Both conditions must be true at the same time for the loop to exit.
6104         // For now, be conservative.
6105         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6106         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6107           MaxBECount = EL0.MaxNotTaken;
6108         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6109           BECount = EL0.ExactNotTaken;
6110       }
6111
6112       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6113       // to be more aggressive when computing BECount than when computing
6114       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6115       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6116       // to not.
6117       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6118           !isa<SCEVCouldNotCompute>(BECount))
6119         MaxBECount = BECount;
6120
6121       return ExitLimit(BECount, MaxBECount, false,
6122                        {&EL0.Predicates, &EL1.Predicates});
6123     }
6124     if (BO->getOpcode() == Instruction::Or) {
6125       // Recurse on the operands of the or.
6126       bool EitherMayExit = L->contains(FBB);
6127       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
6128                                                ControlsExit && !EitherMayExit,
6129                                                AllowPredicates);
6130       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
6131                                                ControlsExit && !EitherMayExit,
6132                                                AllowPredicates);
6133       const SCEV *BECount = getCouldNotCompute();
6134       const SCEV *MaxBECount = getCouldNotCompute();
6135       if (EitherMayExit) {
6136         // Both conditions must be false for the loop to continue executing.
6137         // Choose the less conservative count.
6138         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6139             EL1.ExactNotTaken == getCouldNotCompute())
6140           BECount = getCouldNotCompute();
6141         else
6142           BECount =
6143               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6144         if (EL0.MaxNotTaken == getCouldNotCompute())
6145           MaxBECount = EL1.MaxNotTaken;
6146         else if (EL1.MaxNotTaken == getCouldNotCompute())
6147           MaxBECount = EL0.MaxNotTaken;
6148         else
6149           MaxBECount =
6150               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6151       } else {
6152         // Both conditions must be false at the same time for the loop to exit.
6153         // For now, be conservative.
6154         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6155         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6156           MaxBECount = EL0.MaxNotTaken;
6157         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6158           BECount = EL0.ExactNotTaken;
6159       }
6160
6161       return ExitLimit(BECount, MaxBECount, false,
6162                        {&EL0.Predicates, &EL1.Predicates});
6163     }
6164   }
6165
6166   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6167   // Proceed to the next level to examine the icmp.
6168   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6169     ExitLimit EL =
6170         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6171     if (EL.hasFullInfo() || !AllowPredicates)
6172       return EL;
6173
6174     // Try again, but use SCEV predicates this time.
6175     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6176                                     /*AllowPredicates=*/true);
6177   }
6178
6179   // Check for a constant condition. These are normally stripped out by
6180   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6181   // preserve the CFG and is temporarily leaving constant conditions
6182   // in place.
6183   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6184     if (L->contains(FBB) == !CI->getZExtValue())
6185       // The backedge is always taken.
6186       return getCouldNotCompute();
6187     else
6188       // The backedge is never taken.
6189       return getZero(CI->getType());
6190   }
6191
6192   // If it's not an integer or pointer comparison then compute it the hard way.
6193   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6194 }
6195
6196 ScalarEvolution::ExitLimit
6197 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6198                                           ICmpInst *ExitCond,
6199                                           BasicBlock *TBB,
6200                                           BasicBlock *FBB,
6201                                           bool ControlsExit,
6202                                           bool AllowPredicates) {
6203
6204   // If the condition was exit on true, convert the condition to exit on false
6205   ICmpInst::Predicate Cond;
6206   if (!L->contains(FBB))
6207     Cond = ExitCond->getPredicate();
6208   else
6209     Cond = ExitCond->getInversePredicate();
6210
6211   // Handle common loops like: for (X = "string"; *X; ++X)
6212   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6213     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6214       ExitLimit ItCnt =
6215         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6216       if (ItCnt.hasAnyInfo())
6217         return ItCnt;
6218     }
6219
6220   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6221   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6222
6223   // Try to evaluate any dependencies out of the loop.
6224   LHS = getSCEVAtScope(LHS, L);
6225   RHS = getSCEVAtScope(RHS, L);
6226
6227   // At this point, we would like to compute how many iterations of the
6228   // loop the predicate will return true for these inputs.
6229   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6230     // If there is a loop-invariant, force it into the RHS.
6231     std::swap(LHS, RHS);
6232     Cond = ICmpInst::getSwappedPredicate(Cond);
6233   }
6234
6235   // Simplify the operands before analyzing them.
6236   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6237
6238   // If we have a comparison of a chrec against a constant, try to use value
6239   // ranges to answer this query.
6240   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6241     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6242       if (AddRec->getLoop() == L) {
6243         // Form the constant range.
6244         ConstantRange CompRange =
6245             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6246
6247         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6248         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6249       }
6250
6251   switch (Cond) {
6252   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6253     // Convert to: while (X-Y != 0)
6254     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6255                                 AllowPredicates);
6256     if (EL.hasAnyInfo()) return EL;
6257     break;
6258   }
6259   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6260     // Convert to: while (X-Y == 0)
6261     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6262     if (EL.hasAnyInfo()) return EL;
6263     break;
6264   }
6265   case ICmpInst::ICMP_SLT:
6266   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6267     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6268     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6269                                     AllowPredicates);
6270     if (EL.hasAnyInfo()) return EL;
6271     break;
6272   }
6273   case ICmpInst::ICMP_SGT:
6274   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6275     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6276     ExitLimit EL =
6277         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6278                             AllowPredicates);
6279     if (EL.hasAnyInfo()) return EL;
6280     break;
6281   }
6282   default:
6283     break;
6284   }
6285
6286   auto *ExhaustiveCount =
6287       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6288
6289   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6290     return ExhaustiveCount;
6291
6292   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6293                                       ExitCond->getOperand(1), L, Cond);
6294 }
6295
6296 ScalarEvolution::ExitLimit
6297 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6298                                                       SwitchInst *Switch,
6299                                                       BasicBlock *ExitingBlock,
6300                                                       bool ControlsExit) {
6301   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6302
6303   // Give up if the exit is the default dest of a switch.
6304   if (Switch->getDefaultDest() == ExitingBlock)
6305     return getCouldNotCompute();
6306
6307   assert(L->contains(Switch->getDefaultDest()) &&
6308          "Default case must not exit the loop!");
6309   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6310   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6311
6312   // while (X != Y) --> while (X-Y != 0)
6313   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6314   if (EL.hasAnyInfo())
6315     return EL;
6316
6317   return getCouldNotCompute();
6318 }
6319
6320 static ConstantInt *
6321 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6322                                 ScalarEvolution &SE) {
6323   const SCEV *InVal = SE.getConstant(C);
6324   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6325   assert(isa<SCEVConstant>(Val) &&
6326          "Evaluation of SCEV at constant didn't fold correctly?");
6327   return cast<SCEVConstant>(Val)->getValue();
6328 }
6329
6330 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6331 /// compute the backedge execution count.
6332 ScalarEvolution::ExitLimit
6333 ScalarEvolution::computeLoadConstantCompareExitLimit(
6334   LoadInst *LI,
6335   Constant *RHS,
6336   const Loop *L,
6337   ICmpInst::Predicate predicate) {
6338
6339   if (LI->isVolatile()) return getCouldNotCompute();
6340
6341   // Check to see if the loaded pointer is a getelementptr of a global.
6342   // TODO: Use SCEV instead of manually grubbing with GEPs.
6343   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6344   if (!GEP) return getCouldNotCompute();
6345
6346   // Make sure that it is really a constant global we are gepping, with an
6347   // initializer, and make sure the first IDX is really 0.
6348   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6349   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6350       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6351       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6352     return getCouldNotCompute();
6353
6354   // Okay, we allow one non-constant index into the GEP instruction.
6355   Value *VarIdx = nullptr;
6356   std::vector<Constant*> Indexes;
6357   unsigned VarIdxNum = 0;
6358   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6359     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6360       Indexes.push_back(CI);
6361     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6362       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6363       VarIdx = GEP->getOperand(i);
6364       VarIdxNum = i-2;
6365       Indexes.push_back(nullptr);
6366     }
6367
6368   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6369   if (!VarIdx)
6370     return getCouldNotCompute();
6371
6372   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6373   // Check to see if X is a loop variant variable value now.
6374   const SCEV *Idx = getSCEV(VarIdx);
6375   Idx = getSCEVAtScope(Idx, L);
6376
6377   // We can only recognize very limited forms of loop index expressions, in
6378   // particular, only affine AddRec's like {C1,+,C2}.
6379   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6380   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6381       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6382       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6383     return getCouldNotCompute();
6384
6385   unsigned MaxSteps = MaxBruteForceIterations;
6386   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6387     ConstantInt *ItCst = ConstantInt::get(
6388                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6389     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6390
6391     // Form the GEP offset.
6392     Indexes[VarIdxNum] = Val;
6393
6394     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6395                                                          Indexes);
6396     if (!Result) break;  // Cannot compute!
6397
6398     // Evaluate the condition for this iteration.
6399     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6400     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6401     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6402       ++NumArrayLenItCounts;
6403       return getConstant(ItCst);   // Found terminating iteration!
6404     }
6405   }
6406   return getCouldNotCompute();
6407 }
6408
6409 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6410     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6411   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6412   if (!RHS)
6413     return getCouldNotCompute();
6414
6415   const BasicBlock *Latch = L->getLoopLatch();
6416   if (!Latch)
6417     return getCouldNotCompute();
6418
6419   const BasicBlock *Predecessor = L->getLoopPredecessor();
6420   if (!Predecessor)
6421     return getCouldNotCompute();
6422
6423   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6424   // Return LHS in OutLHS and shift_opt in OutOpCode.
6425   auto MatchPositiveShift =
6426       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6427
6428     using namespace PatternMatch;
6429
6430     ConstantInt *ShiftAmt;
6431     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6432       OutOpCode = Instruction::LShr;
6433     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6434       OutOpCode = Instruction::AShr;
6435     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6436       OutOpCode = Instruction::Shl;
6437     else
6438       return false;
6439
6440     return ShiftAmt->getValue().isStrictlyPositive();
6441   };
6442
6443   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6444   //
6445   // loop:
6446   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6447   //   %iv.shifted = lshr i32 %iv, <positive constant>
6448   //
6449   // Return true on a successful match.  Return the corresponding PHI node (%iv
6450   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6451   auto MatchShiftRecurrence =
6452       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6453     Optional<Instruction::BinaryOps> PostShiftOpCode;
6454
6455     {
6456       Instruction::BinaryOps OpC;
6457       Value *V;
6458
6459       // If we encounter a shift instruction, "peel off" the shift operation,
6460       // and remember that we did so.  Later when we inspect %iv's backedge
6461       // value, we will make sure that the backedge value uses the same
6462       // operation.
6463       //
6464       // Note: the peeled shift operation does not have to be the same
6465       // instruction as the one feeding into the PHI's backedge value.  We only
6466       // really care about it being the same *kind* of shift instruction --
6467       // that's all that is required for our later inferences to hold.
6468       if (MatchPositiveShift(LHS, V, OpC)) {
6469         PostShiftOpCode = OpC;
6470         LHS = V;
6471       }
6472     }
6473
6474     PNOut = dyn_cast<PHINode>(LHS);
6475     if (!PNOut || PNOut->getParent() != L->getHeader())
6476       return false;
6477
6478     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6479     Value *OpLHS;
6480
6481     return
6482         // The backedge value for the PHI node must be a shift by a positive
6483         // amount
6484         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6485
6486         // of the PHI node itself
6487         OpLHS == PNOut &&
6488
6489         // and the kind of shift should be match the kind of shift we peeled
6490         // off, if any.
6491         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6492   };
6493
6494   PHINode *PN;
6495   Instruction::BinaryOps OpCode;
6496   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6497     return getCouldNotCompute();
6498
6499   const DataLayout &DL = getDataLayout();
6500
6501   // The key rationale for this optimization is that for some kinds of shift
6502   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6503   // within a finite number of iterations.  If the condition guarding the
6504   // backedge (in the sense that the backedge is taken if the condition is true)
6505   // is false for the value the shift recurrence stabilizes to, then we know
6506   // that the backedge is taken only a finite number of times.
6507
6508   ConstantInt *StableValue = nullptr;
6509   switch (OpCode) {
6510   default:
6511     llvm_unreachable("Impossible case!");
6512
6513   case Instruction::AShr: {
6514     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6515     // bitwidth(K) iterations.
6516     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6517     bool KnownZero, KnownOne;
6518     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6519                    Predecessor->getTerminator(), &DT);
6520     auto *Ty = cast<IntegerType>(RHS->getType());
6521     if (KnownZero)
6522       StableValue = ConstantInt::get(Ty, 0);
6523     else if (KnownOne)
6524       StableValue = ConstantInt::get(Ty, -1, true);
6525     else
6526       return getCouldNotCompute();
6527
6528     break;
6529   }
6530   case Instruction::LShr:
6531   case Instruction::Shl:
6532     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6533     // stabilize to 0 in at most bitwidth(K) iterations.
6534     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6535     break;
6536   }
6537
6538   auto *Result =
6539       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6540   assert(Result->getType()->isIntegerTy(1) &&
6541          "Otherwise cannot be an operand to a branch instruction");
6542
6543   if (Result->isZeroValue()) {
6544     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6545     const SCEV *UpperBound =
6546         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6547     return ExitLimit(getCouldNotCompute(), UpperBound, false);
6548   }
6549
6550   return getCouldNotCompute();
6551 }
6552
6553 /// Return true if we can constant fold an instruction of the specified type,
6554 /// assuming that all operands were constants.
6555 static bool CanConstantFold(const Instruction *I) {
6556   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6557       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6558       isa<LoadInst>(I))
6559     return true;
6560
6561   if (const CallInst *CI = dyn_cast<CallInst>(I))
6562     if (const Function *F = CI->getCalledFunction())
6563       return canConstantFoldCallTo(F);
6564   return false;
6565 }
6566
6567 /// Determine whether this instruction can constant evolve within this loop
6568 /// assuming its operands can all constant evolve.
6569 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6570   // An instruction outside of the loop can't be derived from a loop PHI.
6571   if (!L->contains(I)) return false;
6572
6573   if (isa<PHINode>(I)) {
6574     // We don't currently keep track of the control flow needed to evaluate
6575     // PHIs, so we cannot handle PHIs inside of loops.
6576     return L->getHeader() == I->getParent();
6577   }
6578
6579   // If we won't be able to constant fold this expression even if the operands
6580   // are constants, bail early.
6581   return CanConstantFold(I);
6582 }
6583
6584 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6585 /// recursing through each instruction operand until reaching a loop header phi.
6586 static PHINode *
6587 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6588                                DenseMap<Instruction *, PHINode *> &PHIMap,
6589                                unsigned Depth) {
6590   if (Depth > MaxConstantEvolvingDepth)
6591     return nullptr;
6592
6593   // Otherwise, we can evaluate this instruction if all of its operands are
6594   // constant or derived from a PHI node themselves.
6595   PHINode *PHI = nullptr;
6596   for (Value *Op : UseInst->operands()) {
6597     if (isa<Constant>(Op)) continue;
6598
6599     Instruction *OpInst = dyn_cast<Instruction>(Op);
6600     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6601
6602     PHINode *P = dyn_cast<PHINode>(OpInst);
6603     if (!P)
6604       // If this operand is already visited, reuse the prior result.
6605       // We may have P != PHI if this is the deepest point at which the
6606       // inconsistent paths meet.
6607       P = PHIMap.lookup(OpInst);
6608     if (!P) {
6609       // Recurse and memoize the results, whether a phi is found or not.
6610       // This recursive call invalidates pointers into PHIMap.
6611       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6612       PHIMap[OpInst] = P;
6613     }
6614     if (!P)
6615       return nullptr;  // Not evolving from PHI
6616     if (PHI && PHI != P)
6617       return nullptr;  // Evolving from multiple different PHIs.
6618     PHI = P;
6619   }
6620   // This is a expression evolving from a constant PHI!
6621   return PHI;
6622 }
6623
6624 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6625 /// in the loop that V is derived from.  We allow arbitrary operations along the
6626 /// way, but the operands of an operation must either be constants or a value
6627 /// derived from a constant PHI.  If this expression does not fit with these
6628 /// constraints, return null.
6629 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6630   Instruction *I = dyn_cast<Instruction>(V);
6631   if (!I || !canConstantEvolve(I, L)) return nullptr;
6632
6633   if (PHINode *PN = dyn_cast<PHINode>(I))
6634     return PN;
6635
6636   // Record non-constant instructions contained by the loop.
6637   DenseMap<Instruction *, PHINode *> PHIMap;
6638   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6639 }
6640
6641 /// EvaluateExpression - Given an expression that passes the
6642 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6643 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6644 /// reason, return null.
6645 static Constant *EvaluateExpression(Value *V, const Loop *L,
6646                                     DenseMap<Instruction *, Constant *> &Vals,
6647                                     const DataLayout &DL,
6648                                     const TargetLibraryInfo *TLI) {
6649   // Convenient constant check, but redundant for recursive calls.
6650   if (Constant *C = dyn_cast<Constant>(V)) return C;
6651   Instruction *I = dyn_cast<Instruction>(V);
6652   if (!I) return nullptr;
6653
6654   if (Constant *C = Vals.lookup(I)) return C;
6655
6656   // An instruction inside the loop depends on a value outside the loop that we
6657   // weren't given a mapping for, or a value such as a call inside the loop.
6658   if (!canConstantEvolve(I, L)) return nullptr;
6659
6660   // An unmapped PHI can be due to a branch or another loop inside this loop,
6661   // or due to this not being the initial iteration through a loop where we
6662   // couldn't compute the evolution of this particular PHI last time.
6663   if (isa<PHINode>(I)) return nullptr;
6664
6665   std::vector<Constant*> Operands(I->getNumOperands());
6666
6667   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6668     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6669     if (!Operand) {
6670       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6671       if (!Operands[i]) return nullptr;
6672       continue;
6673     }
6674     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6675     Vals[Operand] = C;
6676     if (!C) return nullptr;
6677     Operands[i] = C;
6678   }
6679
6680   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6681     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6682                                            Operands[1], DL, TLI);
6683   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6684     if (!LI->isVolatile())
6685       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6686   }
6687   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6688 }
6689
6690
6691 // If every incoming value to PN except the one for BB is a specific Constant,
6692 // return that, else return nullptr.
6693 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6694   Constant *IncomingVal = nullptr;
6695
6696   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6697     if (PN->getIncomingBlock(i) == BB)
6698       continue;
6699
6700     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6701     if (!CurrentVal)
6702       return nullptr;
6703
6704     if (IncomingVal != CurrentVal) {
6705       if (IncomingVal)
6706         return nullptr;
6707       IncomingVal = CurrentVal;
6708     }
6709   }
6710
6711   return IncomingVal;
6712 }
6713
6714 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6715 /// in the header of its containing loop, we know the loop executes a
6716 /// constant number of times, and the PHI node is just a recurrence
6717 /// involving constants, fold it.
6718 Constant *
6719 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6720                                                    const APInt &BEs,
6721                                                    const Loop *L) {
6722   auto I = ConstantEvolutionLoopExitValue.find(PN);
6723   if (I != ConstantEvolutionLoopExitValue.end())
6724     return I->second;
6725
6726   if (BEs.ugt(MaxBruteForceIterations))
6727     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6728
6729   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6730
6731   DenseMap<Instruction *, Constant *> CurrentIterVals;
6732   BasicBlock *Header = L->getHeader();
6733   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6734
6735   BasicBlock *Latch = L->getLoopLatch();
6736   if (!Latch)
6737     return nullptr;
6738
6739   for (auto &I : *Header) {
6740     PHINode *PHI = dyn_cast<PHINode>(&I);
6741     if (!PHI) break;
6742     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6743     if (!StartCST) continue;
6744     CurrentIterVals[PHI] = StartCST;
6745   }
6746   if (!CurrentIterVals.count(PN))
6747     return RetVal = nullptr;
6748
6749   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6750
6751   // Execute the loop symbolically to determine the exit value.
6752   if (BEs.getActiveBits() >= 32)
6753     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6754
6755   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6756   unsigned IterationNum = 0;
6757   const DataLayout &DL = getDataLayout();
6758   for (; ; ++IterationNum) {
6759     if (IterationNum == NumIterations)
6760       return RetVal = CurrentIterVals[PN];  // Got exit value!
6761
6762     // Compute the value of the PHIs for the next iteration.
6763     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6764     DenseMap<Instruction *, Constant *> NextIterVals;
6765     Constant *NextPHI =
6766         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6767     if (!NextPHI)
6768       return nullptr;        // Couldn't evaluate!
6769     NextIterVals[PN] = NextPHI;
6770
6771     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6772
6773     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6774     // cease to be able to evaluate one of them or if they stop evolving,
6775     // because that doesn't necessarily prevent us from computing PN.
6776     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6777     for (const auto &I : CurrentIterVals) {
6778       PHINode *PHI = dyn_cast<PHINode>(I.first);
6779       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6780       PHIsToCompute.emplace_back(PHI, I.second);
6781     }
6782     // We use two distinct loops because EvaluateExpression may invalidate any
6783     // iterators into CurrentIterVals.
6784     for (const auto &I : PHIsToCompute) {
6785       PHINode *PHI = I.first;
6786       Constant *&NextPHI = NextIterVals[PHI];
6787       if (!NextPHI) {   // Not already computed.
6788         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6789         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6790       }
6791       if (NextPHI != I.second)
6792         StoppedEvolving = false;
6793     }
6794
6795     // If all entries in CurrentIterVals == NextIterVals then we can stop
6796     // iterating, the loop can't continue to change.
6797     if (StoppedEvolving)
6798       return RetVal = CurrentIterVals[PN];
6799
6800     CurrentIterVals.swap(NextIterVals);
6801   }
6802 }
6803
6804 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6805                                                           Value *Cond,
6806                                                           bool ExitWhen) {
6807   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6808   if (!PN) return getCouldNotCompute();
6809
6810   // If the loop is canonicalized, the PHI will have exactly two entries.
6811   // That's the only form we support here.
6812   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6813
6814   DenseMap<Instruction *, Constant *> CurrentIterVals;
6815   BasicBlock *Header = L->getHeader();
6816   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6817
6818   BasicBlock *Latch = L->getLoopLatch();
6819   assert(Latch && "Should follow from NumIncomingValues == 2!");
6820
6821   for (auto &I : *Header) {
6822     PHINode *PHI = dyn_cast<PHINode>(&I);
6823     if (!PHI)
6824       break;
6825     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6826     if (!StartCST) continue;
6827     CurrentIterVals[PHI] = StartCST;
6828   }
6829   if (!CurrentIterVals.count(PN))
6830     return getCouldNotCompute();
6831
6832   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6833   // the loop symbolically to determine when the condition gets a value of
6834   // "ExitWhen".
6835   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6836   const DataLayout &DL = getDataLayout();
6837   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6838     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6839         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6840
6841     // Couldn't symbolically evaluate.
6842     if (!CondVal) return getCouldNotCompute();
6843
6844     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6845       ++NumBruteForceTripCountsComputed;
6846       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6847     }
6848
6849     // Update all the PHI nodes for the next iteration.
6850     DenseMap<Instruction *, Constant *> NextIterVals;
6851
6852     // Create a list of which PHIs we need to compute. We want to do this before
6853     // calling EvaluateExpression on them because that may invalidate iterators
6854     // into CurrentIterVals.
6855     SmallVector<PHINode *, 8> PHIsToCompute;
6856     for (const auto &I : CurrentIterVals) {
6857       PHINode *PHI = dyn_cast<PHINode>(I.first);
6858       if (!PHI || PHI->getParent() != Header) continue;
6859       PHIsToCompute.push_back(PHI);
6860     }
6861     for (PHINode *PHI : PHIsToCompute) {
6862       Constant *&NextPHI = NextIterVals[PHI];
6863       if (NextPHI) continue;    // Already computed!
6864
6865       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6866       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6867     }
6868     CurrentIterVals.swap(NextIterVals);
6869   }
6870
6871   // Too many iterations were needed to evaluate.
6872   return getCouldNotCompute();
6873 }
6874
6875 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6876   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6877       ValuesAtScopes[V];
6878   // Check to see if we've folded this expression at this loop before.
6879   for (auto &LS : Values)
6880     if (LS.first == L)
6881       return LS.second ? LS.second : V;
6882
6883   Values.emplace_back(L, nullptr);
6884
6885   // Otherwise compute it.
6886   const SCEV *C = computeSCEVAtScope(V, L);
6887   for (auto &LS : reverse(ValuesAtScopes[V]))
6888     if (LS.first == L) {
6889       LS.second = C;
6890       break;
6891     }
6892   return C;
6893 }
6894
6895 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6896 /// will return Constants for objects which aren't represented by a
6897 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6898 /// Returns NULL if the SCEV isn't representable as a Constant.
6899 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6900   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6901     case scCouldNotCompute:
6902     case scAddRecExpr:
6903       break;
6904     case scConstant:
6905       return cast<SCEVConstant>(V)->getValue();
6906     case scUnknown:
6907       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6908     case scSignExtend: {
6909       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6910       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6911         return ConstantExpr::getSExt(CastOp, SS->getType());
6912       break;
6913     }
6914     case scZeroExtend: {
6915       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6916       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6917         return ConstantExpr::getZExt(CastOp, SZ->getType());
6918       break;
6919     }
6920     case scTruncate: {
6921       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6922       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6923         return ConstantExpr::getTrunc(CastOp, ST->getType());
6924       break;
6925     }
6926     case scAddExpr: {
6927       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6928       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6929         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6930           unsigned AS = PTy->getAddressSpace();
6931           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6932           C = ConstantExpr::getBitCast(C, DestPtrTy);
6933         }
6934         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6935           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6936           if (!C2) return nullptr;
6937
6938           // First pointer!
6939           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6940             unsigned AS = C2->getType()->getPointerAddressSpace();
6941             std::swap(C, C2);
6942             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6943             // The offsets have been converted to bytes.  We can add bytes to an
6944             // i8* by GEP with the byte count in the first index.
6945             C = ConstantExpr::getBitCast(C, DestPtrTy);
6946           }
6947
6948           // Don't bother trying to sum two pointers. We probably can't
6949           // statically compute a load that results from it anyway.
6950           if (C2->getType()->isPointerTy())
6951             return nullptr;
6952
6953           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6954             if (PTy->getElementType()->isStructTy())
6955               C2 = ConstantExpr::getIntegerCast(
6956                   C2, Type::getInt32Ty(C->getContext()), true);
6957             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6958           } else
6959             C = ConstantExpr::getAdd(C, C2);
6960         }
6961         return C;
6962       }
6963       break;
6964     }
6965     case scMulExpr: {
6966       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6967       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6968         // Don't bother with pointers at all.
6969         if (C->getType()->isPointerTy()) return nullptr;
6970         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6971           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6972           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6973           C = ConstantExpr::getMul(C, C2);
6974         }
6975         return C;
6976       }
6977       break;
6978     }
6979     case scUDivExpr: {
6980       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6981       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6982         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6983           if (LHS->getType() == RHS->getType())
6984             return ConstantExpr::getUDiv(LHS, RHS);
6985       break;
6986     }
6987     case scSMaxExpr:
6988     case scUMaxExpr:
6989       break; // TODO: smax, umax.
6990   }
6991   return nullptr;
6992 }
6993
6994 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6995   if (isa<SCEVConstant>(V)) return V;
6996
6997   // If this instruction is evolved from a constant-evolving PHI, compute the
6998   // exit value from the loop without using SCEVs.
6999   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7000     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7001       const Loop *LI = this->LI[I->getParent()];
7002       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7003         if (PHINode *PN = dyn_cast<PHINode>(I))
7004           if (PN->getParent() == LI->getHeader()) {
7005             // Okay, there is no closed form solution for the PHI node.  Check
7006             // to see if the loop that contains it has a known backedge-taken
7007             // count.  If so, we may be able to force computation of the exit
7008             // value.
7009             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7010             if (const SCEVConstant *BTCC =
7011                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7012               // Okay, we know how many times the containing loop executes.  If
7013               // this is a constant evolving PHI node, get the final value at
7014               // the specified iteration number.
7015               Constant *RV =
7016                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7017               if (RV) return getSCEV(RV);
7018             }
7019           }
7020
7021       // Okay, this is an expression that we cannot symbolically evaluate
7022       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7023       // the arguments into constants, and if so, try to constant propagate the
7024       // result.  This is particularly useful for computing loop exit values.
7025       if (CanConstantFold(I)) {
7026         SmallVector<Constant *, 4> Operands;
7027         bool MadeImprovement = false;
7028         for (Value *Op : I->operands()) {
7029           if (Constant *C = dyn_cast<Constant>(Op)) {
7030             Operands.push_back(C);
7031             continue;
7032           }
7033
7034           // If any of the operands is non-constant and if they are
7035           // non-integer and non-pointer, don't even try to analyze them
7036           // with scev techniques.
7037           if (!isSCEVable(Op->getType()))
7038             return V;
7039
7040           const SCEV *OrigV = getSCEV(Op);
7041           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7042           MadeImprovement |= OrigV != OpV;
7043
7044           Constant *C = BuildConstantFromSCEV(OpV);
7045           if (!C) return V;
7046           if (C->getType() != Op->getType())
7047             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7048                                                               Op->getType(),
7049                                                               false),
7050                                       C, Op->getType());
7051           Operands.push_back(C);
7052         }
7053
7054         // Check to see if getSCEVAtScope actually made an improvement.
7055         if (MadeImprovement) {
7056           Constant *C = nullptr;
7057           const DataLayout &DL = getDataLayout();
7058           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7059             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7060                                                 Operands[1], DL, &TLI);
7061           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7062             if (!LI->isVolatile())
7063               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7064           } else
7065             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7066           if (!C) return V;
7067           return getSCEV(C);
7068         }
7069       }
7070     }
7071
7072     // This is some other type of SCEVUnknown, just return it.
7073     return V;
7074   }
7075
7076   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7077     // Avoid performing the look-up in the common case where the specified
7078     // expression has no loop-variant portions.
7079     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7080       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7081       if (OpAtScope != Comm->getOperand(i)) {
7082         // Okay, at least one of these operands is loop variant but might be
7083         // foldable.  Build a new instance of the folded commutative expression.
7084         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7085                                             Comm->op_begin()+i);
7086         NewOps.push_back(OpAtScope);
7087
7088         for (++i; i != e; ++i) {
7089           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7090           NewOps.push_back(OpAtScope);
7091         }
7092         if (isa<SCEVAddExpr>(Comm))
7093           return getAddExpr(NewOps);
7094         if (isa<SCEVMulExpr>(Comm))
7095           return getMulExpr(NewOps);
7096         if (isa<SCEVSMaxExpr>(Comm))
7097           return getSMaxExpr(NewOps);
7098         if (isa<SCEVUMaxExpr>(Comm))
7099           return getUMaxExpr(NewOps);
7100         llvm_unreachable("Unknown commutative SCEV type!");
7101       }
7102     }
7103     // If we got here, all operands are loop invariant.
7104     return Comm;
7105   }
7106
7107   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7108     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7109     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7110     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7111       return Div;   // must be loop invariant
7112     return getUDivExpr(LHS, RHS);
7113   }
7114
7115   // If this is a loop recurrence for a loop that does not contain L, then we
7116   // are dealing with the final value computed by the loop.
7117   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7118     // First, attempt to evaluate each operand.
7119     // Avoid performing the look-up in the common case where the specified
7120     // expression has no loop-variant portions.
7121     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7122       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7123       if (OpAtScope == AddRec->getOperand(i))
7124         continue;
7125
7126       // Okay, at least one of these operands is loop variant but might be
7127       // foldable.  Build a new instance of the folded commutative expression.
7128       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7129                                           AddRec->op_begin()+i);
7130       NewOps.push_back(OpAtScope);
7131       for (++i; i != e; ++i)
7132         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7133
7134       const SCEV *FoldedRec =
7135         getAddRecExpr(NewOps, AddRec->getLoop(),
7136                       AddRec->getNoWrapFlags(SCEV::FlagNW));
7137       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7138       // The addrec may be folded to a nonrecurrence, for example, if the
7139       // induction variable is multiplied by zero after constant folding. Go
7140       // ahead and return the folded value.
7141       if (!AddRec)
7142         return FoldedRec;
7143       break;
7144     }
7145
7146     // If the scope is outside the addrec's loop, evaluate it by using the
7147     // loop exit value of the addrec.
7148     if (!AddRec->getLoop()->contains(L)) {
7149       // To evaluate this recurrence, we need to know how many times the AddRec
7150       // loop iterates.  Compute this now.
7151       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7152       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7153
7154       // Then, evaluate the AddRec.
7155       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7156     }
7157
7158     return AddRec;
7159   }
7160
7161   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7162     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7163     if (Op == Cast->getOperand())
7164       return Cast;  // must be loop invariant
7165     return getZeroExtendExpr(Op, Cast->getType());
7166   }
7167
7168   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7169     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7170     if (Op == Cast->getOperand())
7171       return Cast;  // must be loop invariant
7172     return getSignExtendExpr(Op, Cast->getType());
7173   }
7174
7175   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7176     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7177     if (Op == Cast->getOperand())
7178       return Cast;  // must be loop invariant
7179     return getTruncateExpr(Op, Cast->getType());
7180   }
7181
7182   llvm_unreachable("Unknown SCEV type!");
7183 }
7184
7185 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7186   return getSCEVAtScope(getSCEV(V), L);
7187 }
7188
7189 /// Finds the minimum unsigned root of the following equation:
7190 ///
7191 ///     A * X = B (mod N)
7192 ///
7193 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7194 /// A and B isn't important.
7195 ///
7196 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7197 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7198                                                ScalarEvolution &SE) {
7199   uint32_t BW = A.getBitWidth();
7200   assert(BW == SE.getTypeSizeInBits(B->getType()));
7201   assert(A != 0 && "A must be non-zero.");
7202
7203   // 1. D = gcd(A, N)
7204   //
7205   // The gcd of A and N may have only one prime factor: 2. The number of
7206   // trailing zeros in A is its multiplicity
7207   uint32_t Mult2 = A.countTrailingZeros();
7208   // D = 2^Mult2
7209
7210   // 2. Check if B is divisible by D.
7211   //
7212   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7213   // is not less than multiplicity of this prime factor for D.
7214   if (SE.GetMinTrailingZeros(B) < Mult2)
7215     return SE.getCouldNotCompute();
7216
7217   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7218   // modulo (N / D).
7219   //
7220   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7221   // (N / D) in general. The inverse itself always fits into BW bits, though,
7222   // so we immediately truncate it.
7223   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7224   APInt Mod(BW + 1, 0);
7225   Mod.setBit(BW - Mult2);  // Mod = N / D
7226   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7227
7228   // 4. Compute the minimum unsigned root of the equation:
7229   // I * (B / D) mod (N / D)
7230   // To simplify the computation, we factor out the divide by D:
7231   // (I * B mod N) / D
7232   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7233   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7234 }
7235
7236 /// Find the roots of the quadratic equation for the given quadratic chrec
7237 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7238 /// two SCEVCouldNotCompute objects.
7239 ///
7240 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7241 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7242   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7243   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7244   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7245   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7246
7247   // We currently can only solve this if the coefficients are constants.
7248   if (!LC || !MC || !NC)
7249     return None;
7250
7251   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7252   const APInt &L = LC->getAPInt();
7253   const APInt &M = MC->getAPInt();
7254   const APInt &N = NC->getAPInt();
7255   APInt Two(BitWidth, 2);
7256   APInt Four(BitWidth, 4);
7257
7258   {
7259     using namespace APIntOps;
7260     const APInt& C = L;
7261     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7262     // The B coefficient is M-N/2
7263     APInt B(M);
7264     B -= N.sdiv(Two);
7265
7266     // The A coefficient is N/2
7267     APInt A(N.sdiv(Two));
7268
7269     // Compute the B^2-4ac term.
7270     APInt SqrtTerm(B);
7271     SqrtTerm *= B;
7272     SqrtTerm -= Four * (A * C);
7273
7274     if (SqrtTerm.isNegative()) {
7275       // The loop is provably infinite.
7276       return None;
7277     }
7278
7279     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7280     // integer value or else APInt::sqrt() will assert.
7281     APInt SqrtVal(SqrtTerm.sqrt());
7282
7283     // Compute the two solutions for the quadratic formula.
7284     // The divisions must be performed as signed divisions.
7285     APInt NegB(-B);
7286     APInt TwoA(A << 1);
7287     if (TwoA.isMinValue())
7288       return None;
7289
7290     LLVMContext &Context = SE.getContext();
7291
7292     ConstantInt *Solution1 =
7293       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7294     ConstantInt *Solution2 =
7295       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7296
7297     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7298                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7299   } // end APIntOps namespace
7300 }
7301
7302 ScalarEvolution::ExitLimit
7303 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7304                               bool AllowPredicates) {
7305
7306   // This is only used for loops with a "x != y" exit test. The exit condition
7307   // is now expressed as a single expression, V = x-y. So the exit test is
7308   // effectively V != 0.  We know and take advantage of the fact that this
7309   // expression only being used in a comparison by zero context.
7310
7311   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7312   // If the value is a constant
7313   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7314     // If the value is already zero, the branch will execute zero times.
7315     if (C->getValue()->isZero()) return C;
7316     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7317   }
7318
7319   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7320   if (!AddRec && AllowPredicates)
7321     // Try to make this an AddRec using runtime tests, in the first X
7322     // iterations of this loop, where X is the SCEV expression found by the
7323     // algorithm below.
7324     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7325
7326   if (!AddRec || AddRec->getLoop() != L)
7327     return getCouldNotCompute();
7328
7329   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7330   // the quadratic equation to solve it.
7331   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7332     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7333       const SCEVConstant *R1 = Roots->first;
7334       const SCEVConstant *R2 = Roots->second;
7335       // Pick the smallest positive root value.
7336       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7337               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7338         if (!CB->getZExtValue())
7339           std::swap(R1, R2); // R1 is the minimum root now.
7340
7341         // We can only use this value if the chrec ends up with an exact zero
7342         // value at this index.  When solving for "X*X != 5", for example, we
7343         // should not accept a root of 2.
7344         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7345         if (Val->isZero())
7346           // We found a quadratic root!
7347           return ExitLimit(R1, R1, false, Predicates);
7348       }
7349     }
7350     return getCouldNotCompute();
7351   }
7352
7353   // Otherwise we can only handle this if it is affine.
7354   if (!AddRec->isAffine())
7355     return getCouldNotCompute();
7356
7357   // If this is an affine expression, the execution count of this branch is
7358   // the minimum unsigned root of the following equation:
7359   //
7360   //     Start + Step*N = 0 (mod 2^BW)
7361   //
7362   // equivalent to:
7363   //
7364   //             Step*N = -Start (mod 2^BW)
7365   //
7366   // where BW is the common bit width of Start and Step.
7367
7368   // Get the initial value for the loop.
7369   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7370   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7371
7372   // For now we handle only constant steps.
7373   //
7374   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7375   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7376   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7377   // We have not yet seen any such cases.
7378   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7379   if (!StepC || StepC->getValue()->equalsInt(0))
7380     return getCouldNotCompute();
7381
7382   // For positive steps (counting up until unsigned overflow):
7383   //   N = -Start/Step (as unsigned)
7384   // For negative steps (counting down to zero):
7385   //   N = Start/-Step
7386   // First compute the unsigned distance from zero in the direction of Step.
7387   bool CountDown = StepC->getAPInt().isNegative();
7388   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7389
7390   // Handle unitary steps, which cannot wraparound.
7391   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7392   //   N = Distance (as unsigned)
7393   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7394     APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7395
7396     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7397     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
7398     // case, and see if we can improve the bound.
7399     //
7400     // Explicitly handling this here is necessary because getUnsignedRange
7401     // isn't context-sensitive; it doesn't know that we only care about the
7402     // range inside the loop.
7403     const SCEV *Zero = getZero(Distance->getType());
7404     const SCEV *One = getOne(Distance->getType());
7405     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7406     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7407       // If Distance + 1 doesn't overflow, we can compute the maximum distance
7408       // as "unsigned_max(Distance + 1) - 1".
7409       ConstantRange CR = getUnsignedRange(DistancePlusOne);
7410       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7411     }
7412     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7413   }
7414
7415   // If the condition controls loop exit (the loop exits only if the expression
7416   // is true) and the addition is no-wrap we can use unsigned divide to
7417   // compute the backedge count.  In this case, the step may not divide the
7418   // distance, but we don't care because if the condition is "missed" the loop
7419   // will have undefined behavior due to wrapping.
7420   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7421       loopHasNoAbnormalExits(AddRec->getLoop())) {
7422     const SCEV *Exact =
7423         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7424     return ExitLimit(Exact, Exact, false, Predicates);
7425   }
7426
7427   // Solve the general equation.
7428   const SCEV *E = SolveLinEquationWithOverflow(
7429       StepC->getAPInt(), getNegativeSCEV(Start), *this);
7430   return ExitLimit(E, E, false, Predicates);
7431 }
7432
7433 ScalarEvolution::ExitLimit
7434 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7435   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7436   // handle them yet except for the trivial case.  This could be expanded in the
7437   // future as needed.
7438
7439   // If the value is a constant, check to see if it is known to be non-zero
7440   // already.  If so, the backedge will execute zero times.
7441   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7442     if (!C->getValue()->isNullValue())
7443       return getZero(C->getType());
7444     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7445   }
7446
7447   // We could implement others, but I really doubt anyone writes loops like
7448   // this, and if they did, they would already be constant folded.
7449   return getCouldNotCompute();
7450 }
7451
7452 std::pair<BasicBlock *, BasicBlock *>
7453 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7454   // If the block has a unique predecessor, then there is no path from the
7455   // predecessor to the block that does not go through the direct edge
7456   // from the predecessor to the block.
7457   if (BasicBlock *Pred = BB->getSinglePredecessor())
7458     return {Pred, BB};
7459
7460   // A loop's header is defined to be a block that dominates the loop.
7461   // If the header has a unique predecessor outside the loop, it must be
7462   // a block that has exactly one successor that can reach the loop.
7463   if (Loop *L = LI.getLoopFor(BB))
7464     return {L->getLoopPredecessor(), L->getHeader()};
7465
7466   return {nullptr, nullptr};
7467 }
7468
7469 /// SCEV structural equivalence is usually sufficient for testing whether two
7470 /// expressions are equal, however for the purposes of looking for a condition
7471 /// guarding a loop, it can be useful to be a little more general, since a
7472 /// front-end may have replicated the controlling expression.
7473 ///
7474 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7475   // Quick check to see if they are the same SCEV.
7476   if (A == B) return true;
7477
7478   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7479     // Not all instructions that are "identical" compute the same value.  For
7480     // instance, two distinct alloca instructions allocating the same type are
7481     // identical and do not read memory; but compute distinct values.
7482     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7483   };
7484
7485   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7486   // two different instructions with the same value. Check for this case.
7487   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7488     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7489       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7490         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7491           if (ComputesEqualValues(AI, BI))
7492             return true;
7493
7494   // Otherwise assume they may have a different value.
7495   return false;
7496 }
7497
7498 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7499                                            const SCEV *&LHS, const SCEV *&RHS,
7500                                            unsigned Depth) {
7501   bool Changed = false;
7502
7503   // If we hit the max recursion limit bail out.
7504   if (Depth >= 3)
7505     return false;
7506
7507   // Canonicalize a constant to the right side.
7508   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7509     // Check for both operands constant.
7510     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7511       if (ConstantExpr::getICmp(Pred,
7512                                 LHSC->getValue(),
7513                                 RHSC->getValue())->isNullValue())
7514         goto trivially_false;
7515       else
7516         goto trivially_true;
7517     }
7518     // Otherwise swap the operands to put the constant on the right.
7519     std::swap(LHS, RHS);
7520     Pred = ICmpInst::getSwappedPredicate(Pred);
7521     Changed = true;
7522   }
7523
7524   // If we're comparing an addrec with a value which is loop-invariant in the
7525   // addrec's loop, put the addrec on the left. Also make a dominance check,
7526   // as both operands could be addrecs loop-invariant in each other's loop.
7527   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7528     const Loop *L = AR->getLoop();
7529     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7530       std::swap(LHS, RHS);
7531       Pred = ICmpInst::getSwappedPredicate(Pred);
7532       Changed = true;
7533     }
7534   }
7535
7536   // If there's a constant operand, canonicalize comparisons with boundary
7537   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7538   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7539     const APInt &RA = RC->getAPInt();
7540
7541     bool SimplifiedByConstantRange = false;
7542
7543     if (!ICmpInst::isEquality(Pred)) {
7544       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7545       if (ExactCR.isFullSet())
7546         goto trivially_true;
7547       else if (ExactCR.isEmptySet())
7548         goto trivially_false;
7549
7550       APInt NewRHS;
7551       CmpInst::Predicate NewPred;
7552       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7553           ICmpInst::isEquality(NewPred)) {
7554         // We were able to convert an inequality to an equality.
7555         Pred = NewPred;
7556         RHS = getConstant(NewRHS);
7557         Changed = SimplifiedByConstantRange = true;
7558       }
7559     }
7560
7561     if (!SimplifiedByConstantRange) {
7562       switch (Pred) {
7563       default:
7564         break;
7565       case ICmpInst::ICMP_EQ:
7566       case ICmpInst::ICMP_NE:
7567         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7568         if (!RA)
7569           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7570             if (const SCEVMulExpr *ME =
7571                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7572               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7573                   ME->getOperand(0)->isAllOnesValue()) {
7574                 RHS = AE->getOperand(1);
7575                 LHS = ME->getOperand(1);
7576                 Changed = true;
7577               }
7578         break;
7579
7580
7581         // The "Should have been caught earlier!" messages refer to the fact
7582         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7583         // should have fired on the corresponding cases, and canonicalized the
7584         // check to trivially_true or trivially_false.
7585
7586       case ICmpInst::ICMP_UGE:
7587         assert(!RA.isMinValue() && "Should have been caught earlier!");
7588         Pred = ICmpInst::ICMP_UGT;
7589         RHS = getConstant(RA - 1);
7590         Changed = true;
7591         break;
7592       case ICmpInst::ICMP_ULE:
7593         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7594         Pred = ICmpInst::ICMP_ULT;
7595         RHS = getConstant(RA + 1);
7596         Changed = true;
7597         break;
7598       case ICmpInst::ICMP_SGE:
7599         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7600         Pred = ICmpInst::ICMP_SGT;
7601         RHS = getConstant(RA - 1);
7602         Changed = true;
7603         break;
7604       case ICmpInst::ICMP_SLE:
7605         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7606         Pred = ICmpInst::ICMP_SLT;
7607         RHS = getConstant(RA + 1);
7608         Changed = true;
7609         break;
7610       }
7611     }
7612   }
7613
7614   // Check for obvious equality.
7615   if (HasSameValue(LHS, RHS)) {
7616     if (ICmpInst::isTrueWhenEqual(Pred))
7617       goto trivially_true;
7618     if (ICmpInst::isFalseWhenEqual(Pred))
7619       goto trivially_false;
7620   }
7621
7622   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7623   // adding or subtracting 1 from one of the operands.
7624   switch (Pred) {
7625   case ICmpInst::ICMP_SLE:
7626     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7627       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7628                        SCEV::FlagNSW);
7629       Pred = ICmpInst::ICMP_SLT;
7630       Changed = true;
7631     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7632       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7633                        SCEV::FlagNSW);
7634       Pred = ICmpInst::ICMP_SLT;
7635       Changed = true;
7636     }
7637     break;
7638   case ICmpInst::ICMP_SGE:
7639     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7640       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7641                        SCEV::FlagNSW);
7642       Pred = ICmpInst::ICMP_SGT;
7643       Changed = true;
7644     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7645       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7646                        SCEV::FlagNSW);
7647       Pred = ICmpInst::ICMP_SGT;
7648       Changed = true;
7649     }
7650     break;
7651   case ICmpInst::ICMP_ULE:
7652     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7653       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7654                        SCEV::FlagNUW);
7655       Pred = ICmpInst::ICMP_ULT;
7656       Changed = true;
7657     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7658       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7659       Pred = ICmpInst::ICMP_ULT;
7660       Changed = true;
7661     }
7662     break;
7663   case ICmpInst::ICMP_UGE:
7664     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7665       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7666       Pred = ICmpInst::ICMP_UGT;
7667       Changed = true;
7668     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7669       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7670                        SCEV::FlagNUW);
7671       Pred = ICmpInst::ICMP_UGT;
7672       Changed = true;
7673     }
7674     break;
7675   default:
7676     break;
7677   }
7678
7679   // TODO: More simplifications are possible here.
7680
7681   // Recursively simplify until we either hit a recursion limit or nothing
7682   // changes.
7683   if (Changed)
7684     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7685
7686   return Changed;
7687
7688 trivially_true:
7689   // Return 0 == 0.
7690   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7691   Pred = ICmpInst::ICMP_EQ;
7692   return true;
7693
7694 trivially_false:
7695   // Return 0 != 0.
7696   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7697   Pred = ICmpInst::ICMP_NE;
7698   return true;
7699 }
7700
7701 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7702   return getSignedRange(S).getSignedMax().isNegative();
7703 }
7704
7705 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7706   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7707 }
7708
7709 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7710   return !getSignedRange(S).getSignedMin().isNegative();
7711 }
7712
7713 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7714   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7715 }
7716
7717 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7718   return isKnownNegative(S) || isKnownPositive(S);
7719 }
7720
7721 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7722                                        const SCEV *LHS, const SCEV *RHS) {
7723   // Canonicalize the inputs first.
7724   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7725
7726   // If LHS or RHS is an addrec, check to see if the condition is true in
7727   // every iteration of the loop.
7728   // If LHS and RHS are both addrec, both conditions must be true in
7729   // every iteration of the loop.
7730   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7731   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7732   bool LeftGuarded = false;
7733   bool RightGuarded = false;
7734   if (LAR) {
7735     const Loop *L = LAR->getLoop();
7736     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7737         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7738       if (!RAR) return true;
7739       LeftGuarded = true;
7740     }
7741   }
7742   if (RAR) {
7743     const Loop *L = RAR->getLoop();
7744     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7745         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7746       if (!LAR) return true;
7747       RightGuarded = true;
7748     }
7749   }
7750   if (LeftGuarded && RightGuarded)
7751     return true;
7752
7753   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7754     return true;
7755
7756   // Otherwise see what can be done with known constant ranges.
7757   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7758 }
7759
7760 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7761                                            ICmpInst::Predicate Pred,
7762                                            bool &Increasing) {
7763   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7764
7765 #ifndef NDEBUG
7766   // Verify an invariant: inverting the predicate should turn a monotonically
7767   // increasing change to a monotonically decreasing one, and vice versa.
7768   bool IncreasingSwapped;
7769   bool ResultSwapped = isMonotonicPredicateImpl(
7770       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7771
7772   assert(Result == ResultSwapped && "should be able to analyze both!");
7773   if (ResultSwapped)
7774     assert(Increasing == !IncreasingSwapped &&
7775            "monotonicity should flip as we flip the predicate");
7776 #endif
7777
7778   return Result;
7779 }
7780
7781 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7782                                                ICmpInst::Predicate Pred,
7783                                                bool &Increasing) {
7784
7785   // A zero step value for LHS means the induction variable is essentially a
7786   // loop invariant value. We don't really depend on the predicate actually
7787   // flipping from false to true (for increasing predicates, and the other way
7788   // around for decreasing predicates), all we care about is that *if* the
7789   // predicate changes then it only changes from false to true.
7790   //
7791   // A zero step value in itself is not very useful, but there may be places
7792   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7793   // as general as possible.
7794
7795   switch (Pred) {
7796   default:
7797     return false; // Conservative answer
7798
7799   case ICmpInst::ICMP_UGT:
7800   case ICmpInst::ICMP_UGE:
7801   case ICmpInst::ICMP_ULT:
7802   case ICmpInst::ICMP_ULE:
7803     if (!LHS->hasNoUnsignedWrap())
7804       return false;
7805
7806     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7807     return true;
7808
7809   case ICmpInst::ICMP_SGT:
7810   case ICmpInst::ICMP_SGE:
7811   case ICmpInst::ICMP_SLT:
7812   case ICmpInst::ICMP_SLE: {
7813     if (!LHS->hasNoSignedWrap())
7814       return false;
7815
7816     const SCEV *Step = LHS->getStepRecurrence(*this);
7817
7818     if (isKnownNonNegative(Step)) {
7819       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7820       return true;
7821     }
7822
7823     if (isKnownNonPositive(Step)) {
7824       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7825       return true;
7826     }
7827
7828     return false;
7829   }
7830
7831   }
7832
7833   llvm_unreachable("switch has default clause!");
7834 }
7835
7836 bool ScalarEvolution::isLoopInvariantPredicate(
7837     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7838     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7839     const SCEV *&InvariantRHS) {
7840
7841   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7842   if (!isLoopInvariant(RHS, L)) {
7843     if (!isLoopInvariant(LHS, L))
7844       return false;
7845
7846     std::swap(LHS, RHS);
7847     Pred = ICmpInst::getSwappedPredicate(Pred);
7848   }
7849
7850   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7851   if (!ArLHS || ArLHS->getLoop() != L)
7852     return false;
7853
7854   bool Increasing;
7855   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7856     return false;
7857
7858   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7859   // true as the loop iterates, and the backedge is control dependent on
7860   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7861   //
7862   //   * if the predicate was false in the first iteration then the predicate
7863   //     is never evaluated again, since the loop exits without taking the
7864   //     backedge.
7865   //   * if the predicate was true in the first iteration then it will
7866   //     continue to be true for all future iterations since it is
7867   //     monotonically increasing.
7868   //
7869   // For both the above possibilities, we can replace the loop varying
7870   // predicate with its value on the first iteration of the loop (which is
7871   // loop invariant).
7872   //
7873   // A similar reasoning applies for a monotonically decreasing predicate, by
7874   // replacing true with false and false with true in the above two bullets.
7875
7876   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7877
7878   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7879     return false;
7880
7881   InvariantPred = Pred;
7882   InvariantLHS = ArLHS->getStart();
7883   InvariantRHS = RHS;
7884   return true;
7885 }
7886
7887 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7888     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7889   if (HasSameValue(LHS, RHS))
7890     return ICmpInst::isTrueWhenEqual(Pred);
7891
7892   // This code is split out from isKnownPredicate because it is called from
7893   // within isLoopEntryGuardedByCond.
7894
7895   auto CheckRanges =
7896       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7897     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7898         .contains(RangeLHS);
7899   };
7900
7901   // The check at the top of the function catches the case where the values are
7902   // known to be equal.
7903   if (Pred == CmpInst::ICMP_EQ)
7904     return false;
7905
7906   if (Pred == CmpInst::ICMP_NE)
7907     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7908            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7909            isKnownNonZero(getMinusSCEV(LHS, RHS));
7910
7911   if (CmpInst::isSigned(Pred))
7912     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7913
7914   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7915 }
7916
7917 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7918                                                     const SCEV *LHS,
7919                                                     const SCEV *RHS) {
7920
7921   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7922   // Return Y via OutY.
7923   auto MatchBinaryAddToConst =
7924       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7925              SCEV::NoWrapFlags ExpectedFlags) {
7926     const SCEV *NonConstOp, *ConstOp;
7927     SCEV::NoWrapFlags FlagsPresent;
7928
7929     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7930         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7931       return false;
7932
7933     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7934     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7935   };
7936
7937   APInt C;
7938
7939   switch (Pred) {
7940   default:
7941     break;
7942
7943   case ICmpInst::ICMP_SGE:
7944     std::swap(LHS, RHS);
7945   case ICmpInst::ICMP_SLE:
7946     // X s<= (X + C)<nsw> if C >= 0
7947     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7948       return true;
7949
7950     // (X + C)<nsw> s<= X if C <= 0
7951     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7952         !C.isStrictlyPositive())
7953       return true;
7954     break;
7955
7956   case ICmpInst::ICMP_SGT:
7957     std::swap(LHS, RHS);
7958   case ICmpInst::ICMP_SLT:
7959     // X s< (X + C)<nsw> if C > 0
7960     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7961         C.isStrictlyPositive())
7962       return true;
7963
7964     // (X + C)<nsw> s< X if C < 0
7965     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7966       return true;
7967     break;
7968   }
7969
7970   return false;
7971 }
7972
7973 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7974                                                    const SCEV *LHS,
7975                                                    const SCEV *RHS) {
7976   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7977     return false;
7978
7979   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7980   // the stack can result in exponential time complexity.
7981   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7982
7983   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7984   //
7985   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7986   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7987   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7988   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7989   // use isKnownPredicate later if needed.
7990   return isKnownNonNegative(RHS) &&
7991          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7992          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7993 }
7994
7995 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7996                                         ICmpInst::Predicate Pred,
7997                                         const SCEV *LHS, const SCEV *RHS) {
7998   // No need to even try if we know the module has no guards.
7999   if (!HasGuards)
8000     return false;
8001
8002   return any_of(*BB, [&](Instruction &I) {
8003     using namespace llvm::PatternMatch;
8004
8005     Value *Condition;
8006     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8007                          m_Value(Condition))) &&
8008            isImpliedCond(Pred, LHS, RHS, Condition, false);
8009   });
8010 }
8011
8012 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8013 /// protected by a conditional between LHS and RHS.  This is used to
8014 /// to eliminate casts.
8015 bool
8016 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8017                                              ICmpInst::Predicate Pred,
8018                                              const SCEV *LHS, const SCEV *RHS) {
8019   // Interpret a null as meaning no loop, where there is obviously no guard
8020   // (interprocedural conditions notwithstanding).
8021   if (!L) return true;
8022
8023   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8024     return true;
8025
8026   BasicBlock *Latch = L->getLoopLatch();
8027   if (!Latch)
8028     return false;
8029
8030   BranchInst *LoopContinuePredicate =
8031     dyn_cast<BranchInst>(Latch->getTerminator());
8032   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8033       isImpliedCond(Pred, LHS, RHS,
8034                     LoopContinuePredicate->getCondition(),
8035                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8036     return true;
8037
8038   // We don't want more than one activation of the following loops on the stack
8039   // -- that can lead to O(n!) time complexity.
8040   if (WalkingBEDominatingConds)
8041     return false;
8042
8043   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8044
8045   // See if we can exploit a trip count to prove the predicate.
8046   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8047   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8048   if (LatchBECount != getCouldNotCompute()) {
8049     // We know that Latch branches back to the loop header exactly
8050     // LatchBECount times.  This means the backdege condition at Latch is
8051     // equivalent to  "{0,+,1} u< LatchBECount".
8052     Type *Ty = LatchBECount->getType();
8053     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8054     const SCEV *LoopCounter =
8055       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8056     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8057                       LatchBECount))
8058       return true;
8059   }
8060
8061   // Check conditions due to any @llvm.assume intrinsics.
8062   for (auto &AssumeVH : AC.assumptions()) {
8063     if (!AssumeVH)
8064       continue;
8065     auto *CI = cast<CallInst>(AssumeVH);
8066     if (!DT.dominates(CI, Latch->getTerminator()))
8067       continue;
8068
8069     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8070       return true;
8071   }
8072
8073   // If the loop is not reachable from the entry block, we risk running into an
8074   // infinite loop as we walk up into the dom tree.  These loops do not matter
8075   // anyway, so we just return a conservative answer when we see them.
8076   if (!DT.isReachableFromEntry(L->getHeader()))
8077     return false;
8078
8079   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8080     return true;
8081
8082   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8083        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8084
8085     assert(DTN && "should reach the loop header before reaching the root!");
8086
8087     BasicBlock *BB = DTN->getBlock();
8088     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8089       return true;
8090
8091     BasicBlock *PBB = BB->getSinglePredecessor();
8092     if (!PBB)
8093       continue;
8094
8095     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8096     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8097       continue;
8098
8099     Value *Condition = ContinuePredicate->getCondition();
8100
8101     // If we have an edge `E` within the loop body that dominates the only
8102     // latch, the condition guarding `E` also guards the backedge.  This
8103     // reasoning works only for loops with a single latch.
8104
8105     BasicBlockEdge DominatingEdge(PBB, BB);
8106     if (DominatingEdge.isSingleEdge()) {
8107       // We're constructively (and conservatively) enumerating edges within the
8108       // loop body that dominate the latch.  The dominator tree better agree
8109       // with us on this:
8110       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8111
8112       if (isImpliedCond(Pred, LHS, RHS, Condition,
8113                         BB != ContinuePredicate->getSuccessor(0)))
8114         return true;
8115     }
8116   }
8117
8118   return false;
8119 }
8120
8121 bool
8122 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8123                                           ICmpInst::Predicate Pred,
8124                                           const SCEV *LHS, const SCEV *RHS) {
8125   // Interpret a null as meaning no loop, where there is obviously no guard
8126   // (interprocedural conditions notwithstanding).
8127   if (!L) return false;
8128
8129   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8130     return true;
8131
8132   // Starting at the loop predecessor, climb up the predecessor chain, as long
8133   // as there are predecessors that can be found that have unique successors
8134   // leading to the original header.
8135   for (std::pair<BasicBlock *, BasicBlock *>
8136          Pair(L->getLoopPredecessor(), L->getHeader());
8137        Pair.first;
8138        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8139
8140     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8141       return true;
8142
8143     BranchInst *LoopEntryPredicate =
8144       dyn_cast<BranchInst>(Pair.first->getTerminator());
8145     if (!LoopEntryPredicate ||
8146         LoopEntryPredicate->isUnconditional())
8147       continue;
8148
8149     if (isImpliedCond(Pred, LHS, RHS,
8150                       LoopEntryPredicate->getCondition(),
8151                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8152       return true;
8153   }
8154
8155   // Check conditions due to any @llvm.assume intrinsics.
8156   for (auto &AssumeVH : AC.assumptions()) {
8157     if (!AssumeVH)
8158       continue;
8159     auto *CI = cast<CallInst>(AssumeVH);
8160     if (!DT.dominates(CI, L->getHeader()))
8161       continue;
8162
8163     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8164       return true;
8165   }
8166
8167   return false;
8168 }
8169
8170 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8171                                     const SCEV *LHS, const SCEV *RHS,
8172                                     Value *FoundCondValue,
8173                                     bool Inverse) {
8174   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8175     return false;
8176
8177   auto ClearOnExit =
8178       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8179
8180   // Recursively handle And and Or conditions.
8181   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8182     if (BO->getOpcode() == Instruction::And) {
8183       if (!Inverse)
8184         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8185                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8186     } else if (BO->getOpcode() == Instruction::Or) {
8187       if (Inverse)
8188         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8189                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8190     }
8191   }
8192
8193   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8194   if (!ICI) return false;
8195
8196   // Now that we found a conditional branch that dominates the loop or controls
8197   // the loop latch. Check to see if it is the comparison we are looking for.
8198   ICmpInst::Predicate FoundPred;
8199   if (Inverse)
8200     FoundPred = ICI->getInversePredicate();
8201   else
8202     FoundPred = ICI->getPredicate();
8203
8204   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8205   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8206
8207   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8208 }
8209
8210 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8211                                     const SCEV *RHS,
8212                                     ICmpInst::Predicate FoundPred,
8213                                     const SCEV *FoundLHS,
8214                                     const SCEV *FoundRHS) {
8215   // Balance the types.
8216   if (getTypeSizeInBits(LHS->getType()) <
8217       getTypeSizeInBits(FoundLHS->getType())) {
8218     if (CmpInst::isSigned(Pred)) {
8219       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8220       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8221     } else {
8222       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8223       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8224     }
8225   } else if (getTypeSizeInBits(LHS->getType()) >
8226       getTypeSizeInBits(FoundLHS->getType())) {
8227     if (CmpInst::isSigned(FoundPred)) {
8228       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8229       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8230     } else {
8231       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8232       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8233     }
8234   }
8235
8236   // Canonicalize the query to match the way instcombine will have
8237   // canonicalized the comparison.
8238   if (SimplifyICmpOperands(Pred, LHS, RHS))
8239     if (LHS == RHS)
8240       return CmpInst::isTrueWhenEqual(Pred);
8241   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8242     if (FoundLHS == FoundRHS)
8243       return CmpInst::isFalseWhenEqual(FoundPred);
8244
8245   // Check to see if we can make the LHS or RHS match.
8246   if (LHS == FoundRHS || RHS == FoundLHS) {
8247     if (isa<SCEVConstant>(RHS)) {
8248       std::swap(FoundLHS, FoundRHS);
8249       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8250     } else {
8251       std::swap(LHS, RHS);
8252       Pred = ICmpInst::getSwappedPredicate(Pred);
8253     }
8254   }
8255
8256   // Check whether the found predicate is the same as the desired predicate.
8257   if (FoundPred == Pred)
8258     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8259
8260   // Check whether swapping the found predicate makes it the same as the
8261   // desired predicate.
8262   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8263     if (isa<SCEVConstant>(RHS))
8264       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8265     else
8266       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8267                                    RHS, LHS, FoundLHS, FoundRHS);
8268   }
8269
8270   // Unsigned comparison is the same as signed comparison when both the operands
8271   // are non-negative.
8272   if (CmpInst::isUnsigned(FoundPred) &&
8273       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8274       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8275     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8276
8277   // Check if we can make progress by sharpening ranges.
8278   if (FoundPred == ICmpInst::ICMP_NE &&
8279       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8280
8281     const SCEVConstant *C = nullptr;
8282     const SCEV *V = nullptr;
8283
8284     if (isa<SCEVConstant>(FoundLHS)) {
8285       C = cast<SCEVConstant>(FoundLHS);
8286       V = FoundRHS;
8287     } else {
8288       C = cast<SCEVConstant>(FoundRHS);
8289       V = FoundLHS;
8290     }
8291
8292     // The guarding predicate tells us that C != V. If the known range
8293     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8294     // range we consider has to correspond to same signedness as the
8295     // predicate we're interested in folding.
8296
8297     APInt Min = ICmpInst::isSigned(Pred) ?
8298         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8299
8300     if (Min == C->getAPInt()) {
8301       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8302       // This is true even if (Min + 1) wraps around -- in case of
8303       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8304
8305       APInt SharperMin = Min + 1;
8306
8307       switch (Pred) {
8308         case ICmpInst::ICMP_SGE:
8309         case ICmpInst::ICMP_UGE:
8310           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8311           // RHS, we're done.
8312           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8313                                     getConstant(SharperMin)))
8314             return true;
8315
8316         case ICmpInst::ICMP_SGT:
8317         case ICmpInst::ICMP_UGT:
8318           // We know from the range information that (V `Pred` Min ||
8319           // V == Min).  We know from the guarding condition that !(V
8320           // == Min).  This gives us
8321           //
8322           //       V `Pred` Min || V == Min && !(V == Min)
8323           //   =>  V `Pred` Min
8324           //
8325           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8326
8327           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8328             return true;
8329
8330         default:
8331           // No change
8332           break;
8333       }
8334     }
8335   }
8336
8337   // Check whether the actual condition is beyond sufficient.
8338   if (FoundPred == ICmpInst::ICMP_EQ)
8339     if (ICmpInst::isTrueWhenEqual(Pred))
8340       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8341         return true;
8342   if (Pred == ICmpInst::ICMP_NE)
8343     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8344       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8345         return true;
8346
8347   // Otherwise assume the worst.
8348   return false;
8349 }
8350
8351 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8352                                      const SCEV *&L, const SCEV *&R,
8353                                      SCEV::NoWrapFlags &Flags) {
8354   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8355   if (!AE || AE->getNumOperands() != 2)
8356     return false;
8357
8358   L = AE->getOperand(0);
8359   R = AE->getOperand(1);
8360   Flags = AE->getNoWrapFlags();
8361   return true;
8362 }
8363
8364 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8365                                                            const SCEV *Less) {
8366   // We avoid subtracting expressions here because this function is usually
8367   // fairly deep in the call stack (i.e. is called many times).
8368
8369   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8370     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8371     const auto *MAR = cast<SCEVAddRecExpr>(More);
8372
8373     if (LAR->getLoop() != MAR->getLoop())
8374       return None;
8375
8376     // We look at affine expressions only; not for correctness but to keep
8377     // getStepRecurrence cheap.
8378     if (!LAR->isAffine() || !MAR->isAffine())
8379       return None;
8380
8381     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8382       return None;
8383
8384     Less = LAR->getStart();
8385     More = MAR->getStart();
8386
8387     // fall through
8388   }
8389
8390   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8391     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8392     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8393     return M - L;
8394   }
8395
8396   const SCEV *L, *R;
8397   SCEV::NoWrapFlags Flags;
8398   if (splitBinaryAdd(Less, L, R, Flags))
8399     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8400       if (R == More)
8401         return -(LC->getAPInt());
8402
8403   if (splitBinaryAdd(More, L, R, Flags))
8404     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8405       if (R == Less)
8406         return LC->getAPInt();
8407
8408   return None;
8409 }
8410
8411 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8412     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8413     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8414   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8415     return false;
8416
8417   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8418   if (!AddRecLHS)
8419     return false;
8420
8421   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8422   if (!AddRecFoundLHS)
8423     return false;
8424
8425   // We'd like to let SCEV reason about control dependencies, so we constrain
8426   // both the inequalities to be about add recurrences on the same loop.  This
8427   // way we can use isLoopEntryGuardedByCond later.
8428
8429   const Loop *L = AddRecFoundLHS->getLoop();
8430   if (L != AddRecLHS->getLoop())
8431     return false;
8432
8433   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8434   //
8435   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8436   //                                                                  ... (2)
8437   //
8438   // Informal proof for (2), assuming (1) [*]:
8439   //
8440   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8441   //
8442   // Then
8443   //
8444   //       FoundLHS s< FoundRHS s< INT_MIN - C
8445   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8446   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8447   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8448   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8449   // <=>  FoundLHS + C s< FoundRHS + C
8450   //
8451   // [*]: (1) can be proved by ruling out overflow.
8452   //
8453   // [**]: This can be proved by analyzing all the four possibilities:
8454   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8455   //    (A s>= 0, B s>= 0).
8456   //
8457   // Note:
8458   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8459   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8460   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8461   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8462   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8463   // C)".
8464
8465   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8466   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8467   if (!LDiff || !RDiff || *LDiff != *RDiff)
8468     return false;
8469
8470   if (LDiff->isMinValue())
8471     return true;
8472
8473   APInt FoundRHSLimit;
8474
8475   if (Pred == CmpInst::ICMP_ULT) {
8476     FoundRHSLimit = -(*RDiff);
8477   } else {
8478     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8479     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8480   }
8481
8482   // Try to prove (1) or (2), as needed.
8483   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8484                                   getConstant(FoundRHSLimit));
8485 }
8486
8487 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8488                                             const SCEV *LHS, const SCEV *RHS,
8489                                             const SCEV *FoundLHS,
8490                                             const SCEV *FoundRHS) {
8491   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8492     return true;
8493
8494   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8495     return true;
8496
8497   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8498                                      FoundLHS, FoundRHS) ||
8499          // ~x < ~y --> x > y
8500          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8501                                      getNotSCEV(FoundRHS),
8502                                      getNotSCEV(FoundLHS));
8503 }
8504
8505
8506 /// If Expr computes ~A, return A else return nullptr
8507 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8508   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8509   if (!Add || Add->getNumOperands() != 2 ||
8510       !Add->getOperand(0)->isAllOnesValue())
8511     return nullptr;
8512
8513   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8514   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8515       !AddRHS->getOperand(0)->isAllOnesValue())
8516     return nullptr;
8517
8518   return AddRHS->getOperand(1);
8519 }
8520
8521
8522 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8523 template<typename MaxExprType>
8524 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8525                               const SCEV *Candidate) {
8526   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8527   if (!MaxExpr) return false;
8528
8529   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8530 }
8531
8532
8533 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8534 template<typename MaxExprType>
8535 static bool IsMinConsistingOf(ScalarEvolution &SE,
8536                               const SCEV *MaybeMinExpr,
8537                               const SCEV *Candidate) {
8538   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8539   if (!MaybeMaxExpr)
8540     return false;
8541
8542   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8543 }
8544
8545 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8546                                            ICmpInst::Predicate Pred,
8547                                            const SCEV *LHS, const SCEV *RHS) {
8548
8549   // If both sides are affine addrecs for the same loop, with equal
8550   // steps, and we know the recurrences don't wrap, then we only
8551   // need to check the predicate on the starting values.
8552
8553   if (!ICmpInst::isRelational(Pred))
8554     return false;
8555
8556   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8557   if (!LAR)
8558     return false;
8559   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8560   if (!RAR)
8561     return false;
8562   if (LAR->getLoop() != RAR->getLoop())
8563     return false;
8564   if (!LAR->isAffine() || !RAR->isAffine())
8565     return false;
8566
8567   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8568     return false;
8569
8570   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8571                          SCEV::FlagNSW : SCEV::FlagNUW;
8572   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8573     return false;
8574
8575   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8576 }
8577
8578 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8579 /// expression?
8580 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8581                                         ICmpInst::Predicate Pred,
8582                                         const SCEV *LHS, const SCEV *RHS) {
8583   switch (Pred) {
8584   default:
8585     return false;
8586
8587   case ICmpInst::ICMP_SGE:
8588     std::swap(LHS, RHS);
8589     LLVM_FALLTHROUGH;
8590   case ICmpInst::ICMP_SLE:
8591     return
8592       // min(A, ...) <= A
8593       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8594       // A <= max(A, ...)
8595       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8596
8597   case ICmpInst::ICMP_UGE:
8598     std::swap(LHS, RHS);
8599     LLVM_FALLTHROUGH;
8600   case ICmpInst::ICMP_ULE:
8601     return
8602       // min(A, ...) <= A
8603       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8604       // A <= max(A, ...)
8605       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8606   }
8607
8608   llvm_unreachable("covered switch fell through?!");
8609 }
8610
8611 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8612                                              const SCEV *LHS, const SCEV *RHS,
8613                                              const SCEV *FoundLHS,
8614                                              const SCEV *FoundRHS,
8615                                              unsigned Depth) {
8616   assert(getTypeSizeInBits(LHS->getType()) ==
8617              getTypeSizeInBits(RHS->getType()) &&
8618          "LHS and RHS have different sizes?");
8619   assert(getTypeSizeInBits(FoundLHS->getType()) ==
8620              getTypeSizeInBits(FoundRHS->getType()) &&
8621          "FoundLHS and FoundRHS have different sizes?");
8622   // We want to avoid hurting the compile time with analysis of too big trees.
8623   if (Depth > MaxSCEVOperationsImplicationDepth)
8624     return false;
8625   // We only want to work with ICMP_SGT comparison so far.
8626   // TODO: Extend to ICMP_UGT?
8627   if (Pred == ICmpInst::ICMP_SLT) {
8628     Pred = ICmpInst::ICMP_SGT;
8629     std::swap(LHS, RHS);
8630     std::swap(FoundLHS, FoundRHS);
8631   }
8632   if (Pred != ICmpInst::ICMP_SGT)
8633     return false;
8634
8635   auto GetOpFromSExt = [&](const SCEV *S) {
8636     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8637       return Ext->getOperand();
8638     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8639     // the constant in some cases.
8640     return S;
8641   };
8642
8643   // Acquire values from extensions.
8644   auto *OrigFoundLHS = FoundLHS;
8645   LHS = GetOpFromSExt(LHS);
8646   FoundLHS = GetOpFromSExt(FoundLHS);
8647
8648   // Is the SGT predicate can be proved trivially or using the found context.
8649   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8650     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8651            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8652                                   FoundRHS, Depth + 1);
8653   };
8654
8655   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8656     // We want to avoid creation of any new non-constant SCEV. Since we are
8657     // going to compare the operands to RHS, we should be certain that we don't
8658     // need any size extensions for this. So let's decline all cases when the
8659     // sizes of types of LHS and RHS do not match.
8660     // TODO: Maybe try to get RHS from sext to catch more cases?
8661     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8662       return false;
8663
8664     // Should not overflow.
8665     if (!LHSAddExpr->hasNoSignedWrap())
8666       return false;
8667
8668     auto *LL = LHSAddExpr->getOperand(0);
8669     auto *LR = LHSAddExpr->getOperand(1);
8670     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8671
8672     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8673     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8674       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8675     };
8676     // Try to prove the following rule:
8677     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8678     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8679     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8680       return true;
8681   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8682     Value *LL, *LR;
8683     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8684     using namespace llvm::PatternMatch;
8685     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8686       // Rules for division.
8687       // We are going to perform some comparisons with Denominator and its
8688       // derivative expressions. In general case, creating a SCEV for it may
8689       // lead to a complex analysis of the entire graph, and in particular it
8690       // can request trip count recalculation for the same loop. This would
8691       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8692       // this, we only want to create SCEVs that are constants in this section.
8693       // So we bail if Denominator is not a constant.
8694       if (!isa<ConstantInt>(LR))
8695         return false;
8696
8697       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8698
8699       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8700       // then a SCEV for the numerator already exists and matches with FoundLHS.
8701       auto *Numerator = getExistingSCEV(LL);
8702       if (!Numerator || Numerator->getType() != FoundLHS->getType())
8703         return false;
8704
8705       // Make sure that the numerator matches with FoundLHS and the denominator
8706       // is positive.
8707       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8708         return false;
8709
8710       auto *DTy = Denominator->getType();
8711       auto *FRHSTy = FoundRHS->getType();
8712       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8713         // One of types is a pointer and another one is not. We cannot extend
8714         // them properly to a wider type, so let us just reject this case.
8715         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8716         // to avoid this check.
8717         return false;
8718
8719       // Given that:
8720       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8721       auto *WTy = getWiderType(DTy, FRHSTy);
8722       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8723       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8724
8725       // Try to prove the following rule:
8726       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8727       // For example, given that FoundLHS > 2. It means that FoundLHS is at
8728       // least 3. If we divide it by Denominator < 4, we will have at least 1.
8729       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8730       if (isKnownNonPositive(RHS) &&
8731           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8732         return true;
8733
8734       // Try to prove the following rule:
8735       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
8736       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
8737       // If we divide it by Denominator > 2, then:
8738       // 1. If FoundLHS is negative, then the result is 0.
8739       // 2. If FoundLHS is non-negative, then the result is non-negative.
8740       // Anyways, the result is non-negative.
8741       auto *MinusOne = getNegativeSCEV(getOne(WTy));
8742       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
8743       if (isKnownNegative(RHS) &&
8744           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
8745         return true;
8746     }
8747   }
8748
8749   return false;
8750 }
8751
8752 bool
8753 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
8754                                            const SCEV *LHS, const SCEV *RHS) {
8755   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8756          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8757          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8758          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8759 }
8760
8761 bool
8762 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8763                                              const SCEV *LHS, const SCEV *RHS,
8764                                              const SCEV *FoundLHS,
8765                                              const SCEV *FoundRHS) {
8766   switch (Pred) {
8767   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8768   case ICmpInst::ICMP_EQ:
8769   case ICmpInst::ICMP_NE:
8770     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8771       return true;
8772     break;
8773   case ICmpInst::ICMP_SLT:
8774   case ICmpInst::ICMP_SLE:
8775     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8776         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8777       return true;
8778     break;
8779   case ICmpInst::ICMP_SGT:
8780   case ICmpInst::ICMP_SGE:
8781     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8782         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8783       return true;
8784     break;
8785   case ICmpInst::ICMP_ULT:
8786   case ICmpInst::ICMP_ULE:
8787     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8788         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8789       return true;
8790     break;
8791   case ICmpInst::ICMP_UGT:
8792   case ICmpInst::ICMP_UGE:
8793     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8794         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8795       return true;
8796     break;
8797   }
8798
8799   // Maybe it can be proved via operations?
8800   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
8801     return true;
8802
8803   return false;
8804 }
8805
8806 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8807                                                      const SCEV *LHS,
8808                                                      const SCEV *RHS,
8809                                                      const SCEV *FoundLHS,
8810                                                      const SCEV *FoundRHS) {
8811   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8812     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8813     // reduce the compile time impact of this optimization.
8814     return false;
8815
8816   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8817   if (!Addend)
8818     return false;
8819
8820   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8821
8822   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8823   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8824   ConstantRange FoundLHSRange =
8825       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8826
8827   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8828   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8829
8830   // We can also compute the range of values for `LHS` that satisfy the
8831   // consequent, "`LHS` `Pred` `RHS`":
8832   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8833   ConstantRange SatisfyingLHSRange =
8834       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8835
8836   // The antecedent implies the consequent if every value of `LHS` that
8837   // satisfies the antecedent also satisfies the consequent.
8838   return SatisfyingLHSRange.contains(LHSRange);
8839 }
8840
8841 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8842                                          bool IsSigned, bool NoWrap) {
8843   assert(isKnownPositive(Stride) && "Positive stride expected!");
8844
8845   if (NoWrap) return false;
8846
8847   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8848   const SCEV *One = getOne(Stride->getType());
8849
8850   if (IsSigned) {
8851     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8852     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8853     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8854                                 .getSignedMax();
8855
8856     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8857     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8858   }
8859
8860   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8861   APInt MaxValue = APInt::getMaxValue(BitWidth);
8862   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8863                               .getUnsignedMax();
8864
8865   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8866   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8867 }
8868
8869 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8870                                          bool IsSigned, bool NoWrap) {
8871   if (NoWrap) return false;
8872
8873   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8874   const SCEV *One = getOne(Stride->getType());
8875
8876   if (IsSigned) {
8877     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8878     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8879     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8880                                .getSignedMax();
8881
8882     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8883     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8884   }
8885
8886   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8887   APInt MinValue = APInt::getMinValue(BitWidth);
8888   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8889                             .getUnsignedMax();
8890
8891   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8892   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8893 }
8894
8895 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8896                                             bool Equality) {
8897   const SCEV *One = getOne(Step->getType());
8898   Delta = Equality ? getAddExpr(Delta, Step)
8899                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8900   return getUDivExpr(Delta, Step);
8901 }
8902
8903 ScalarEvolution::ExitLimit
8904 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8905                                   const Loop *L, bool IsSigned,
8906                                   bool ControlsExit, bool AllowPredicates) {
8907   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8908   // We handle only IV < Invariant
8909   if (!isLoopInvariant(RHS, L))
8910     return getCouldNotCompute();
8911
8912   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8913   bool PredicatedIV = false;
8914
8915   if (!IV && AllowPredicates) {
8916     // Try to make this an AddRec using runtime tests, in the first X
8917     // iterations of this loop, where X is the SCEV expression found by the
8918     // algorithm below.
8919     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8920     PredicatedIV = true;
8921   }
8922
8923   // Avoid weird loops
8924   if (!IV || IV->getLoop() != L || !IV->isAffine())
8925     return getCouldNotCompute();
8926
8927   bool NoWrap = ControlsExit &&
8928                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8929
8930   const SCEV *Stride = IV->getStepRecurrence(*this);
8931
8932   bool PositiveStride = isKnownPositive(Stride);
8933
8934   // Avoid negative or zero stride values.
8935   if (!PositiveStride) {
8936     // We can compute the correct backedge taken count for loops with unknown
8937     // strides if we can prove that the loop is not an infinite loop with side
8938     // effects. Here's the loop structure we are trying to handle -
8939     //
8940     // i = start
8941     // do {
8942     //   A[i] = i;
8943     //   i += s;
8944     // } while (i < end);
8945     //
8946     // The backedge taken count for such loops is evaluated as -
8947     // (max(end, start + stride) - start - 1) /u stride
8948     //
8949     // The additional preconditions that we need to check to prove correctness
8950     // of the above formula is as follows -
8951     //
8952     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8953     //    NoWrap flag).
8954     // b) loop is single exit with no side effects.
8955     //
8956     //
8957     // Precondition a) implies that if the stride is negative, this is a single
8958     // trip loop. The backedge taken count formula reduces to zero in this case.
8959     //
8960     // Precondition b) implies that the unknown stride cannot be zero otherwise
8961     // we have UB.
8962     //
8963     // The positive stride case is the same as isKnownPositive(Stride) returning
8964     // true (original behavior of the function).
8965     //
8966     // We want to make sure that the stride is truly unknown as there are edge
8967     // cases where ScalarEvolution propagates no wrap flags to the
8968     // post-increment/decrement IV even though the increment/decrement operation
8969     // itself is wrapping. The computed backedge taken count may be wrong in
8970     // such cases. This is prevented by checking that the stride is not known to
8971     // be either positive or non-positive. For example, no wrap flags are
8972     // propagated to the post-increment IV of this loop with a trip count of 2 -
8973     //
8974     // unsigned char i;
8975     // for(i=127; i<128; i+=129)
8976     //   A[i] = i;
8977     //
8978     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8979         !loopHasNoSideEffects(L))
8980       return getCouldNotCompute();
8981
8982   } else if (!Stride->isOne() &&
8983              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8984     // Avoid proven overflow cases: this will ensure that the backedge taken
8985     // count will not generate any unsigned overflow. Relaxed no-overflow
8986     // conditions exploit NoWrapFlags, allowing to optimize in presence of
8987     // undefined behaviors like the case of C language.
8988     return getCouldNotCompute();
8989
8990   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8991                                       : ICmpInst::ICMP_ULT;
8992   const SCEV *Start = IV->getStart();
8993   const SCEV *End = RHS;
8994   // If the backedge is taken at least once, then it will be taken
8995   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8996   // is the LHS value of the less-than comparison the first time it is evaluated
8997   // and End is the RHS.
8998   const SCEV *BECountIfBackedgeTaken =
8999     computeBECount(getMinusSCEV(End, Start), Stride, false);
9000   // If the loop entry is guarded by the result of the backedge test of the
9001   // first loop iteration, then we know the backedge will be taken at least
9002   // once and so the backedge taken count is as above. If not then we use the
9003   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9004   // as if the backedge is taken at least once max(End,Start) is End and so the
9005   // result is as above, and if not max(End,Start) is Start so we get a backedge
9006   // count of zero.
9007   const SCEV *BECount;
9008   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9009     BECount = BECountIfBackedgeTaken;
9010   else {
9011     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9012     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9013   }
9014
9015   const SCEV *MaxBECount;
9016   bool MaxOrZero = false;
9017   if (isa<SCEVConstant>(BECount))
9018     MaxBECount = BECount;
9019   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9020     // If we know exactly how many times the backedge will be taken if it's
9021     // taken at least once, then the backedge count will either be that or
9022     // zero.
9023     MaxBECount = BECountIfBackedgeTaken;
9024     MaxOrZero = true;
9025   } else {
9026     // Calculate the maximum backedge count based on the range of values
9027     // permitted by Start, End, and Stride.
9028     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
9029                               : getUnsignedRange(Start).getUnsignedMin();
9030
9031     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9032
9033     APInt StrideForMaxBECount;
9034
9035     if (PositiveStride)
9036       StrideForMaxBECount =
9037         IsSigned ? getSignedRange(Stride).getSignedMin()
9038                  : getUnsignedRange(Stride).getUnsignedMin();
9039     else
9040       // Using a stride of 1 is safe when computing max backedge taken count for
9041       // a loop with unknown stride.
9042       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9043
9044     APInt Limit =
9045       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9046                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9047
9048     // Although End can be a MAX expression we estimate MaxEnd considering only
9049     // the case End = RHS. This is safe because in the other case (End - Start)
9050     // is zero, leading to a zero maximum backedge taken count.
9051     APInt MaxEnd =
9052       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
9053                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
9054
9055     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9056                                 getConstant(StrideForMaxBECount), false);
9057   }
9058
9059   if (isa<SCEVCouldNotCompute>(MaxBECount))
9060     MaxBECount = BECount;
9061
9062   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9063 }
9064
9065 ScalarEvolution::ExitLimit
9066 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9067                                      const Loop *L, bool IsSigned,
9068                                      bool ControlsExit, bool AllowPredicates) {
9069   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9070   // We handle only IV > Invariant
9071   if (!isLoopInvariant(RHS, L))
9072     return getCouldNotCompute();
9073
9074   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9075   if (!IV && AllowPredicates)
9076     // Try to make this an AddRec using runtime tests, in the first X
9077     // iterations of this loop, where X is the SCEV expression found by the
9078     // algorithm below.
9079     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9080
9081   // Avoid weird loops
9082   if (!IV || IV->getLoop() != L || !IV->isAffine())
9083     return getCouldNotCompute();
9084
9085   bool NoWrap = ControlsExit &&
9086                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9087
9088   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9089
9090   // Avoid negative or zero stride values
9091   if (!isKnownPositive(Stride))
9092     return getCouldNotCompute();
9093
9094   // Avoid proven overflow cases: this will ensure that the backedge taken count
9095   // will not generate any unsigned overflow. Relaxed no-overflow conditions
9096   // exploit NoWrapFlags, allowing to optimize in presence of undefined
9097   // behaviors like the case of C language.
9098   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9099     return getCouldNotCompute();
9100
9101   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9102                                       : ICmpInst::ICMP_UGT;
9103
9104   const SCEV *Start = IV->getStart();
9105   const SCEV *End = RHS;
9106   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9107     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9108
9109   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9110
9111   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
9112                             : getUnsignedRange(Start).getUnsignedMax();
9113
9114   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
9115                              : getUnsignedRange(Stride).getUnsignedMin();
9116
9117   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9118   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9119                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
9120
9121   // Although End can be a MIN expression we estimate MinEnd considering only
9122   // the case End = RHS. This is safe because in the other case (Start - End)
9123   // is zero, leading to a zero maximum backedge taken count.
9124   APInt MinEnd =
9125     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
9126              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
9127
9128
9129   const SCEV *MaxBECount = getCouldNotCompute();
9130   if (isa<SCEVConstant>(BECount))
9131     MaxBECount = BECount;
9132   else
9133     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9134                                 getConstant(MinStride), false);
9135
9136   if (isa<SCEVCouldNotCompute>(MaxBECount))
9137     MaxBECount = BECount;
9138
9139   return ExitLimit(BECount, MaxBECount, false, Predicates);
9140 }
9141
9142 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9143                                                     ScalarEvolution &SE) const {
9144   if (Range.isFullSet())  // Infinite loop.
9145     return SE.getCouldNotCompute();
9146
9147   // If the start is a non-zero constant, shift the range to simplify things.
9148   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9149     if (!SC->getValue()->isZero()) {
9150       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9151       Operands[0] = SE.getZero(SC->getType());
9152       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9153                                              getNoWrapFlags(FlagNW));
9154       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9155         return ShiftedAddRec->getNumIterationsInRange(
9156             Range.subtract(SC->getAPInt()), SE);
9157       // This is strange and shouldn't happen.
9158       return SE.getCouldNotCompute();
9159     }
9160
9161   // The only time we can solve this is when we have all constant indices.
9162   // Otherwise, we cannot determine the overflow conditions.
9163   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9164     return SE.getCouldNotCompute();
9165
9166   // Okay at this point we know that all elements of the chrec are constants and
9167   // that the start element is zero.
9168
9169   // First check to see if the range contains zero.  If not, the first
9170   // iteration exits.
9171   unsigned BitWidth = SE.getTypeSizeInBits(getType());
9172   if (!Range.contains(APInt(BitWidth, 0)))
9173     return SE.getZero(getType());
9174
9175   if (isAffine()) {
9176     // If this is an affine expression then we have this situation:
9177     //   Solve {0,+,A} in Range  ===  Ax in Range
9178
9179     // We know that zero is in the range.  If A is positive then we know that
9180     // the upper value of the range must be the first possible exit value.
9181     // If A is negative then the lower of the range is the last possible loop
9182     // value.  Also note that we already checked for a full range.
9183     APInt One(BitWidth,1);
9184     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9185     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
9186
9187     // The exit value should be (End+A)/A.
9188     APInt ExitVal = (End + A).udiv(A);
9189     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9190
9191     // Evaluate at the exit value.  If we really did fall out of the valid
9192     // range, then we computed our trip count, otherwise wrap around or other
9193     // things must have happened.
9194     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9195     if (Range.contains(Val->getValue()))
9196       return SE.getCouldNotCompute();  // Something strange happened
9197
9198     // Ensure that the previous value is in the range.  This is a sanity check.
9199     assert(Range.contains(
9200            EvaluateConstantChrecAtConstant(this,
9201            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
9202            "Linear scev computation is off in a bad way!");
9203     return SE.getConstant(ExitValue);
9204   } else if (isQuadratic()) {
9205     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9206     // quadratic equation to solve it.  To do this, we must frame our problem in
9207     // terms of figuring out when zero is crossed, instead of when
9208     // Range.getUpper() is crossed.
9209     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9210     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9211     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9212
9213     // Next, solve the constructed addrec
9214     if (auto Roots =
9215             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9216       const SCEVConstant *R1 = Roots->first;
9217       const SCEVConstant *R2 = Roots->second;
9218       // Pick the smallest positive root value.
9219       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9220               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9221         if (!CB->getZExtValue())
9222           std::swap(R1, R2); // R1 is the minimum root now.
9223
9224         // Make sure the root is not off by one.  The returned iteration should
9225         // not be in the range, but the previous one should be.  When solving
9226         // for "X*X < 5", for example, we should not return a root of 2.
9227         ConstantInt *R1Val =
9228             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9229         if (Range.contains(R1Val->getValue())) {
9230           // The next iteration must be out of the range...
9231           ConstantInt *NextVal =
9232               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9233
9234           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9235           if (!Range.contains(R1Val->getValue()))
9236             return SE.getConstant(NextVal);
9237           return SE.getCouldNotCompute(); // Something strange happened
9238         }
9239
9240         // If R1 was not in the range, then it is a good return value.  Make
9241         // sure that R1-1 WAS in the range though, just in case.
9242         ConstantInt *NextVal =
9243             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9244         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9245         if (Range.contains(R1Val->getValue()))
9246           return R1;
9247         return SE.getCouldNotCompute(); // Something strange happened
9248       }
9249     }
9250   }
9251
9252   return SE.getCouldNotCompute();
9253 }
9254
9255 // Return true when S contains at least an undef value.
9256 static inline bool containsUndefs(const SCEV *S) {
9257   return SCEVExprContains(S, [](const SCEV *S) {
9258     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9259       return isa<UndefValue>(SU->getValue());
9260     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9261       return isa<UndefValue>(SC->getValue());
9262     return false;
9263   });
9264 }
9265
9266 namespace {
9267 // Collect all steps of SCEV expressions.
9268 struct SCEVCollectStrides {
9269   ScalarEvolution &SE;
9270   SmallVectorImpl<const SCEV *> &Strides;
9271
9272   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9273       : SE(SE), Strides(S) {}
9274
9275   bool follow(const SCEV *S) {
9276     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9277       Strides.push_back(AR->getStepRecurrence(SE));
9278     return true;
9279   }
9280   bool isDone() const { return false; }
9281 };
9282
9283 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9284 struct SCEVCollectTerms {
9285   SmallVectorImpl<const SCEV *> &Terms;
9286
9287   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9288       : Terms(T) {}
9289
9290   bool follow(const SCEV *S) {
9291     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9292         isa<SCEVSignExtendExpr>(S)) {
9293       if (!containsUndefs(S))
9294         Terms.push_back(S);
9295
9296       // Stop recursion: once we collected a term, do not walk its operands.
9297       return false;
9298     }
9299
9300     // Keep looking.
9301     return true;
9302   }
9303   bool isDone() const { return false; }
9304 };
9305
9306 // Check if a SCEV contains an AddRecExpr.
9307 struct SCEVHasAddRec {
9308   bool &ContainsAddRec;
9309
9310   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9311    ContainsAddRec = false;
9312   }
9313
9314   bool follow(const SCEV *S) {
9315     if (isa<SCEVAddRecExpr>(S)) {
9316       ContainsAddRec = true;
9317
9318       // Stop recursion: once we collected a term, do not walk its operands.
9319       return false;
9320     }
9321
9322     // Keep looking.
9323     return true;
9324   }
9325   bool isDone() const { return false; }
9326 };
9327
9328 // Find factors that are multiplied with an expression that (possibly as a
9329 // subexpression) contains an AddRecExpr. In the expression:
9330 //
9331 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9332 //
9333 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9334 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9335 // parameters as they form a product with an induction variable.
9336 //
9337 // This collector expects all array size parameters to be in the same MulExpr.
9338 // It might be necessary to later add support for collecting parameters that are
9339 // spread over different nested MulExpr.
9340 struct SCEVCollectAddRecMultiplies {
9341   SmallVectorImpl<const SCEV *> &Terms;
9342   ScalarEvolution &SE;
9343
9344   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9345       : Terms(T), SE(SE) {}
9346
9347   bool follow(const SCEV *S) {
9348     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9349       bool HasAddRec = false;
9350       SmallVector<const SCEV *, 0> Operands;
9351       for (auto Op : Mul->operands()) {
9352         if (isa<SCEVUnknown>(Op)) {
9353           Operands.push_back(Op);
9354         } else {
9355           bool ContainsAddRec;
9356           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9357           visitAll(Op, ContiansAddRec);
9358           HasAddRec |= ContainsAddRec;
9359         }
9360       }
9361       if (Operands.size() == 0)
9362         return true;
9363
9364       if (!HasAddRec)
9365         return false;
9366
9367       Terms.push_back(SE.getMulExpr(Operands));
9368       // Stop recursion: once we collected a term, do not walk its operands.
9369       return false;
9370     }
9371
9372     // Keep looking.
9373     return true;
9374   }
9375   bool isDone() const { return false; }
9376 };
9377 }
9378
9379 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9380 /// two places:
9381 ///   1) The strides of AddRec expressions.
9382 ///   2) Unknowns that are multiplied with AddRec expressions.
9383 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9384     SmallVectorImpl<const SCEV *> &Terms) {
9385   SmallVector<const SCEV *, 4> Strides;
9386   SCEVCollectStrides StrideCollector(*this, Strides);
9387   visitAll(Expr, StrideCollector);
9388
9389   DEBUG({
9390       dbgs() << "Strides:\n";
9391       for (const SCEV *S : Strides)
9392         dbgs() << *S << "\n";
9393     });
9394
9395   for (const SCEV *S : Strides) {
9396     SCEVCollectTerms TermCollector(Terms);
9397     visitAll(S, TermCollector);
9398   }
9399
9400   DEBUG({
9401       dbgs() << "Terms:\n";
9402       for (const SCEV *T : Terms)
9403         dbgs() << *T << "\n";
9404     });
9405
9406   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9407   visitAll(Expr, MulCollector);
9408 }
9409
9410 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9411                                    SmallVectorImpl<const SCEV *> &Terms,
9412                                    SmallVectorImpl<const SCEV *> &Sizes) {
9413   int Last = Terms.size() - 1;
9414   const SCEV *Step = Terms[Last];
9415
9416   // End of recursion.
9417   if (Last == 0) {
9418     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9419       SmallVector<const SCEV *, 2> Qs;
9420       for (const SCEV *Op : M->operands())
9421         if (!isa<SCEVConstant>(Op))
9422           Qs.push_back(Op);
9423
9424       Step = SE.getMulExpr(Qs);
9425     }
9426
9427     Sizes.push_back(Step);
9428     return true;
9429   }
9430
9431   for (const SCEV *&Term : Terms) {
9432     // Normalize the terms before the next call to findArrayDimensionsRec.
9433     const SCEV *Q, *R;
9434     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9435
9436     // Bail out when GCD does not evenly divide one of the terms.
9437     if (!R->isZero())
9438       return false;
9439
9440     Term = Q;
9441   }
9442
9443   // Remove all SCEVConstants.
9444   Terms.erase(
9445       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9446       Terms.end());
9447
9448   if (Terms.size() > 0)
9449     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9450       return false;
9451
9452   Sizes.push_back(Step);
9453   return true;
9454 }
9455
9456
9457 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9458 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9459   for (const SCEV *T : Terms)
9460     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9461       return true;
9462   return false;
9463 }
9464
9465 // Return the number of product terms in S.
9466 static inline int numberOfTerms(const SCEV *S) {
9467   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9468     return Expr->getNumOperands();
9469   return 1;
9470 }
9471
9472 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9473   if (isa<SCEVConstant>(T))
9474     return nullptr;
9475
9476   if (isa<SCEVUnknown>(T))
9477     return T;
9478
9479   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9480     SmallVector<const SCEV *, 2> Factors;
9481     for (const SCEV *Op : M->operands())
9482       if (!isa<SCEVConstant>(Op))
9483         Factors.push_back(Op);
9484
9485     return SE.getMulExpr(Factors);
9486   }
9487
9488   return T;
9489 }
9490
9491 /// Return the size of an element read or written by Inst.
9492 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9493   Type *Ty;
9494   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9495     Ty = Store->getValueOperand()->getType();
9496   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9497     Ty = Load->getType();
9498   else
9499     return nullptr;
9500
9501   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9502   return getSizeOfExpr(ETy, Ty);
9503 }
9504
9505 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9506                                           SmallVectorImpl<const SCEV *> &Sizes,
9507                                           const SCEV *ElementSize) const {
9508   if (Terms.size() < 1 || !ElementSize)
9509     return;
9510
9511   // Early return when Terms do not contain parameters: we do not delinearize
9512   // non parametric SCEVs.
9513   if (!containsParameters(Terms))
9514     return;
9515
9516   DEBUG({
9517       dbgs() << "Terms:\n";
9518       for (const SCEV *T : Terms)
9519         dbgs() << *T << "\n";
9520     });
9521
9522   // Remove duplicates.
9523   std::sort(Terms.begin(), Terms.end());
9524   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9525
9526   // Put larger terms first.
9527   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9528     return numberOfTerms(LHS) > numberOfTerms(RHS);
9529   });
9530
9531   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9532
9533   // Try to divide all terms by the element size. If term is not divisible by
9534   // element size, proceed with the original term.
9535   for (const SCEV *&Term : Terms) {
9536     const SCEV *Q, *R;
9537     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9538     if (!Q->isZero())
9539       Term = Q;
9540   }
9541
9542   SmallVector<const SCEV *, 4> NewTerms;
9543
9544   // Remove constant factors.
9545   for (const SCEV *T : Terms)
9546     if (const SCEV *NewT = removeConstantFactors(SE, T))
9547       NewTerms.push_back(NewT);
9548
9549   DEBUG({
9550       dbgs() << "Terms after sorting:\n";
9551       for (const SCEV *T : NewTerms)
9552         dbgs() << *T << "\n";
9553     });
9554
9555   if (NewTerms.empty() ||
9556       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9557     Sizes.clear();
9558     return;
9559   }
9560
9561   // The last element to be pushed into Sizes is the size of an element.
9562   Sizes.push_back(ElementSize);
9563
9564   DEBUG({
9565       dbgs() << "Sizes:\n";
9566       for (const SCEV *S : Sizes)
9567         dbgs() << *S << "\n";
9568     });
9569 }
9570
9571 void ScalarEvolution::computeAccessFunctions(
9572     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9573     SmallVectorImpl<const SCEV *> &Sizes) {
9574
9575   // Early exit in case this SCEV is not an affine multivariate function.
9576   if (Sizes.empty())
9577     return;
9578
9579   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9580     if (!AR->isAffine())
9581       return;
9582
9583   const SCEV *Res = Expr;
9584   int Last = Sizes.size() - 1;
9585   for (int i = Last; i >= 0; i--) {
9586     const SCEV *Q, *R;
9587     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9588
9589     DEBUG({
9590         dbgs() << "Res: " << *Res << "\n";
9591         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9592         dbgs() << "Res divided by Sizes[i]:\n";
9593         dbgs() << "Quotient: " << *Q << "\n";
9594         dbgs() << "Remainder: " << *R << "\n";
9595       });
9596
9597     Res = Q;
9598
9599     // Do not record the last subscript corresponding to the size of elements in
9600     // the array.
9601     if (i == Last) {
9602
9603       // Bail out if the remainder is too complex.
9604       if (isa<SCEVAddRecExpr>(R)) {
9605         Subscripts.clear();
9606         Sizes.clear();
9607         return;
9608       }
9609
9610       continue;
9611     }
9612
9613     // Record the access function for the current subscript.
9614     Subscripts.push_back(R);
9615   }
9616
9617   // Also push in last position the remainder of the last division: it will be
9618   // the access function of the innermost dimension.
9619   Subscripts.push_back(Res);
9620
9621   std::reverse(Subscripts.begin(), Subscripts.end());
9622
9623   DEBUG({
9624       dbgs() << "Subscripts:\n";
9625       for (const SCEV *S : Subscripts)
9626         dbgs() << *S << "\n";
9627     });
9628 }
9629
9630 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9631 /// sizes of an array access. Returns the remainder of the delinearization that
9632 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9633 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9634 /// expressions in the stride and base of a SCEV corresponding to the
9635 /// computation of a GCD (greatest common divisor) of base and stride.  When
9636 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9637 ///
9638 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9639 ///
9640 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9641 ///
9642 ///    for (long i = 0; i < n; i++)
9643 ///      for (long j = 0; j < m; j++)
9644 ///        for (long k = 0; k < o; k++)
9645 ///          A[i][j][k] = 1.0;
9646 ///  }
9647 ///
9648 /// the delinearization input is the following AddRec SCEV:
9649 ///
9650 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9651 ///
9652 /// From this SCEV, we are able to say that the base offset of the access is %A
9653 /// because it appears as an offset that does not divide any of the strides in
9654 /// the loops:
9655 ///
9656 ///  CHECK: Base offset: %A
9657 ///
9658 /// and then SCEV->delinearize determines the size of some of the dimensions of
9659 /// the array as these are the multiples by which the strides are happening:
9660 ///
9661 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9662 ///
9663 /// Note that the outermost dimension remains of UnknownSize because there are
9664 /// no strides that would help identifying the size of the last dimension: when
9665 /// the array has been statically allocated, one could compute the size of that
9666 /// dimension by dividing the overall size of the array by the size of the known
9667 /// dimensions: %m * %o * 8.
9668 ///
9669 /// Finally delinearize provides the access functions for the array reference
9670 /// that does correspond to A[i][j][k] of the above C testcase:
9671 ///
9672 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9673 ///
9674 /// The testcases are checking the output of a function pass:
9675 /// DelinearizationPass that walks through all loads and stores of a function
9676 /// asking for the SCEV of the memory access with respect to all enclosing
9677 /// loops, calling SCEV->delinearize on that and printing the results.
9678
9679 void ScalarEvolution::delinearize(const SCEV *Expr,
9680                                  SmallVectorImpl<const SCEV *> &Subscripts,
9681                                  SmallVectorImpl<const SCEV *> &Sizes,
9682                                  const SCEV *ElementSize) {
9683   // First step: collect parametric terms.
9684   SmallVector<const SCEV *, 4> Terms;
9685   collectParametricTerms(Expr, Terms);
9686
9687   if (Terms.empty())
9688     return;
9689
9690   // Second step: find subscript sizes.
9691   findArrayDimensions(Terms, Sizes, ElementSize);
9692
9693   if (Sizes.empty())
9694     return;
9695
9696   // Third step: compute the access functions for each subscript.
9697   computeAccessFunctions(Expr, Subscripts, Sizes);
9698
9699   if (Subscripts.empty())
9700     return;
9701
9702   DEBUG({
9703       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9704       dbgs() << "ArrayDecl[UnknownSize]";
9705       for (const SCEV *S : Sizes)
9706         dbgs() << "[" << *S << "]";
9707
9708       dbgs() << "\nArrayRef";
9709       for (const SCEV *S : Subscripts)
9710         dbgs() << "[" << *S << "]";
9711       dbgs() << "\n";
9712     });
9713 }
9714
9715 //===----------------------------------------------------------------------===//
9716 //                   SCEVCallbackVH Class Implementation
9717 //===----------------------------------------------------------------------===//
9718
9719 void ScalarEvolution::SCEVCallbackVH::deleted() {
9720   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9721   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9722     SE->ConstantEvolutionLoopExitValue.erase(PN);
9723   SE->eraseValueFromMap(getValPtr());
9724   // this now dangles!
9725 }
9726
9727 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9728   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9729
9730   // Forget all the expressions associated with users of the old value,
9731   // so that future queries will recompute the expressions using the new
9732   // value.
9733   Value *Old = getValPtr();
9734   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9735   SmallPtrSet<User *, 8> Visited;
9736   while (!Worklist.empty()) {
9737     User *U = Worklist.pop_back_val();
9738     // Deleting the Old value will cause this to dangle. Postpone
9739     // that until everything else is done.
9740     if (U == Old)
9741       continue;
9742     if (!Visited.insert(U).second)
9743       continue;
9744     if (PHINode *PN = dyn_cast<PHINode>(U))
9745       SE->ConstantEvolutionLoopExitValue.erase(PN);
9746     SE->eraseValueFromMap(U);
9747     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9748   }
9749   // Delete the Old value.
9750   if (PHINode *PN = dyn_cast<PHINode>(Old))
9751     SE->ConstantEvolutionLoopExitValue.erase(PN);
9752   SE->eraseValueFromMap(Old);
9753   // this now dangles!
9754 }
9755
9756 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9757   : CallbackVH(V), SE(se) {}
9758
9759 //===----------------------------------------------------------------------===//
9760 //                   ScalarEvolution Class Implementation
9761 //===----------------------------------------------------------------------===//
9762
9763 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9764                                  AssumptionCache &AC, DominatorTree &DT,
9765                                  LoopInfo &LI)
9766     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9767       CouldNotCompute(new SCEVCouldNotCompute()),
9768       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9769       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9770       FirstUnknown(nullptr) {
9771
9772   // To use guards for proving predicates, we need to scan every instruction in
9773   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9774   // time if the IR does not actually contain any calls to
9775   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9776   //
9777   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9778   // to _add_ guards to the module when there weren't any before, and wants
9779   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9780   // efficient in lieu of being smart in that rather obscure case.
9781
9782   auto *GuardDecl = F.getParent()->getFunction(
9783       Intrinsic::getName(Intrinsic::experimental_guard));
9784   HasGuards = GuardDecl && !GuardDecl->use_empty();
9785 }
9786
9787 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9788     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9789       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9790       ValueExprMap(std::move(Arg.ValueExprMap)),
9791       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9792       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9793       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
9794       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9795       PredicatedBackedgeTakenCounts(
9796           std::move(Arg.PredicatedBackedgeTakenCounts)),
9797       ConstantEvolutionLoopExitValue(
9798           std::move(Arg.ConstantEvolutionLoopExitValue)),
9799       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9800       LoopDispositions(std::move(Arg.LoopDispositions)),
9801       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9802       BlockDispositions(std::move(Arg.BlockDispositions)),
9803       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9804       SignedRanges(std::move(Arg.SignedRanges)),
9805       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9806       UniquePreds(std::move(Arg.UniquePreds)),
9807       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9808       FirstUnknown(Arg.FirstUnknown) {
9809   Arg.FirstUnknown = nullptr;
9810 }
9811
9812 ScalarEvolution::~ScalarEvolution() {
9813   // Iterate through all the SCEVUnknown instances and call their
9814   // destructors, so that they release their references to their values.
9815   for (SCEVUnknown *U = FirstUnknown; U;) {
9816     SCEVUnknown *Tmp = U;
9817     U = U->Next;
9818     Tmp->~SCEVUnknown();
9819   }
9820   FirstUnknown = nullptr;
9821
9822   ExprValueMap.clear();
9823   ValueExprMap.clear();
9824   HasRecMap.clear();
9825
9826   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9827   // that a loop had multiple computable exits.
9828   for (auto &BTCI : BackedgeTakenCounts)
9829     BTCI.second.clear();
9830   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9831     BTCI.second.clear();
9832
9833   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9834   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9835   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9836 }
9837
9838 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9839   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9840 }
9841
9842 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9843                           const Loop *L) {
9844   // Print all inner loops first
9845   for (Loop *I : *L)
9846     PrintLoopInfo(OS, SE, I);
9847
9848   OS << "Loop ";
9849   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9850   OS << ": ";
9851
9852   SmallVector<BasicBlock *, 8> ExitBlocks;
9853   L->getExitBlocks(ExitBlocks);
9854   if (ExitBlocks.size() != 1)
9855     OS << "<multiple exits> ";
9856
9857   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9858     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9859   } else {
9860     OS << "Unpredictable backedge-taken count. ";
9861   }
9862
9863   OS << "\n"
9864         "Loop ";
9865   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9866   OS << ": ";
9867
9868   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9869     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9870     if (SE->isBackedgeTakenCountMaxOrZero(L))
9871       OS << ", actual taken count either this or zero.";
9872   } else {
9873     OS << "Unpredictable max backedge-taken count. ";
9874   }
9875
9876   OS << "\n"
9877         "Loop ";
9878   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9879   OS << ": ";
9880
9881   SCEVUnionPredicate Pred;
9882   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9883   if (!isa<SCEVCouldNotCompute>(PBT)) {
9884     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9885     OS << " Predicates:\n";
9886     Pred.print(OS, 4);
9887   } else {
9888     OS << "Unpredictable predicated backedge-taken count. ";
9889   }
9890   OS << "\n";
9891
9892   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9893     OS << "Loop ";
9894     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9895     OS << ": ";
9896     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
9897   }
9898 }
9899
9900 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9901   switch (LD) {
9902   case ScalarEvolution::LoopVariant:
9903     return "Variant";
9904   case ScalarEvolution::LoopInvariant:
9905     return "Invariant";
9906   case ScalarEvolution::LoopComputable:
9907     return "Computable";
9908   }
9909   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9910 }
9911
9912 void ScalarEvolution::print(raw_ostream &OS) const {
9913   // ScalarEvolution's implementation of the print method is to print
9914   // out SCEV values of all instructions that are interesting. Doing
9915   // this potentially causes it to create new SCEV objects though,
9916   // which technically conflicts with the const qualifier. This isn't
9917   // observable from outside the class though, so casting away the
9918   // const isn't dangerous.
9919   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9920
9921   OS << "Classifying expressions for: ";
9922   F.printAsOperand(OS, /*PrintType=*/false);
9923   OS << "\n";
9924   for (Instruction &I : instructions(F))
9925     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9926       OS << I << '\n';
9927       OS << "  -->  ";
9928       const SCEV *SV = SE.getSCEV(&I);
9929       SV->print(OS);
9930       if (!isa<SCEVCouldNotCompute>(SV)) {
9931         OS << " U: ";
9932         SE.getUnsignedRange(SV).print(OS);
9933         OS << " S: ";
9934         SE.getSignedRange(SV).print(OS);
9935       }
9936
9937       const Loop *L = LI.getLoopFor(I.getParent());
9938
9939       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9940       if (AtUse != SV) {
9941         OS << "  -->  ";
9942         AtUse->print(OS);
9943         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9944           OS << " U: ";
9945           SE.getUnsignedRange(AtUse).print(OS);
9946           OS << " S: ";
9947           SE.getSignedRange(AtUse).print(OS);
9948         }
9949       }
9950
9951       if (L) {
9952         OS << "\t\t" "Exits: ";
9953         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9954         if (!SE.isLoopInvariant(ExitValue, L)) {
9955           OS << "<<Unknown>>";
9956         } else {
9957           OS << *ExitValue;
9958         }
9959
9960         bool First = true;
9961         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9962           if (First) {
9963             OS << "\t\t" "LoopDispositions: { ";
9964             First = false;
9965           } else {
9966             OS << ", ";
9967           }
9968
9969           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9970           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9971         }
9972
9973         for (auto *InnerL : depth_first(L)) {
9974           if (InnerL == L)
9975             continue;
9976           if (First) {
9977             OS << "\t\t" "LoopDispositions: { ";
9978             First = false;
9979           } else {
9980             OS << ", ";
9981           }
9982
9983           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9984           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9985         }
9986
9987         OS << " }";
9988       }
9989
9990       OS << "\n";
9991     }
9992
9993   OS << "Determining loop execution counts for: ";
9994   F.printAsOperand(OS, /*PrintType=*/false);
9995   OS << "\n";
9996   for (Loop *I : LI)
9997     PrintLoopInfo(OS, &SE, I);
9998 }
9999
10000 ScalarEvolution::LoopDisposition
10001 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10002   auto &Values = LoopDispositions[S];
10003   for (auto &V : Values) {
10004     if (V.getPointer() == L)
10005       return V.getInt();
10006   }
10007   Values.emplace_back(L, LoopVariant);
10008   LoopDisposition D = computeLoopDisposition(S, L);
10009   auto &Values2 = LoopDispositions[S];
10010   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10011     if (V.getPointer() == L) {
10012       V.setInt(D);
10013       break;
10014     }
10015   }
10016   return D;
10017 }
10018
10019 ScalarEvolution::LoopDisposition
10020 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10021   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10022   case scConstant:
10023     return LoopInvariant;
10024   case scTruncate:
10025   case scZeroExtend:
10026   case scSignExtend:
10027     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10028   case scAddRecExpr: {
10029     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10030
10031     // If L is the addrec's loop, it's computable.
10032     if (AR->getLoop() == L)
10033       return LoopComputable;
10034
10035     // Add recurrences are never invariant in the function-body (null loop).
10036     if (!L)
10037       return LoopVariant;
10038
10039     // This recurrence is variant w.r.t. L if L contains AR's loop.
10040     if (L->contains(AR->getLoop()))
10041       return LoopVariant;
10042
10043     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10044     if (AR->getLoop()->contains(L))
10045       return LoopInvariant;
10046
10047     // This recurrence is variant w.r.t. L if any of its operands
10048     // are variant.
10049     for (auto *Op : AR->operands())
10050       if (!isLoopInvariant(Op, L))
10051         return LoopVariant;
10052
10053     // Otherwise it's loop-invariant.
10054     return LoopInvariant;
10055   }
10056   case scAddExpr:
10057   case scMulExpr:
10058   case scUMaxExpr:
10059   case scSMaxExpr: {
10060     bool HasVarying = false;
10061     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10062       LoopDisposition D = getLoopDisposition(Op, L);
10063       if (D == LoopVariant)
10064         return LoopVariant;
10065       if (D == LoopComputable)
10066         HasVarying = true;
10067     }
10068     return HasVarying ? LoopComputable : LoopInvariant;
10069   }
10070   case scUDivExpr: {
10071     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10072     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10073     if (LD == LoopVariant)
10074       return LoopVariant;
10075     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10076     if (RD == LoopVariant)
10077       return LoopVariant;
10078     return (LD == LoopInvariant && RD == LoopInvariant) ?
10079            LoopInvariant : LoopComputable;
10080   }
10081   case scUnknown:
10082     // All non-instruction values are loop invariant.  All instructions are loop
10083     // invariant if they are not contained in the specified loop.
10084     // Instructions are never considered invariant in the function body
10085     // (null loop) because they are defined within the "loop".
10086     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10087       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10088     return LoopInvariant;
10089   case scCouldNotCompute:
10090     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10091   }
10092   llvm_unreachable("Unknown SCEV kind!");
10093 }
10094
10095 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10096   return getLoopDisposition(S, L) == LoopInvariant;
10097 }
10098
10099 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10100   return getLoopDisposition(S, L) == LoopComputable;
10101 }
10102
10103 ScalarEvolution::BlockDisposition
10104 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10105   auto &Values = BlockDispositions[S];
10106   for (auto &V : Values) {
10107     if (V.getPointer() == BB)
10108       return V.getInt();
10109   }
10110   Values.emplace_back(BB, DoesNotDominateBlock);
10111   BlockDisposition D = computeBlockDisposition(S, BB);
10112   auto &Values2 = BlockDispositions[S];
10113   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10114     if (V.getPointer() == BB) {
10115       V.setInt(D);
10116       break;
10117     }
10118   }
10119   return D;
10120 }
10121
10122 ScalarEvolution::BlockDisposition
10123 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10124   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10125   case scConstant:
10126     return ProperlyDominatesBlock;
10127   case scTruncate:
10128   case scZeroExtend:
10129   case scSignExtend:
10130     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10131   case scAddRecExpr: {
10132     // This uses a "dominates" query instead of "properly dominates" query
10133     // to test for proper dominance too, because the instruction which
10134     // produces the addrec's value is a PHI, and a PHI effectively properly
10135     // dominates its entire containing block.
10136     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10137     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10138       return DoesNotDominateBlock;
10139
10140     // Fall through into SCEVNAryExpr handling.
10141     LLVM_FALLTHROUGH;
10142   }
10143   case scAddExpr:
10144   case scMulExpr:
10145   case scUMaxExpr:
10146   case scSMaxExpr: {
10147     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10148     bool Proper = true;
10149     for (const SCEV *NAryOp : NAry->operands()) {
10150       BlockDisposition D = getBlockDisposition(NAryOp, BB);
10151       if (D == DoesNotDominateBlock)
10152         return DoesNotDominateBlock;
10153       if (D == DominatesBlock)
10154         Proper = false;
10155     }
10156     return Proper ? ProperlyDominatesBlock : DominatesBlock;
10157   }
10158   case scUDivExpr: {
10159     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10160     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10161     BlockDisposition LD = getBlockDisposition(LHS, BB);
10162     if (LD == DoesNotDominateBlock)
10163       return DoesNotDominateBlock;
10164     BlockDisposition RD = getBlockDisposition(RHS, BB);
10165     if (RD == DoesNotDominateBlock)
10166       return DoesNotDominateBlock;
10167     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10168       ProperlyDominatesBlock : DominatesBlock;
10169   }
10170   case scUnknown:
10171     if (Instruction *I =
10172           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10173       if (I->getParent() == BB)
10174         return DominatesBlock;
10175       if (DT.properlyDominates(I->getParent(), BB))
10176         return ProperlyDominatesBlock;
10177       return DoesNotDominateBlock;
10178     }
10179     return ProperlyDominatesBlock;
10180   case scCouldNotCompute:
10181     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10182   }
10183   llvm_unreachable("Unknown SCEV kind!");
10184 }
10185
10186 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10187   return getBlockDisposition(S, BB) >= DominatesBlock;
10188 }
10189
10190 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10191   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10192 }
10193
10194 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10195   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10196 }
10197
10198 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10199   ValuesAtScopes.erase(S);
10200   LoopDispositions.erase(S);
10201   BlockDispositions.erase(S);
10202   UnsignedRanges.erase(S);
10203   SignedRanges.erase(S);
10204   ExprValueMap.erase(S);
10205   HasRecMap.erase(S);
10206   MinTrailingZerosCache.erase(S);
10207
10208   auto RemoveSCEVFromBackedgeMap =
10209       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10210         for (auto I = Map.begin(), E = Map.end(); I != E;) {
10211           BackedgeTakenInfo &BEInfo = I->second;
10212           if (BEInfo.hasOperand(S, this)) {
10213             BEInfo.clear();
10214             Map.erase(I++);
10215           } else
10216             ++I;
10217         }
10218       };
10219
10220   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10221   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10222 }
10223
10224 typedef DenseMap<const Loop *, std::string> VerifyMap;
10225
10226 /// replaceSubString - Replaces all occurrences of From in Str with To.
10227 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10228   size_t Pos = 0;
10229   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10230     Str.replace(Pos, From.size(), To.data(), To.size());
10231     Pos += To.size();
10232   }
10233 }
10234
10235 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10236 static void
10237 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
10238   std::string &S = Map[L];
10239   if (S.empty()) {
10240     raw_string_ostream OS(S);
10241     SE.getBackedgeTakenCount(L)->print(OS);
10242
10243     // false and 0 are semantically equivalent. This can happen in dead loops.
10244     replaceSubString(OS.str(), "false", "0");
10245     // Remove wrap flags, their use in SCEV is highly fragile.
10246     // FIXME: Remove this when SCEV gets smarter about them.
10247     replaceSubString(OS.str(), "<nw>", "");
10248     replaceSubString(OS.str(), "<nsw>", "");
10249     replaceSubString(OS.str(), "<nuw>", "");
10250   }
10251
10252   for (auto *R : reverse(*L))
10253     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
10254 }
10255
10256 void ScalarEvolution::verify() const {
10257   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10258
10259   // Gather stringified backedge taken counts for all loops using SCEV's caches.
10260   // FIXME: It would be much better to store actual values instead of strings,
10261   //        but SCEV pointers will change if we drop the caches.
10262   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
10263   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10264     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10265
10266   // Gather stringified backedge taken counts for all loops using a fresh
10267   // ScalarEvolution object.
10268   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10269   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10270     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
10271
10272   // Now compare whether they're the same with and without caches. This allows
10273   // verifying that no pass changed the cache.
10274   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10275          "New loops suddenly appeared!");
10276
10277   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10278                            OldE = BackedgeDumpsOld.end(),
10279                            NewI = BackedgeDumpsNew.begin();
10280        OldI != OldE; ++OldI, ++NewI) {
10281     assert(OldI->first == NewI->first && "Loop order changed!");
10282
10283     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10284     // changes.
10285     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
10286     // means that a pass is buggy or SCEV has to learn a new pattern but is
10287     // usually not harmful.
10288     if (OldI->second != NewI->second &&
10289         OldI->second.find("undef") == std::string::npos &&
10290         NewI->second.find("undef") == std::string::npos &&
10291         OldI->second != "***COULDNOTCOMPUTE***" &&
10292         NewI->second != "***COULDNOTCOMPUTE***") {
10293       dbgs() << "SCEVValidator: SCEV for loop '"
10294              << OldI->first->getHeader()->getName()
10295              << "' changed from '" << OldI->second
10296              << "' to '" << NewI->second << "'!\n";
10297       std::abort();
10298     }
10299   }
10300
10301   // TODO: Verify more things.
10302 }
10303
10304 bool ScalarEvolution::invalidate(
10305     Function &F, const PreservedAnalyses &PA,
10306     FunctionAnalysisManager::Invalidator &Inv) {
10307   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10308   // of its dependencies is invalidated.
10309   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10310   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10311          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10312          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10313          Inv.invalidate<LoopAnalysis>(F, PA);
10314 }
10315
10316 AnalysisKey ScalarEvolutionAnalysis::Key;
10317
10318 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10319                                              FunctionAnalysisManager &AM) {
10320   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10321                          AM.getResult<AssumptionAnalysis>(F),
10322                          AM.getResult<DominatorTreeAnalysis>(F),
10323                          AM.getResult<LoopAnalysis>(F));
10324 }
10325
10326 PreservedAnalyses
10327 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10328   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10329   return PreservedAnalyses::all();
10330 }
10331
10332 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10333                       "Scalar Evolution Analysis", false, true)
10334 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10335 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10336 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10337 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10338 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10339                     "Scalar Evolution Analysis", false, true)
10340 char ScalarEvolutionWrapperPass::ID = 0;
10341
10342 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10343   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10344 }
10345
10346 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10347   SE.reset(new ScalarEvolution(
10348       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10349       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10350       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10351       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10352   return false;
10353 }
10354
10355 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10356
10357 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10358   SE->print(OS);
10359 }
10360
10361 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10362   if (!VerifySCEV)
10363     return;
10364
10365   SE->verify();
10366 }
10367
10368 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10369   AU.setPreservesAll();
10370   AU.addRequiredTransitive<AssumptionCacheTracker>();
10371   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10372   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10373   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10374 }
10375
10376 const SCEVPredicate *
10377 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10378                                    const SCEVConstant *RHS) {
10379   FoldingSetNodeID ID;
10380   // Unique this node based on the arguments
10381   ID.AddInteger(SCEVPredicate::P_Equal);
10382   ID.AddPointer(LHS);
10383   ID.AddPointer(RHS);
10384   void *IP = nullptr;
10385   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10386     return S;
10387   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10388       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10389   UniquePreds.InsertNode(Eq, IP);
10390   return Eq;
10391 }
10392
10393 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10394     const SCEVAddRecExpr *AR,
10395     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10396   FoldingSetNodeID ID;
10397   // Unique this node based on the arguments
10398   ID.AddInteger(SCEVPredicate::P_Wrap);
10399   ID.AddPointer(AR);
10400   ID.AddInteger(AddedFlags);
10401   void *IP = nullptr;
10402   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10403     return S;
10404   auto *OF = new (SCEVAllocator)
10405       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10406   UniquePreds.InsertNode(OF, IP);
10407   return OF;
10408 }
10409
10410 namespace {
10411
10412 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10413 public:
10414   /// Rewrites \p S in the context of a loop L and the SCEV predication
10415   /// infrastructure.
10416   ///
10417   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10418   /// equivalences present in \p Pred.
10419   ///
10420   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10421   /// \p NewPreds such that the result will be an AddRecExpr.
10422   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10423                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10424                              SCEVUnionPredicate *Pred) {
10425     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10426     return Rewriter.visit(S);
10427   }
10428
10429   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10430                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10431                         SCEVUnionPredicate *Pred)
10432       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10433
10434   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10435     if (Pred) {
10436       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10437       for (auto *Pred : ExprPreds)
10438         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10439           if (IPred->getLHS() == Expr)
10440             return IPred->getRHS();
10441     }
10442
10443     return Expr;
10444   }
10445
10446   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10447     const SCEV *Operand = visit(Expr->getOperand());
10448     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10449     if (AR && AR->getLoop() == L && AR->isAffine()) {
10450       // This couldn't be folded because the operand didn't have the nuw
10451       // flag. Add the nusw flag as an assumption that we could make.
10452       const SCEV *Step = AR->getStepRecurrence(SE);
10453       Type *Ty = Expr->getType();
10454       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10455         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10456                                 SE.getSignExtendExpr(Step, Ty), L,
10457                                 AR->getNoWrapFlags());
10458     }
10459     return SE.getZeroExtendExpr(Operand, Expr->getType());
10460   }
10461
10462   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10463     const SCEV *Operand = visit(Expr->getOperand());
10464     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10465     if (AR && AR->getLoop() == L && AR->isAffine()) {
10466       // This couldn't be folded because the operand didn't have the nsw
10467       // flag. Add the nssw flag as an assumption that we could make.
10468       const SCEV *Step = AR->getStepRecurrence(SE);
10469       Type *Ty = Expr->getType();
10470       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10471         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10472                                 SE.getSignExtendExpr(Step, Ty), L,
10473                                 AR->getNoWrapFlags());
10474     }
10475     return SE.getSignExtendExpr(Operand, Expr->getType());
10476   }
10477
10478 private:
10479   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10480                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10481     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10482     if (!NewPreds) {
10483       // Check if we've already made this assumption.
10484       return Pred && Pred->implies(A);
10485     }
10486     NewPreds->insert(A);
10487     return true;
10488   }
10489
10490   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10491   SCEVUnionPredicate *Pred;
10492   const Loop *L;
10493 };
10494 } // end anonymous namespace
10495
10496 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10497                                                    SCEVUnionPredicate &Preds) {
10498   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10499 }
10500
10501 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10502     const SCEV *S, const Loop *L,
10503     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10504
10505   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10506   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10507   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10508
10509   if (!AddRec)
10510     return nullptr;
10511
10512   // Since the transformation was successful, we can now transfer the SCEV
10513   // predicates.
10514   for (auto *P : TransformPreds)
10515     Preds.insert(P);
10516
10517   return AddRec;
10518 }
10519
10520 /// SCEV predicates
10521 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10522                              SCEVPredicateKind Kind)
10523     : FastID(ID), Kind(Kind) {}
10524
10525 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10526                                        const SCEVUnknown *LHS,
10527                                        const SCEVConstant *RHS)
10528     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10529
10530 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10531   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10532
10533   if (!Op)
10534     return false;
10535
10536   return Op->LHS == LHS && Op->RHS == RHS;
10537 }
10538
10539 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10540
10541 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10542
10543 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10544   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10545 }
10546
10547 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10548                                      const SCEVAddRecExpr *AR,
10549                                      IncrementWrapFlags Flags)
10550     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10551
10552 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10553
10554 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10555   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10556
10557   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10558 }
10559
10560 bool SCEVWrapPredicate::isAlwaysTrue() const {
10561   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10562   IncrementWrapFlags IFlags = Flags;
10563
10564   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10565     IFlags = clearFlags(IFlags, IncrementNSSW);
10566
10567   return IFlags == IncrementAnyWrap;
10568 }
10569
10570 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10571   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10572   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10573     OS << "<nusw>";
10574   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10575     OS << "<nssw>";
10576   OS << "\n";
10577 }
10578
10579 SCEVWrapPredicate::IncrementWrapFlags
10580 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10581                                    ScalarEvolution &SE) {
10582   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10583   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10584
10585   // We can safely transfer the NSW flag as NSSW.
10586   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10587     ImpliedFlags = IncrementNSSW;
10588
10589   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10590     // If the increment is positive, the SCEV NUW flag will also imply the
10591     // WrapPredicate NUSW flag.
10592     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10593       if (Step->getValue()->getValue().isNonNegative())
10594         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10595   }
10596
10597   return ImpliedFlags;
10598 }
10599
10600 /// Union predicates don't get cached so create a dummy set ID for it.
10601 SCEVUnionPredicate::SCEVUnionPredicate()
10602     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10603
10604 bool SCEVUnionPredicate::isAlwaysTrue() const {
10605   return all_of(Preds,
10606                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10607 }
10608
10609 ArrayRef<const SCEVPredicate *>
10610 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10611   auto I = SCEVToPreds.find(Expr);
10612   if (I == SCEVToPreds.end())
10613     return ArrayRef<const SCEVPredicate *>();
10614   return I->second;
10615 }
10616
10617 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10618   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10619     return all_of(Set->Preds,
10620                   [this](const SCEVPredicate *I) { return this->implies(I); });
10621
10622   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10623   if (ScevPredsIt == SCEVToPreds.end())
10624     return false;
10625   auto &SCEVPreds = ScevPredsIt->second;
10626
10627   return any_of(SCEVPreds,
10628                 [N](const SCEVPredicate *I) { return I->implies(N); });
10629 }
10630
10631 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10632
10633 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10634   for (auto Pred : Preds)
10635     Pred->print(OS, Depth);
10636 }
10637
10638 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10639   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10640     for (auto Pred : Set->Preds)
10641       add(Pred);
10642     return;
10643   }
10644
10645   if (implies(N))
10646     return;
10647
10648   const SCEV *Key = N->getExpr();
10649   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10650                 " associated expression!");
10651
10652   SCEVToPreds[Key].push_back(N);
10653   Preds.push_back(N);
10654 }
10655
10656 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10657                                                      Loop &L)
10658     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10659
10660 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10661   const SCEV *Expr = SE.getSCEV(V);
10662   RewriteEntry &Entry = RewriteMap[Expr];
10663
10664   // If we already have an entry and the version matches, return it.
10665   if (Entry.second && Generation == Entry.first)
10666     return Entry.second;
10667
10668   // We found an entry but it's stale. Rewrite the stale entry
10669   // according to the current predicate.
10670   if (Entry.second)
10671     Expr = Entry.second;
10672
10673   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10674   Entry = {Generation, NewSCEV};
10675
10676   return NewSCEV;
10677 }
10678
10679 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10680   if (!BackedgeCount) {
10681     SCEVUnionPredicate BackedgePred;
10682     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10683     addPredicate(BackedgePred);
10684   }
10685   return BackedgeCount;
10686 }
10687
10688 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10689   if (Preds.implies(&Pred))
10690     return;
10691   Preds.add(&Pred);
10692   updateGeneration();
10693 }
10694
10695 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10696   return Preds;
10697 }
10698
10699 void PredicatedScalarEvolution::updateGeneration() {
10700   // If the generation number wrapped recompute everything.
10701   if (++Generation == 0) {
10702     for (auto &II : RewriteMap) {
10703       const SCEV *Rewritten = II.second.second;
10704       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10705     }
10706   }
10707 }
10708
10709 void PredicatedScalarEvolution::setNoOverflow(
10710     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10711   const SCEV *Expr = getSCEV(V);
10712   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10713
10714   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10715
10716   // Clear the statically implied flags.
10717   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10718   addPredicate(*SE.getWrapPredicate(AR, Flags));
10719
10720   auto II = FlagsMap.insert({V, Flags});
10721   if (!II.second)
10722     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10723 }
10724
10725 bool PredicatedScalarEvolution::hasNoOverflow(
10726     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10727   const SCEV *Expr = getSCEV(V);
10728   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10729
10730   Flags = SCEVWrapPredicate::clearFlags(
10731       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10732
10733   auto II = FlagsMap.find(V);
10734
10735   if (II != FlagsMap.end())
10736     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10737
10738   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10739 }
10740
10741 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10742   const SCEV *Expr = this->getSCEV(V);
10743   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10744   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10745
10746   if (!New)
10747     return nullptr;
10748
10749   for (auto *P : NewPreds)
10750     Preds.add(P);
10751
10752   updateGeneration();
10753   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10754   return New;
10755 }
10756
10757 PredicatedScalarEvolution::PredicatedScalarEvolution(
10758     const PredicatedScalarEvolution &Init)
10759     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10760       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10761   for (const auto &I : Init.FlagsMap)
10762     FlagsMap.insert(I);
10763 }
10764
10765 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10766   // For each block.
10767   for (auto *BB : L.getBlocks())
10768     for (auto &I : *BB) {
10769       if (!SE.isSCEVable(I.getType()))
10770         continue;
10771
10772       auto *Expr = SE.getSCEV(&I);
10773       auto II = RewriteMap.find(Expr);
10774
10775       if (II == RewriteMap.end())
10776         continue;
10777
10778       // Don't print things that are not interesting.
10779       if (II->second.second == Expr)
10780         continue;
10781
10782       OS.indent(Depth) << "[PSE]" << I << ":\n";
10783       OS.indent(Depth + 2) << *Expr << "\n";
10784       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10785     }
10786 }