]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Analysis/ScalarEvolution.cpp
MFV r331712:
[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/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/EquivalenceClasses.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/ConstantFolding.h"
81 #include "llvm/Analysis/InstructionSimplify.h"
82 #include "llvm/Analysis/LoopInfo.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/Pass.h"
115 #include "llvm/Support/Casting.h"
116 #include "llvm/Support/CommandLine.h"
117 #include "llvm/Support/Compiler.h"
118 #include "llvm/Support/Debug.h"
119 #include "llvm/Support/ErrorHandling.h"
120 #include "llvm/Support/KnownBits.h"
121 #include "llvm/Support/SaveAndRestore.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <climits>
126 #include <cstddef>
127 #include <cstdint>
128 #include <cstdlib>
129 #include <map>
130 #include <memory>
131 #include <tuple>
132 #include <utility>
133 #include <vector>
134
135 using namespace llvm;
136
137 #define DEBUG_TYPE "scalar-evolution"
138
139 STATISTIC(NumArrayLenItCounts,
140           "Number of trip counts computed with array length");
141 STATISTIC(NumTripCountsComputed,
142           "Number of loops with predictable loop counts");
143 STATISTIC(NumTripCountsNotComputed,
144           "Number of loops without predictable loop counts");
145 STATISTIC(NumBruteForceTripCountsComputed,
146           "Number of loops with trip counts computed by force");
147
148 static cl::opt<unsigned>
149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
150                         cl::desc("Maximum number of iterations SCEV will "
151                                  "symbolically execute a constant "
152                                  "derived loop"),
153                         cl::init(100));
154
155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
156 static cl::opt<bool> VerifySCEV(
157     "verify-scev", cl::Hidden,
158     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159 static cl::opt<bool>
160     VerifySCEVMap("verify-scev-maps", cl::Hidden,
161                   cl::desc("Verify no dangling value in ScalarEvolution's "
162                            "ExprValueMap (slow)"));
163
164 static cl::opt<unsigned> MulOpsInlineThreshold(
165     "scev-mulops-inline-threshold", cl::Hidden,
166     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
167     cl::init(32));
168
169 static cl::opt<unsigned> AddOpsInlineThreshold(
170     "scev-addops-inline-threshold", cl::Hidden,
171     cl::desc("Threshold for inlining addition operands into a SCEV"),
172     cl::init(500));
173
174 static cl::opt<unsigned> MaxSCEVCompareDepth(
175     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
176     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
177     cl::init(32));
178
179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
180     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
181     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
182     cl::init(2));
183
184 static cl::opt<unsigned> MaxValueCompareDepth(
185     "scalar-evolution-max-value-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive value complexity comparisons"),
187     cl::init(2));
188
189 static cl::opt<unsigned>
190     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
191                   cl::desc("Maximum depth of recursive arithmetics"),
192                   cl::init(32));
193
194 static cl::opt<unsigned> MaxConstantEvolvingDepth(
195     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
197
198 static cl::opt<unsigned>
199     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
200                 cl::desc("Maximum depth of recursive SExt/ZExt"),
201                 cl::init(8));
202
203 static cl::opt<unsigned>
204     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
205                   cl::desc("Max coefficients in AddRec during evolving"),
206                   cl::init(16));
207
208 static cl::opt<bool> VersionUnknown(
209     "scev-version-unknown", cl::Hidden,
210     cl::desc("Use predicated scalar evolution to version SCEVUnknowns"),
211     cl::init(false));
212
213 //===----------------------------------------------------------------------===//
214 //                           SCEV class definitions
215 //===----------------------------------------------------------------------===//
216
217 //===----------------------------------------------------------------------===//
218 // Implementation of the SCEV class.
219 //
220
221 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
222 LLVM_DUMP_METHOD void SCEV::dump() const {
223   print(dbgs());
224   dbgs() << '\n';
225 }
226 #endif
227
228 void SCEV::print(raw_ostream &OS) const {
229   switch (static_cast<SCEVTypes>(getSCEVType())) {
230   case scConstant:
231     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
232     return;
233   case scTruncate: {
234     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
235     const SCEV *Op = Trunc->getOperand();
236     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
237        << *Trunc->getType() << ")";
238     return;
239   }
240   case scZeroExtend: {
241     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
242     const SCEV *Op = ZExt->getOperand();
243     OS << "(zext " << *Op->getType() << " " << *Op << " to "
244        << *ZExt->getType() << ")";
245     return;
246   }
247   case scSignExtend: {
248     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
249     const SCEV *Op = SExt->getOperand();
250     OS << "(sext " << *Op->getType() << " " << *Op << " to "
251        << *SExt->getType() << ")";
252     return;
253   }
254   case scAddRecExpr: {
255     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
256     OS << "{" << *AR->getOperand(0);
257     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
258       OS << ",+," << *AR->getOperand(i);
259     OS << "}<";
260     if (AR->hasNoUnsignedWrap())
261       OS << "nuw><";
262     if (AR->hasNoSignedWrap())
263       OS << "nsw><";
264     if (AR->hasNoSelfWrap() &&
265         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
266       OS << "nw><";
267     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
268     OS << ">";
269     return;
270   }
271   case scAddExpr:
272   case scMulExpr:
273   case scUMaxExpr:
274   case scSMaxExpr: {
275     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
276     const char *OpStr = nullptr;
277     switch (NAry->getSCEVType()) {
278     case scAddExpr: OpStr = " + "; break;
279     case scMulExpr: OpStr = " * "; break;
280     case scUMaxExpr: OpStr = " umax "; break;
281     case scSMaxExpr: OpStr = " smax "; break;
282     }
283     OS << "(";
284     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
285          I != E; ++I) {
286       OS << **I;
287       if (std::next(I) != E)
288         OS << OpStr;
289     }
290     OS << ")";
291     switch (NAry->getSCEVType()) {
292     case scAddExpr:
293     case scMulExpr:
294       if (NAry->hasNoUnsignedWrap())
295         OS << "<nuw>";
296       if (NAry->hasNoSignedWrap())
297         OS << "<nsw>";
298     }
299     return;
300   }
301   case scUDivExpr: {
302     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
303     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
304     return;
305   }
306   case scUnknown: {
307     const SCEVUnknown *U = cast<SCEVUnknown>(this);
308     Type *AllocTy;
309     if (U->isSizeOf(AllocTy)) {
310       OS << "sizeof(" << *AllocTy << ")";
311       return;
312     }
313     if (U->isAlignOf(AllocTy)) {
314       OS << "alignof(" << *AllocTy << ")";
315       return;
316     }
317
318     Type *CTy;
319     Constant *FieldNo;
320     if (U->isOffsetOf(CTy, FieldNo)) {
321       OS << "offsetof(" << *CTy << ", ";
322       FieldNo->printAsOperand(OS, false);
323       OS << ")";
324       return;
325     }
326
327     // Otherwise just print it normally.
328     U->getValue()->printAsOperand(OS, false);
329     return;
330   }
331   case scCouldNotCompute:
332     OS << "***COULDNOTCOMPUTE***";
333     return;
334   }
335   llvm_unreachable("Unknown SCEV kind!");
336 }
337
338 Type *SCEV::getType() const {
339   switch (static_cast<SCEVTypes>(getSCEVType())) {
340   case scConstant:
341     return cast<SCEVConstant>(this)->getType();
342   case scTruncate:
343   case scZeroExtend:
344   case scSignExtend:
345     return cast<SCEVCastExpr>(this)->getType();
346   case scAddRecExpr:
347   case scMulExpr:
348   case scUMaxExpr:
349   case scSMaxExpr:
350     return cast<SCEVNAryExpr>(this)->getType();
351   case scAddExpr:
352     return cast<SCEVAddExpr>(this)->getType();
353   case scUDivExpr:
354     return cast<SCEVUDivExpr>(this)->getType();
355   case scUnknown:
356     return cast<SCEVUnknown>(this)->getType();
357   case scCouldNotCompute:
358     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
359   }
360   llvm_unreachable("Unknown SCEV kind!");
361 }
362
363 bool SCEV::isZero() const {
364   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
365     return SC->getValue()->isZero();
366   return false;
367 }
368
369 bool SCEV::isOne() const {
370   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
371     return SC->getValue()->isOne();
372   return false;
373 }
374
375 bool SCEV::isAllOnesValue() const {
376   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
377     return SC->getValue()->isMinusOne();
378   return false;
379 }
380
381 bool SCEV::isNonConstantNegative() const {
382   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
383   if (!Mul) return false;
384
385   // If there is a constant factor, it will be first.
386   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
387   if (!SC) return false;
388
389   // Return true if the value is negative, this matches things like (-42 * V).
390   return SC->getAPInt().isNegative();
391 }
392
393 SCEVCouldNotCompute::SCEVCouldNotCompute() :
394   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
395
396 bool SCEVCouldNotCompute::classof(const SCEV *S) {
397   return S->getSCEVType() == scCouldNotCompute;
398 }
399
400 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
401   FoldingSetNodeID ID;
402   ID.AddInteger(scConstant);
403   ID.AddPointer(V);
404   void *IP = nullptr;
405   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
406   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
407   UniqueSCEVs.InsertNode(S, IP);
408   return S;
409 }
410
411 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
412   return getConstant(ConstantInt::get(getContext(), Val));
413 }
414
415 const SCEV *
416 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
417   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
418   return getConstant(ConstantInt::get(ITy, V, isSigned));
419 }
420
421 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
422                            unsigned SCEVTy, const SCEV *op, Type *ty)
423   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
424
425 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
426                                    const SCEV *op, Type *ty)
427   : SCEVCastExpr(ID, scTruncate, op, ty) {
428   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
429          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
430          "Cannot truncate non-integer value!");
431 }
432
433 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
434                                        const SCEV *op, Type *ty)
435   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
436   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
437          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
438          "Cannot zero extend non-integer value!");
439 }
440
441 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
442                                        const SCEV *op, Type *ty)
443   : SCEVCastExpr(ID, scSignExtend, op, ty) {
444   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
445          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
446          "Cannot sign extend non-integer value!");
447 }
448
449 void SCEVUnknown::deleted() {
450   // Clear this SCEVUnknown from various maps.
451   SE->forgetMemoizedResults(this);
452
453   // Remove this SCEVUnknown from the uniquing map.
454   SE->UniqueSCEVs.RemoveNode(this);
455
456   // Release the value.
457   setValPtr(nullptr);
458 }
459
460 void SCEVUnknown::allUsesReplacedWith(Value *New) {
461   // Remove this SCEVUnknown from the uniquing map.
462   SE->UniqueSCEVs.RemoveNode(this);
463
464   // Update this SCEVUnknown to point to the new value. This is needed
465   // because there may still be outstanding SCEVs which still point to
466   // this SCEVUnknown.
467   setValPtr(New);
468 }
469
470 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
471   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
472     if (VCE->getOpcode() == Instruction::PtrToInt)
473       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
474         if (CE->getOpcode() == Instruction::GetElementPtr &&
475             CE->getOperand(0)->isNullValue() &&
476             CE->getNumOperands() == 2)
477           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
478             if (CI->isOne()) {
479               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
480                                  ->getElementType();
481               return true;
482             }
483
484   return false;
485 }
486
487 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
488   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
489     if (VCE->getOpcode() == Instruction::PtrToInt)
490       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
491         if (CE->getOpcode() == Instruction::GetElementPtr &&
492             CE->getOperand(0)->isNullValue()) {
493           Type *Ty =
494             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
495           if (StructType *STy = dyn_cast<StructType>(Ty))
496             if (!STy->isPacked() &&
497                 CE->getNumOperands() == 3 &&
498                 CE->getOperand(1)->isNullValue()) {
499               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
500                 if (CI->isOne() &&
501                     STy->getNumElements() == 2 &&
502                     STy->getElementType(0)->isIntegerTy(1)) {
503                   AllocTy = STy->getElementType(1);
504                   return true;
505                 }
506             }
507         }
508
509   return false;
510 }
511
512 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
513   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
514     if (VCE->getOpcode() == Instruction::PtrToInt)
515       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
516         if (CE->getOpcode() == Instruction::GetElementPtr &&
517             CE->getNumOperands() == 3 &&
518             CE->getOperand(0)->isNullValue() &&
519             CE->getOperand(1)->isNullValue()) {
520           Type *Ty =
521             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
522           // Ignore vector types here so that ScalarEvolutionExpander doesn't
523           // emit getelementptrs that index into vectors.
524           if (Ty->isStructTy() || Ty->isArrayTy()) {
525             CTy = Ty;
526             FieldNo = CE->getOperand(2);
527             return true;
528           }
529         }
530
531   return false;
532 }
533
534 //===----------------------------------------------------------------------===//
535 //                               SCEV Utilities
536 //===----------------------------------------------------------------------===//
537
538 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
539 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
540 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
541 /// have been previously deemed to be "equally complex" by this routine.  It is
542 /// intended to avoid exponential time complexity in cases like:
543 ///
544 ///   %a = f(%x, %y)
545 ///   %b = f(%a, %a)
546 ///   %c = f(%b, %b)
547 ///
548 ///   %d = f(%x, %y)
549 ///   %e = f(%d, %d)
550 ///   %f = f(%e, %e)
551 ///
552 ///   CompareValueComplexity(%f, %c)
553 ///
554 /// Since we do not continue running this routine on expression trees once we
555 /// have seen unequal values, there is no need to track them in the cache.
556 static int
557 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
558                        const LoopInfo *const LI, Value *LV, Value *RV,
559                        unsigned Depth) {
560   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
561     return 0;
562
563   // Order pointer values after integer values. This helps SCEVExpander form
564   // GEPs.
565   bool LIsPointer = LV->getType()->isPointerTy(),
566        RIsPointer = RV->getType()->isPointerTy();
567   if (LIsPointer != RIsPointer)
568     return (int)LIsPointer - (int)RIsPointer;
569
570   // Compare getValueID values.
571   unsigned LID = LV->getValueID(), RID = RV->getValueID();
572   if (LID != RID)
573     return (int)LID - (int)RID;
574
575   // Sort arguments by their position.
576   if (const auto *LA = dyn_cast<Argument>(LV)) {
577     const auto *RA = cast<Argument>(RV);
578     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
579     return (int)LArgNo - (int)RArgNo;
580   }
581
582   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
583     const auto *RGV = cast<GlobalValue>(RV);
584
585     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
586       auto LT = GV->getLinkage();
587       return !(GlobalValue::isPrivateLinkage(LT) ||
588                GlobalValue::isInternalLinkage(LT));
589     };
590
591     // Use the names to distinguish the two values, but only if the
592     // names are semantically important.
593     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
594       return LGV->getName().compare(RGV->getName());
595   }
596
597   // For instructions, compare their loop depth, and their operand count.  This
598   // is pretty loose.
599   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
600     const auto *RInst = cast<Instruction>(RV);
601
602     // Compare loop depths.
603     const BasicBlock *LParent = LInst->getParent(),
604                      *RParent = RInst->getParent();
605     if (LParent != RParent) {
606       unsigned LDepth = LI->getLoopDepth(LParent),
607                RDepth = LI->getLoopDepth(RParent);
608       if (LDepth != RDepth)
609         return (int)LDepth - (int)RDepth;
610     }
611
612     // Compare the number of operands.
613     unsigned LNumOps = LInst->getNumOperands(),
614              RNumOps = RInst->getNumOperands();
615     if (LNumOps != RNumOps)
616       return (int)LNumOps - (int)RNumOps;
617
618     for (unsigned Idx : seq(0u, LNumOps)) {
619       int Result =
620           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
621                                  RInst->getOperand(Idx), Depth + 1);
622       if (Result != 0)
623         return Result;
624     }
625   }
626
627   EqCacheValue.unionSets(LV, RV);
628   return 0;
629 }
630
631 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
632 // than RHS, respectively. A three-way result allows recursive comparisons to be
633 // more efficient.
634 static int CompareSCEVComplexity(
635     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
636     EquivalenceClasses<const Value *> &EqCacheValue,
637     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
638     DominatorTree &DT, unsigned Depth = 0) {
639   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
640   if (LHS == RHS)
641     return 0;
642
643   // Primarily, sort the SCEVs by their getSCEVType().
644   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
645   if (LType != RType)
646     return (int)LType - (int)RType;
647
648   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
649     return 0;
650   // Aside from the getSCEVType() ordering, the particular ordering
651   // isn't very important except that it's beneficial to be consistent,
652   // so that (a + b) and (b + a) don't end up as different expressions.
653   switch (static_cast<SCEVTypes>(LType)) {
654   case scUnknown: {
655     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
656     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
657
658     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
659                                    RU->getValue(), Depth + 1);
660     if (X == 0)
661       EqCacheSCEV.unionSets(LHS, RHS);
662     return X;
663   }
664
665   case scConstant: {
666     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
667     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
668
669     // Compare constant values.
670     const APInt &LA = LC->getAPInt();
671     const APInt &RA = RC->getAPInt();
672     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
673     if (LBitWidth != RBitWidth)
674       return (int)LBitWidth - (int)RBitWidth;
675     return LA.ult(RA) ? -1 : 1;
676   }
677
678   case scAddRecExpr: {
679     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
680     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
681
682     // There is always a dominance between two recs that are used by one SCEV,
683     // so we can safely sort recs by loop header dominance. We require such
684     // order in getAddExpr.
685     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
686     if (LLoop != RLoop) {
687       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
688       assert(LHead != RHead && "Two loops share the same header?");
689       if (DT.dominates(LHead, RHead))
690         return 1;
691       else
692         assert(DT.dominates(RHead, LHead) &&
693                "No dominance between recurrences used by one SCEV?");
694       return -1;
695     }
696
697     // Addrec complexity grows with operand count.
698     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
699     if (LNumOps != RNumOps)
700       return (int)LNumOps - (int)RNumOps;
701
702     // Compare NoWrap flags.
703     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
704       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
705
706     // Lexicographically compare.
707     for (unsigned i = 0; i != LNumOps; ++i) {
708       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
709                                     LA->getOperand(i), RA->getOperand(i), DT,
710                                     Depth + 1);
711       if (X != 0)
712         return X;
713     }
714     EqCacheSCEV.unionSets(LHS, RHS);
715     return 0;
716   }
717
718   case scAddExpr:
719   case scMulExpr:
720   case scSMaxExpr:
721   case scUMaxExpr: {
722     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
723     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
724
725     // Lexicographically compare n-ary expressions.
726     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
727     if (LNumOps != RNumOps)
728       return (int)LNumOps - (int)RNumOps;
729
730     // Compare NoWrap flags.
731     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
732       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
733
734     for (unsigned i = 0; i != LNumOps; ++i) {
735       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
736                                     LC->getOperand(i), RC->getOperand(i), DT,
737                                     Depth + 1);
738       if (X != 0)
739         return X;
740     }
741     EqCacheSCEV.unionSets(LHS, RHS);
742     return 0;
743   }
744
745   case scUDivExpr: {
746     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
747     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
748
749     // Lexicographically compare udiv expressions.
750     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
751                                   RC->getLHS(), DT, Depth + 1);
752     if (X != 0)
753       return X;
754     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
755                               RC->getRHS(), DT, Depth + 1);
756     if (X == 0)
757       EqCacheSCEV.unionSets(LHS, RHS);
758     return X;
759   }
760
761   case scTruncate:
762   case scZeroExtend:
763   case scSignExtend: {
764     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
765     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
766
767     // Compare cast expressions by operand.
768     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
769                                   LC->getOperand(), RC->getOperand(), DT,
770                                   Depth + 1);
771     if (X == 0)
772       EqCacheSCEV.unionSets(LHS, RHS);
773     return X;
774   }
775
776   case scCouldNotCompute:
777     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
778   }
779   llvm_unreachable("Unknown SCEV kind!");
780 }
781
782 /// Given a list of SCEV objects, order them by their complexity, and group
783 /// objects of the same complexity together by value.  When this routine is
784 /// finished, we know that any duplicates in the vector are consecutive and that
785 /// complexity is monotonically increasing.
786 ///
787 /// Note that we go take special precautions to ensure that we get deterministic
788 /// results from this routine.  In other words, we don't want the results of
789 /// this to depend on where the addresses of various SCEV objects happened to
790 /// land in memory.
791 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
792                               LoopInfo *LI, DominatorTree &DT) {
793   if (Ops.size() < 2) return;  // Noop
794
795   EquivalenceClasses<const SCEV *> EqCacheSCEV;
796   EquivalenceClasses<const Value *> EqCacheValue;
797   if (Ops.size() == 2) {
798     // This is the common case, which also happens to be trivially simple.
799     // Special case it.
800     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
801     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
802       std::swap(LHS, RHS);
803     return;
804   }
805
806   // Do the rough sort by complexity.
807   std::stable_sort(Ops.begin(), Ops.end(),
808                    [&](const SCEV *LHS, const SCEV *RHS) {
809                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
810                                                   LHS, RHS, DT) < 0;
811                    });
812
813   // Now that we are sorted by complexity, group elements of the same
814   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
815   // be extremely short in practice.  Note that we take this approach because we
816   // do not want to depend on the addresses of the objects we are grouping.
817   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
818     const SCEV *S = Ops[i];
819     unsigned Complexity = S->getSCEVType();
820
821     // If there are any objects of the same complexity and same value as this
822     // one, group them.
823     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
824       if (Ops[j] == S) { // Found a duplicate.
825         // Move it to immediately after i'th element.
826         std::swap(Ops[i+1], Ops[j]);
827         ++i;   // no need to rescan it.
828         if (i == e-2) return;  // Done!
829       }
830     }
831   }
832 }
833
834 // Returns the size of the SCEV S.
835 static inline int sizeOfSCEV(const SCEV *S) {
836   struct FindSCEVSize {
837     int Size = 0;
838
839     FindSCEVSize() = default;
840
841     bool follow(const SCEV *S) {
842       ++Size;
843       // Keep looking at all operands of S.
844       return true;
845     }
846
847     bool isDone() const {
848       return false;
849     }
850   };
851
852   FindSCEVSize F;
853   SCEVTraversal<FindSCEVSize> ST(F);
854   ST.visitAll(S);
855   return F.Size;
856 }
857
858 namespace {
859
860 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
861 public:
862   // Computes the Quotient and Remainder of the division of Numerator by
863   // Denominator.
864   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
865                      const SCEV *Denominator, const SCEV **Quotient,
866                      const SCEV **Remainder) {
867     assert(Numerator && Denominator && "Uninitialized SCEV");
868
869     SCEVDivision D(SE, Numerator, Denominator);
870
871     // Check for the trivial case here to avoid having to check for it in the
872     // rest of the code.
873     if (Numerator == Denominator) {
874       *Quotient = D.One;
875       *Remainder = D.Zero;
876       return;
877     }
878
879     if (Numerator->isZero()) {
880       *Quotient = D.Zero;
881       *Remainder = D.Zero;
882       return;
883     }
884
885     // A simple case when N/1. The quotient is N.
886     if (Denominator->isOne()) {
887       *Quotient = Numerator;
888       *Remainder = D.Zero;
889       return;
890     }
891
892     // Split the Denominator when it is a product.
893     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
894       const SCEV *Q, *R;
895       *Quotient = Numerator;
896       for (const SCEV *Op : T->operands()) {
897         divide(SE, *Quotient, Op, &Q, &R);
898         *Quotient = Q;
899
900         // Bail out when the Numerator is not divisible by one of the terms of
901         // the Denominator.
902         if (!R->isZero()) {
903           *Quotient = D.Zero;
904           *Remainder = Numerator;
905           return;
906         }
907       }
908       *Remainder = D.Zero;
909       return;
910     }
911
912     D.visit(Numerator);
913     *Quotient = D.Quotient;
914     *Remainder = D.Remainder;
915   }
916
917   // Except in the trivial case described above, we do not know how to divide
918   // Expr by Denominator for the following functions with empty implementation.
919   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
920   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
921   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
922   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
923   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
924   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
925   void visitUnknown(const SCEVUnknown *Numerator) {}
926   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
927
928   void visitConstant(const SCEVConstant *Numerator) {
929     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
930       APInt NumeratorVal = Numerator->getAPInt();
931       APInt DenominatorVal = D->getAPInt();
932       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
933       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
934
935       if (NumeratorBW > DenominatorBW)
936         DenominatorVal = DenominatorVal.sext(NumeratorBW);
937       else if (NumeratorBW < DenominatorBW)
938         NumeratorVal = NumeratorVal.sext(DenominatorBW);
939
940       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
941       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
942       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
943       Quotient = SE.getConstant(QuotientVal);
944       Remainder = SE.getConstant(RemainderVal);
945       return;
946     }
947   }
948
949   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
950     const SCEV *StartQ, *StartR, *StepQ, *StepR;
951     if (!Numerator->isAffine())
952       return cannotDivide(Numerator);
953     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
954     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
955     // Bail out if the types do not match.
956     Type *Ty = Denominator->getType();
957     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
958         Ty != StepQ->getType() || Ty != StepR->getType())
959       return cannotDivide(Numerator);
960     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
961                                 Numerator->getNoWrapFlags());
962     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
963                                  Numerator->getNoWrapFlags());
964   }
965
966   void visitAddExpr(const SCEVAddExpr *Numerator) {
967     SmallVector<const SCEV *, 2> Qs, Rs;
968     Type *Ty = Denominator->getType();
969
970     for (const SCEV *Op : Numerator->operands()) {
971       const SCEV *Q, *R;
972       divide(SE, Op, Denominator, &Q, &R);
973
974       // Bail out if types do not match.
975       if (Ty != Q->getType() || Ty != R->getType())
976         return cannotDivide(Numerator);
977
978       Qs.push_back(Q);
979       Rs.push_back(R);
980     }
981
982     if (Qs.size() == 1) {
983       Quotient = Qs[0];
984       Remainder = Rs[0];
985       return;
986     }
987
988     Quotient = SE.getAddExpr(Qs);
989     Remainder = SE.getAddExpr(Rs);
990   }
991
992   void visitMulExpr(const SCEVMulExpr *Numerator) {
993     SmallVector<const SCEV *, 2> Qs;
994     Type *Ty = Denominator->getType();
995
996     bool FoundDenominatorTerm = false;
997     for (const SCEV *Op : Numerator->operands()) {
998       // Bail out if types do not match.
999       if (Ty != Op->getType())
1000         return cannotDivide(Numerator);
1001
1002       if (FoundDenominatorTerm) {
1003         Qs.push_back(Op);
1004         continue;
1005       }
1006
1007       // Check whether Denominator divides one of the product operands.
1008       const SCEV *Q, *R;
1009       divide(SE, Op, Denominator, &Q, &R);
1010       if (!R->isZero()) {
1011         Qs.push_back(Op);
1012         continue;
1013       }
1014
1015       // Bail out if types do not match.
1016       if (Ty != Q->getType())
1017         return cannotDivide(Numerator);
1018
1019       FoundDenominatorTerm = true;
1020       Qs.push_back(Q);
1021     }
1022
1023     if (FoundDenominatorTerm) {
1024       Remainder = Zero;
1025       if (Qs.size() == 1)
1026         Quotient = Qs[0];
1027       else
1028         Quotient = SE.getMulExpr(Qs);
1029       return;
1030     }
1031
1032     if (!isa<SCEVUnknown>(Denominator))
1033       return cannotDivide(Numerator);
1034
1035     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1036     ValueToValueMap RewriteMap;
1037     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1038         cast<SCEVConstant>(Zero)->getValue();
1039     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1040
1041     if (Remainder->isZero()) {
1042       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1043       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1044           cast<SCEVConstant>(One)->getValue();
1045       Quotient =
1046           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1047       return;
1048     }
1049
1050     // Quotient is (Numerator - Remainder) divided by Denominator.
1051     const SCEV *Q, *R;
1052     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1053     // This SCEV does not seem to simplify: fail the division here.
1054     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1055       return cannotDivide(Numerator);
1056     divide(SE, Diff, Denominator, &Q, &R);
1057     if (R != Zero)
1058       return cannotDivide(Numerator);
1059     Quotient = Q;
1060   }
1061
1062 private:
1063   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1064                const SCEV *Denominator)
1065       : SE(S), Denominator(Denominator) {
1066     Zero = SE.getZero(Denominator->getType());
1067     One = SE.getOne(Denominator->getType());
1068
1069     // We generally do not know how to divide Expr by Denominator. We
1070     // initialize the division to a "cannot divide" state to simplify the rest
1071     // of the code.
1072     cannotDivide(Numerator);
1073   }
1074
1075   // Convenience function for giving up on the division. We set the quotient to
1076   // be equal to zero and the remainder to be equal to the numerator.
1077   void cannotDivide(const SCEV *Numerator) {
1078     Quotient = Zero;
1079     Remainder = Numerator;
1080   }
1081
1082   ScalarEvolution &SE;
1083   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1084 };
1085
1086 } // end anonymous namespace
1087
1088 //===----------------------------------------------------------------------===//
1089 //                      Simple SCEV method implementations
1090 //===----------------------------------------------------------------------===//
1091
1092 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1093 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1094                                        ScalarEvolution &SE,
1095                                        Type *ResultTy) {
1096   // Handle the simplest case efficiently.
1097   if (K == 1)
1098     return SE.getTruncateOrZeroExtend(It, ResultTy);
1099
1100   // We are using the following formula for BC(It, K):
1101   //
1102   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1103   //
1104   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1105   // overflow.  Hence, we must assure that the result of our computation is
1106   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1107   // safe in modular arithmetic.
1108   //
1109   // However, this code doesn't use exactly that formula; the formula it uses
1110   // is something like the following, where T is the number of factors of 2 in
1111   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1112   // exponentiation:
1113   //
1114   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1115   //
1116   // This formula is trivially equivalent to the previous formula.  However,
1117   // this formula can be implemented much more efficiently.  The trick is that
1118   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1119   // arithmetic.  To do exact division in modular arithmetic, all we have
1120   // to do is multiply by the inverse.  Therefore, this step can be done at
1121   // width W.
1122   //
1123   // The next issue is how to safely do the division by 2^T.  The way this
1124   // is done is by doing the multiplication step at a width of at least W + T
1125   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1126   // when we perform the division by 2^T (which is equivalent to a right shift
1127   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1128   // truncated out after the division by 2^T.
1129   //
1130   // In comparison to just directly using the first formula, this technique
1131   // is much more efficient; using the first formula requires W * K bits,
1132   // but this formula less than W + K bits. Also, the first formula requires
1133   // a division step, whereas this formula only requires multiplies and shifts.
1134   //
1135   // It doesn't matter whether the subtraction step is done in the calculation
1136   // width or the input iteration count's width; if the subtraction overflows,
1137   // the result must be zero anyway.  We prefer here to do it in the width of
1138   // the induction variable because it helps a lot for certain cases; CodeGen
1139   // isn't smart enough to ignore the overflow, which leads to much less
1140   // efficient code if the width of the subtraction is wider than the native
1141   // register width.
1142   //
1143   // (It's possible to not widen at all by pulling out factors of 2 before
1144   // the multiplication; for example, K=2 can be calculated as
1145   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1146   // extra arithmetic, so it's not an obvious win, and it gets
1147   // much more complicated for K > 3.)
1148
1149   // Protection from insane SCEVs; this bound is conservative,
1150   // but it probably doesn't matter.
1151   if (K > 1000)
1152     return SE.getCouldNotCompute();
1153
1154   unsigned W = SE.getTypeSizeInBits(ResultTy);
1155
1156   // Calculate K! / 2^T and T; we divide out the factors of two before
1157   // multiplying for calculating K! / 2^T to avoid overflow.
1158   // Other overflow doesn't matter because we only care about the bottom
1159   // W bits of the result.
1160   APInt OddFactorial(W, 1);
1161   unsigned T = 1;
1162   for (unsigned i = 3; i <= K; ++i) {
1163     APInt Mult(W, i);
1164     unsigned TwoFactors = Mult.countTrailingZeros();
1165     T += TwoFactors;
1166     Mult.lshrInPlace(TwoFactors);
1167     OddFactorial *= Mult;
1168   }
1169
1170   // We need at least W + T bits for the multiplication step
1171   unsigned CalculationBits = W + T;
1172
1173   // Calculate 2^T, at width T+W.
1174   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1175
1176   // Calculate the multiplicative inverse of K! / 2^T;
1177   // this multiplication factor will perform the exact division by
1178   // K! / 2^T.
1179   APInt Mod = APInt::getSignedMinValue(W+1);
1180   APInt MultiplyFactor = OddFactorial.zext(W+1);
1181   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1182   MultiplyFactor = MultiplyFactor.trunc(W);
1183
1184   // Calculate the product, at width T+W
1185   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1186                                                       CalculationBits);
1187   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1188   for (unsigned i = 1; i != K; ++i) {
1189     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1190     Dividend = SE.getMulExpr(Dividend,
1191                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1192   }
1193
1194   // Divide by 2^T
1195   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1196
1197   // Truncate the result, and divide by K! / 2^T.
1198
1199   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1200                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1201 }
1202
1203 /// Return the value of this chain of recurrences at the specified iteration
1204 /// number.  We can evaluate this recurrence by multiplying each element in the
1205 /// chain by the binomial coefficient corresponding to it.  In other words, we
1206 /// can evaluate {A,+,B,+,C,+,D} as:
1207 ///
1208 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1209 ///
1210 /// where BC(It, k) stands for binomial coefficient.
1211 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1212                                                 ScalarEvolution &SE) const {
1213   const SCEV *Result = getStart();
1214   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1215     // The computation is correct in the face of overflow provided that the
1216     // multiplication is performed _after_ the evaluation of the binomial
1217     // coefficient.
1218     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1219     if (isa<SCEVCouldNotCompute>(Coeff))
1220       return Coeff;
1221
1222     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1223   }
1224   return Result;
1225 }
1226
1227 //===----------------------------------------------------------------------===//
1228 //                    SCEV Expression folder implementations
1229 //===----------------------------------------------------------------------===//
1230
1231 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1232                                              Type *Ty) {
1233   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1234          "This is not a truncating conversion!");
1235   assert(isSCEVable(Ty) &&
1236          "This is not a conversion to a SCEVable type!");
1237   Ty = getEffectiveSCEVType(Ty);
1238
1239   FoldingSetNodeID ID;
1240   ID.AddInteger(scTruncate);
1241   ID.AddPointer(Op);
1242   ID.AddPointer(Ty);
1243   void *IP = nullptr;
1244   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1245
1246   // Fold if the operand is constant.
1247   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1248     return getConstant(
1249       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1250
1251   // trunc(trunc(x)) --> trunc(x)
1252   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1253     return getTruncateExpr(ST->getOperand(), Ty);
1254
1255   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1256   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1257     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1258
1259   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1260   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1261     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1262
1263   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1264   // eliminate all the truncates, or we replace other casts with truncates.
1265   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1266     SmallVector<const SCEV *, 4> Operands;
1267     bool hasTrunc = false;
1268     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1269       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1270       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1271         hasTrunc = isa<SCEVTruncateExpr>(S);
1272       Operands.push_back(S);
1273     }
1274     if (!hasTrunc)
1275       return getAddExpr(Operands);
1276     // In spite we checked in the beginning that ID is not in the cache,
1277     // it is possible that during recursion and different modification
1278     // ID came to cache, so if we found it, just return it.
1279     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1280       return S;
1281   }
1282
1283   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1284   // eliminate all the truncates, or we replace other casts with truncates.
1285   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1286     SmallVector<const SCEV *, 4> Operands;
1287     bool hasTrunc = false;
1288     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1289       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1290       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1291         hasTrunc = isa<SCEVTruncateExpr>(S);
1292       Operands.push_back(S);
1293     }
1294     if (!hasTrunc)
1295       return getMulExpr(Operands);
1296     // In spite we checked in the beginning that ID is not in the cache,
1297     // it is possible that during recursion and different modification
1298     // ID came to cache, so if we found it, just return it.
1299     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1300       return S;
1301   }
1302
1303   // If the input value is a chrec scev, truncate the chrec's operands.
1304   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1305     SmallVector<const SCEV *, 4> Operands;
1306     for (const SCEV *Op : AddRec->operands())
1307       Operands.push_back(getTruncateExpr(Op, Ty));
1308     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1309   }
1310
1311   // The cast wasn't folded; create an explicit cast node. We can reuse
1312   // the existing insert position since if we get here, we won't have
1313   // made any changes which would invalidate it.
1314   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1315                                                  Op, Ty);
1316   UniqueSCEVs.InsertNode(S, IP);
1317   addToLoopUseLists(S);
1318   return S;
1319 }
1320
1321 // Get the limit of a recurrence such that incrementing by Step cannot cause
1322 // signed overflow as long as the value of the recurrence within the
1323 // loop does not exceed this limit before incrementing.
1324 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1325                                                  ICmpInst::Predicate *Pred,
1326                                                  ScalarEvolution *SE) {
1327   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1328   if (SE->isKnownPositive(Step)) {
1329     *Pred = ICmpInst::ICMP_SLT;
1330     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1331                            SE->getSignedRangeMax(Step));
1332   }
1333   if (SE->isKnownNegative(Step)) {
1334     *Pred = ICmpInst::ICMP_SGT;
1335     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1336                            SE->getSignedRangeMin(Step));
1337   }
1338   return nullptr;
1339 }
1340
1341 // Get the limit of a recurrence such that incrementing by Step cannot cause
1342 // unsigned overflow as long as the value of the recurrence within the loop does
1343 // not exceed this limit before incrementing.
1344 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1345                                                    ICmpInst::Predicate *Pred,
1346                                                    ScalarEvolution *SE) {
1347   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1348   *Pred = ICmpInst::ICMP_ULT;
1349
1350   return SE->getConstant(APInt::getMinValue(BitWidth) -
1351                          SE->getUnsignedRangeMax(Step));
1352 }
1353
1354 namespace {
1355
1356 struct ExtendOpTraitsBase {
1357   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1358                                                           unsigned);
1359 };
1360
1361 // Used to make code generic over signed and unsigned overflow.
1362 template <typename ExtendOp> struct ExtendOpTraits {
1363   // Members present:
1364   //
1365   // static const SCEV::NoWrapFlags WrapType;
1366   //
1367   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1368   //
1369   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1370   //                                           ICmpInst::Predicate *Pred,
1371   //                                           ScalarEvolution *SE);
1372 };
1373
1374 template <>
1375 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1376   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1377
1378   static const GetExtendExprTy GetExtendExpr;
1379
1380   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1381                                              ICmpInst::Predicate *Pred,
1382                                              ScalarEvolution *SE) {
1383     return getSignedOverflowLimitForStep(Step, Pred, SE);
1384   }
1385 };
1386
1387 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1388     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1389
1390 template <>
1391 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1392   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1393
1394   static const GetExtendExprTy GetExtendExpr;
1395
1396   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1397                                              ICmpInst::Predicate *Pred,
1398                                              ScalarEvolution *SE) {
1399     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1400   }
1401 };
1402
1403 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1404     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1405
1406 } // end anonymous namespace
1407
1408 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1409 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1410 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1411 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1412 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1413 // expression "Step + sext/zext(PreIncAR)" is congruent with
1414 // "sext/zext(PostIncAR)"
1415 template <typename ExtendOpTy>
1416 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1417                                         ScalarEvolution *SE, unsigned Depth) {
1418   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1419   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1420
1421   const Loop *L = AR->getLoop();
1422   const SCEV *Start = AR->getStart();
1423   const SCEV *Step = AR->getStepRecurrence(*SE);
1424
1425   // Check for a simple looking step prior to loop entry.
1426   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1427   if (!SA)
1428     return nullptr;
1429
1430   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1431   // subtraction is expensive. For this purpose, perform a quick and dirty
1432   // difference, by checking for Step in the operand list.
1433   SmallVector<const SCEV *, 4> DiffOps;
1434   for (const SCEV *Op : SA->operands())
1435     if (Op != Step)
1436       DiffOps.push_back(Op);
1437
1438   if (DiffOps.size() == SA->getNumOperands())
1439     return nullptr;
1440
1441   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1442   // `Step`:
1443
1444   // 1. NSW/NUW flags on the step increment.
1445   auto PreStartFlags =
1446     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1447   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1448   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1449       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1450
1451   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1452   // "S+X does not sign/unsign-overflow".
1453   //
1454
1455   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1456   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1457       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1458     return PreStart;
1459
1460   // 2. Direct overflow check on the step operation's expression.
1461   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1462   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1463   const SCEV *OperandExtendedStart =
1464       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1465                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1466   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1467     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1468       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1469       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1470       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1471       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1472     }
1473     return PreStart;
1474   }
1475
1476   // 3. Loop precondition.
1477   ICmpInst::Predicate Pred;
1478   const SCEV *OverflowLimit =
1479       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1480
1481   if (OverflowLimit &&
1482       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1483     return PreStart;
1484
1485   return nullptr;
1486 }
1487
1488 // Get the normalized zero or sign extended expression for this AddRec's Start.
1489 template <typename ExtendOpTy>
1490 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1491                                         ScalarEvolution *SE,
1492                                         unsigned Depth) {
1493   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1494
1495   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1496   if (!PreStart)
1497     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1498
1499   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1500                                              Depth),
1501                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1502 }
1503
1504 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1505 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1506 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1507 //
1508 // Formally:
1509 //
1510 //     {S,+,X} == {S-T,+,X} + T
1511 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1512 //
1513 // If ({S-T,+,X} + T) does not overflow  ... (1)
1514 //
1515 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1516 //
1517 // If {S-T,+,X} does not overflow  ... (2)
1518 //
1519 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1520 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1521 //
1522 // If (S-T)+T does not overflow  ... (3)
1523 //
1524 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1525 //      == {Ext(S),+,Ext(X)} == LHS
1526 //
1527 // Thus, if (1), (2) and (3) are true for some T, then
1528 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1529 //
1530 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1531 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1532 // to check for (1) and (2).
1533 //
1534 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1535 // is `Delta` (defined below).
1536 template <typename ExtendOpTy>
1537 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1538                                                 const SCEV *Step,
1539                                                 const Loop *L) {
1540   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1541
1542   // We restrict `Start` to a constant to prevent SCEV from spending too much
1543   // time here.  It is correct (but more expensive) to continue with a
1544   // non-constant `Start` and do a general SCEV subtraction to compute
1545   // `PreStart` below.
1546   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1547   if (!StartC)
1548     return false;
1549
1550   APInt StartAI = StartC->getAPInt();
1551
1552   for (unsigned Delta : {-2, -1, 1, 2}) {
1553     const SCEV *PreStart = getConstant(StartAI - Delta);
1554
1555     FoldingSetNodeID ID;
1556     ID.AddInteger(scAddRecExpr);
1557     ID.AddPointer(PreStart);
1558     ID.AddPointer(Step);
1559     ID.AddPointer(L);
1560     void *IP = nullptr;
1561     const auto *PreAR =
1562       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1563
1564     // Give up if we don't already have the add recurrence we need because
1565     // actually constructing an add recurrence is relatively expensive.
1566     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1567       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1568       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1569       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1570           DeltaS, &Pred, this);
1571       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1572         return true;
1573     }
1574   }
1575
1576   return false;
1577 }
1578
1579 const SCEV *
1580 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1581   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1582          "This is not an extending conversion!");
1583   assert(isSCEVable(Ty) &&
1584          "This is not a conversion to a SCEVable type!");
1585   Ty = getEffectiveSCEVType(Ty);
1586
1587   // Fold if the operand is constant.
1588   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1589     return getConstant(
1590       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1591
1592   // zext(zext(x)) --> zext(x)
1593   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1594     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1595
1596   // Before doing any expensive analysis, check to see if we've already
1597   // computed a SCEV for this Op and Ty.
1598   FoldingSetNodeID ID;
1599   ID.AddInteger(scZeroExtend);
1600   ID.AddPointer(Op);
1601   ID.AddPointer(Ty);
1602   void *IP = nullptr;
1603   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1604   if (Depth > MaxExtDepth) {
1605     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1606                                                      Op, Ty);
1607     UniqueSCEVs.InsertNode(S, IP);
1608     addToLoopUseLists(S);
1609     return S;
1610   }
1611
1612   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1613   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1614     // It's possible the bits taken off by the truncate were all zero bits. If
1615     // so, we should be able to simplify this further.
1616     const SCEV *X = ST->getOperand();
1617     ConstantRange CR = getUnsignedRange(X);
1618     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1619     unsigned NewBits = getTypeSizeInBits(Ty);
1620     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1621             CR.zextOrTrunc(NewBits)))
1622       return getTruncateOrZeroExtend(X, Ty);
1623   }
1624
1625   // If the input value is a chrec scev, and we can prove that the value
1626   // did not overflow the old, smaller, value, we can zero extend all of the
1627   // operands (often constants).  This allows analysis of something like
1628   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1629   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1630     if (AR->isAffine()) {
1631       const SCEV *Start = AR->getStart();
1632       const SCEV *Step = AR->getStepRecurrence(*this);
1633       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1634       const Loop *L = AR->getLoop();
1635
1636       if (!AR->hasNoUnsignedWrap()) {
1637         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1638         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1639       }
1640
1641       // If we have special knowledge that this addrec won't overflow,
1642       // we don't need to do any further analysis.
1643       if (AR->hasNoUnsignedWrap())
1644         return getAddRecExpr(
1645             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1646             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1647
1648       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1649       // Note that this serves two purposes: It filters out loops that are
1650       // simply not analyzable, and it covers the case where this code is
1651       // being called from within backedge-taken count analysis, such that
1652       // attempting to ask for the backedge-taken count would likely result
1653       // in infinite recursion. In the later case, the analysis code will
1654       // cope with a conservative value, and it will take care to purge
1655       // that value once it has finished.
1656       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1657       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1658         // Manually compute the final value for AR, checking for
1659         // overflow.
1660
1661         // Check whether the backedge-taken count can be losslessly casted to
1662         // the addrec's type. The count is always unsigned.
1663         const SCEV *CastedMaxBECount =
1664           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1665         const SCEV *RecastedMaxBECount =
1666           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1667         if (MaxBECount == RecastedMaxBECount) {
1668           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1669           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1670           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1671                                         SCEV::FlagAnyWrap, Depth + 1);
1672           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1673                                                           SCEV::FlagAnyWrap,
1674                                                           Depth + 1),
1675                                                WideTy, Depth + 1);
1676           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1677           const SCEV *WideMaxBECount =
1678             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1679           const SCEV *OperandExtendedAdd =
1680             getAddExpr(WideStart,
1681                        getMulExpr(WideMaxBECount,
1682                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1683                                   SCEV::FlagAnyWrap, Depth + 1),
1684                        SCEV::FlagAnyWrap, Depth + 1);
1685           if (ZAdd == OperandExtendedAdd) {
1686             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1687             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1688             // Return the expression with the addrec on the outside.
1689             return getAddRecExpr(
1690                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1691                                                          Depth + 1),
1692                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1693                 AR->getNoWrapFlags());
1694           }
1695           // Similar to above, only this time treat the step value as signed.
1696           // This covers loops that count down.
1697           OperandExtendedAdd =
1698             getAddExpr(WideStart,
1699                        getMulExpr(WideMaxBECount,
1700                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1701                                   SCEV::FlagAnyWrap, Depth + 1),
1702                        SCEV::FlagAnyWrap, Depth + 1);
1703           if (ZAdd == OperandExtendedAdd) {
1704             // Cache knowledge of AR NW, which is propagated to this AddRec.
1705             // Negative step causes unsigned wrap, but it still can't self-wrap.
1706             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1707             // Return the expression with the addrec on the outside.
1708             return getAddRecExpr(
1709                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1710                                                          Depth + 1),
1711                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1712                 AR->getNoWrapFlags());
1713           }
1714         }
1715       }
1716
1717       // Normally, in the cases we can prove no-overflow via a
1718       // backedge guarding condition, we can also compute a backedge
1719       // taken count for the loop.  The exceptions are assumptions and
1720       // guards present in the loop -- SCEV is not great at exploiting
1721       // these to compute max backedge taken counts, but can still use
1722       // these to prove lack of overflow.  Use this fact to avoid
1723       // doing extra work that may not pay off.
1724       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1725           !AC.assumptions().empty()) {
1726         // If the backedge is guarded by a comparison with the pre-inc
1727         // value the addrec is safe. Also, if the entry is guarded by
1728         // a comparison with the start value and the backedge is
1729         // guarded by a comparison with the post-inc value, the addrec
1730         // is safe.
1731         if (isKnownPositive(Step)) {
1732           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1733                                       getUnsignedRangeMax(Step));
1734           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1735               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1736                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1737                                            AR->getPostIncExpr(*this), N))) {
1738             // Cache knowledge of AR NUW, which is propagated to this
1739             // AddRec.
1740             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1741             // Return the expression with the addrec on the outside.
1742             return getAddRecExpr(
1743                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1744                                                          Depth + 1),
1745                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1746                 AR->getNoWrapFlags());
1747           }
1748         } else if (isKnownNegative(Step)) {
1749           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1750                                       getSignedRangeMin(Step));
1751           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1752               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1753                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1754                                            AR->getPostIncExpr(*this), N))) {
1755             // Cache knowledge of AR NW, which is propagated to this
1756             // AddRec.  Negative step causes unsigned wrap, but it
1757             // still can't self-wrap.
1758             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1759             // Return the expression with the addrec on the outside.
1760             return getAddRecExpr(
1761                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1762                                                          Depth + 1),
1763                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1764                 AR->getNoWrapFlags());
1765           }
1766         }
1767       }
1768
1769       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1770         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1771         return getAddRecExpr(
1772             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1773             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1774       }
1775     }
1776
1777   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1778     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1779     if (SA->hasNoUnsignedWrap()) {
1780       // If the addition does not unsign overflow then we can, by definition,
1781       // commute the zero extension with the addition operation.
1782       SmallVector<const SCEV *, 4> Ops;
1783       for (const auto *Op : SA->operands())
1784         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1785       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1786     }
1787   }
1788
1789   // The cast wasn't folded; create an explicit cast node.
1790   // Recompute the insert position, as it may have been invalidated.
1791   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1792   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1793                                                    Op, Ty);
1794   UniqueSCEVs.InsertNode(S, IP);
1795   addToLoopUseLists(S);
1796   return S;
1797 }
1798
1799 const SCEV *
1800 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1801   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1802          "This is not an extending conversion!");
1803   assert(isSCEVable(Ty) &&
1804          "This is not a conversion to a SCEVable type!");
1805   Ty = getEffectiveSCEVType(Ty);
1806
1807   // Fold if the operand is constant.
1808   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1809     return getConstant(
1810       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1811
1812   // sext(sext(x)) --> sext(x)
1813   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1814     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1815
1816   // sext(zext(x)) --> zext(x)
1817   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1818     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1819
1820   // Before doing any expensive analysis, check to see if we've already
1821   // computed a SCEV for this Op and Ty.
1822   FoldingSetNodeID ID;
1823   ID.AddInteger(scSignExtend);
1824   ID.AddPointer(Op);
1825   ID.AddPointer(Ty);
1826   void *IP = nullptr;
1827   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1828   // Limit recursion depth.
1829   if (Depth > MaxExtDepth) {
1830     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1831                                                      Op, Ty);
1832     UniqueSCEVs.InsertNode(S, IP);
1833     addToLoopUseLists(S);
1834     return S;
1835   }
1836
1837   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1838   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1839     // It's possible the bits taken off by the truncate were all sign bits. If
1840     // so, we should be able to simplify this further.
1841     const SCEV *X = ST->getOperand();
1842     ConstantRange CR = getSignedRange(X);
1843     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1844     unsigned NewBits = getTypeSizeInBits(Ty);
1845     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1846             CR.sextOrTrunc(NewBits)))
1847       return getTruncateOrSignExtend(X, Ty);
1848   }
1849
1850   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1851   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1852     if (SA->getNumOperands() == 2) {
1853       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1854       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1855       if (SMul && SC1) {
1856         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1857           const APInt &C1 = SC1->getAPInt();
1858           const APInt &C2 = SC2->getAPInt();
1859           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1860               C2.ugt(C1) && C2.isPowerOf2())
1861             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1862                               getSignExtendExpr(SMul, Ty, Depth + 1),
1863                               SCEV::FlagAnyWrap, Depth + 1);
1864         }
1865       }
1866     }
1867
1868     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1869     if (SA->hasNoSignedWrap()) {
1870       // If the addition does not sign overflow then we can, by definition,
1871       // commute the sign extension with the addition operation.
1872       SmallVector<const SCEV *, 4> Ops;
1873       for (const auto *Op : SA->operands())
1874         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1875       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1876     }
1877   }
1878   // If the input value is a chrec scev, and we can prove that the value
1879   // did not overflow the old, smaller, value, we can sign extend all of the
1880   // operands (often constants).  This allows analysis of something like
1881   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1882   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1883     if (AR->isAffine()) {
1884       const SCEV *Start = AR->getStart();
1885       const SCEV *Step = AR->getStepRecurrence(*this);
1886       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1887       const Loop *L = AR->getLoop();
1888
1889       if (!AR->hasNoSignedWrap()) {
1890         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1891         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1892       }
1893
1894       // If we have special knowledge that this addrec won't overflow,
1895       // we don't need to do any further analysis.
1896       if (AR->hasNoSignedWrap())
1897         return getAddRecExpr(
1898             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1899             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1900
1901       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1902       // Note that this serves two purposes: It filters out loops that are
1903       // simply not analyzable, and it covers the case where this code is
1904       // being called from within backedge-taken count analysis, such that
1905       // attempting to ask for the backedge-taken count would likely result
1906       // in infinite recursion. In the later case, the analysis code will
1907       // cope with a conservative value, and it will take care to purge
1908       // that value once it has finished.
1909       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1910       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1911         // Manually compute the final value for AR, checking for
1912         // overflow.
1913
1914         // Check whether the backedge-taken count can be losslessly casted to
1915         // the addrec's type. The count is always unsigned.
1916         const SCEV *CastedMaxBECount =
1917           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1918         const SCEV *RecastedMaxBECount =
1919           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1920         if (MaxBECount == RecastedMaxBECount) {
1921           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1922           // Check whether Start+Step*MaxBECount has no signed overflow.
1923           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1924                                         SCEV::FlagAnyWrap, Depth + 1);
1925           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1926                                                           SCEV::FlagAnyWrap,
1927                                                           Depth + 1),
1928                                                WideTy, Depth + 1);
1929           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1930           const SCEV *WideMaxBECount =
1931             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1932           const SCEV *OperandExtendedAdd =
1933             getAddExpr(WideStart,
1934                        getMulExpr(WideMaxBECount,
1935                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1936                                   SCEV::FlagAnyWrap, Depth + 1),
1937                        SCEV::FlagAnyWrap, Depth + 1);
1938           if (SAdd == OperandExtendedAdd) {
1939             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1940             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1941             // Return the expression with the addrec on the outside.
1942             return getAddRecExpr(
1943                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1944                                                          Depth + 1),
1945                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1946                 AR->getNoWrapFlags());
1947           }
1948           // Similar to above, only this time treat the step value as unsigned.
1949           // This covers loops that count up with an unsigned step.
1950           OperandExtendedAdd =
1951             getAddExpr(WideStart,
1952                        getMulExpr(WideMaxBECount,
1953                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1954                                   SCEV::FlagAnyWrap, Depth + 1),
1955                        SCEV::FlagAnyWrap, Depth + 1);
1956           if (SAdd == OperandExtendedAdd) {
1957             // If AR wraps around then
1958             //
1959             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1960             // => SAdd != OperandExtendedAdd
1961             //
1962             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1963             // (SAdd == OperandExtendedAdd => AR is NW)
1964
1965             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1966
1967             // Return the expression with the addrec on the outside.
1968             return getAddRecExpr(
1969                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1970                                                          Depth + 1),
1971                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1972                 AR->getNoWrapFlags());
1973           }
1974         }
1975       }
1976
1977       // Normally, in the cases we can prove no-overflow via a
1978       // backedge guarding condition, we can also compute a backedge
1979       // taken count for the loop.  The exceptions are assumptions and
1980       // guards present in the loop -- SCEV is not great at exploiting
1981       // these to compute max backedge taken counts, but can still use
1982       // these to prove lack of overflow.  Use this fact to avoid
1983       // doing extra work that may not pay off.
1984
1985       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1986           !AC.assumptions().empty()) {
1987         // If the backedge is guarded by a comparison with the pre-inc
1988         // value the addrec is safe. Also, if the entry is guarded by
1989         // a comparison with the start value and the backedge is
1990         // guarded by a comparison with the post-inc value, the addrec
1991         // is safe.
1992         ICmpInst::Predicate Pred;
1993         const SCEV *OverflowLimit =
1994             getSignedOverflowLimitForStep(Step, &Pred, this);
1995         if (OverflowLimit &&
1996             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1997              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1998               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1999                                           OverflowLimit)))) {
2000           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2001           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2002           return getAddRecExpr(
2003               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2004               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2005         }
2006       }
2007
2008       // If Start and Step are constants, check if we can apply this
2009       // transformation:
2010       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2011       auto *SC1 = dyn_cast<SCEVConstant>(Start);
2012       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2013       if (SC1 && SC2) {
2014         const APInt &C1 = SC1->getAPInt();
2015         const APInt &C2 = SC2->getAPInt();
2016         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2017             C2.isPowerOf2()) {
2018           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2019           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2020                                             AR->getNoWrapFlags());
2021           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2022                             SCEV::FlagAnyWrap, Depth + 1);
2023         }
2024       }
2025
2026       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2027         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2028         return getAddRecExpr(
2029             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2030             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2031       }
2032     }
2033
2034   // If the input value is provably positive and we could not simplify
2035   // away the sext build a zext instead.
2036   if (isKnownNonNegative(Op))
2037     return getZeroExtendExpr(Op, Ty, Depth + 1);
2038
2039   // The cast wasn't folded; create an explicit cast node.
2040   // Recompute the insert position, as it may have been invalidated.
2041   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2042   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2043                                                    Op, Ty);
2044   UniqueSCEVs.InsertNode(S, IP);
2045   addToLoopUseLists(S);
2046   return S;
2047 }
2048
2049 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2050 /// unspecified bits out to the given type.
2051 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2052                                               Type *Ty) {
2053   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2054          "This is not an extending conversion!");
2055   assert(isSCEVable(Ty) &&
2056          "This is not a conversion to a SCEVable type!");
2057   Ty = getEffectiveSCEVType(Ty);
2058
2059   // Sign-extend negative constants.
2060   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2061     if (SC->getAPInt().isNegative())
2062       return getSignExtendExpr(Op, Ty);
2063
2064   // Peel off a truncate cast.
2065   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2066     const SCEV *NewOp = T->getOperand();
2067     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2068       return getAnyExtendExpr(NewOp, Ty);
2069     return getTruncateOrNoop(NewOp, Ty);
2070   }
2071
2072   // Next try a zext cast. If the cast is folded, use it.
2073   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2074   if (!isa<SCEVZeroExtendExpr>(ZExt))
2075     return ZExt;
2076
2077   // Next try a sext cast. If the cast is folded, use it.
2078   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2079   if (!isa<SCEVSignExtendExpr>(SExt))
2080     return SExt;
2081
2082   // Force the cast to be folded into the operands of an addrec.
2083   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2084     SmallVector<const SCEV *, 4> Ops;
2085     for (const SCEV *Op : AR->operands())
2086       Ops.push_back(getAnyExtendExpr(Op, Ty));
2087     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2088   }
2089
2090   // If the expression is obviously signed, use the sext cast value.
2091   if (isa<SCEVSMaxExpr>(Op))
2092     return SExt;
2093
2094   // Absent any other information, use the zext cast value.
2095   return ZExt;
2096 }
2097
2098 /// Process the given Ops list, which is a list of operands to be added under
2099 /// the given scale, update the given map. This is a helper function for
2100 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2101 /// that would form an add expression like this:
2102 ///
2103 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2104 ///
2105 /// where A and B are constants, update the map with these values:
2106 ///
2107 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2108 ///
2109 /// and add 13 + A*B*29 to AccumulatedConstant.
2110 /// This will allow getAddRecExpr to produce this:
2111 ///
2112 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2113 ///
2114 /// This form often exposes folding opportunities that are hidden in
2115 /// the original operand list.
2116 ///
2117 /// Return true iff it appears that any interesting folding opportunities
2118 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2119 /// the common case where no interesting opportunities are present, and
2120 /// is also used as a check to avoid infinite recursion.
2121 static bool
2122 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2123                              SmallVectorImpl<const SCEV *> &NewOps,
2124                              APInt &AccumulatedConstant,
2125                              const SCEV *const *Ops, size_t NumOperands,
2126                              const APInt &Scale,
2127                              ScalarEvolution &SE) {
2128   bool Interesting = false;
2129
2130   // Iterate over the add operands. They are sorted, with constants first.
2131   unsigned i = 0;
2132   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2133     ++i;
2134     // Pull a buried constant out to the outside.
2135     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2136       Interesting = true;
2137     AccumulatedConstant += Scale * C->getAPInt();
2138   }
2139
2140   // Next comes everything else. We're especially interested in multiplies
2141   // here, but they're in the middle, so just visit the rest with one loop.
2142   for (; i != NumOperands; ++i) {
2143     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2144     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2145       APInt NewScale =
2146           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2147       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2148         // A multiplication of a constant with another add; recurse.
2149         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2150         Interesting |=
2151           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2152                                        Add->op_begin(), Add->getNumOperands(),
2153                                        NewScale, SE);
2154       } else {
2155         // A multiplication of a constant with some other value. Update
2156         // the map.
2157         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2158         const SCEV *Key = SE.getMulExpr(MulOps);
2159         auto Pair = M.insert({Key, NewScale});
2160         if (Pair.second) {
2161           NewOps.push_back(Pair.first->first);
2162         } else {
2163           Pair.first->second += NewScale;
2164           // The map already had an entry for this value, which may indicate
2165           // a folding opportunity.
2166           Interesting = true;
2167         }
2168       }
2169     } else {
2170       // An ordinary operand. Update the map.
2171       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2172           M.insert({Ops[i], Scale});
2173       if (Pair.second) {
2174         NewOps.push_back(Pair.first->first);
2175       } else {
2176         Pair.first->second += Scale;
2177         // The map already had an entry for this value, which may indicate
2178         // a folding opportunity.
2179         Interesting = true;
2180       }
2181     }
2182   }
2183
2184   return Interesting;
2185 }
2186
2187 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2188 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2189 // can't-overflow flags for the operation if possible.
2190 static SCEV::NoWrapFlags
2191 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2192                       const SmallVectorImpl<const SCEV *> &Ops,
2193                       SCEV::NoWrapFlags Flags) {
2194   using namespace std::placeholders;
2195
2196   using OBO = OverflowingBinaryOperator;
2197
2198   bool CanAnalyze =
2199       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2200   (void)CanAnalyze;
2201   assert(CanAnalyze && "don't call from other places!");
2202
2203   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2204   SCEV::NoWrapFlags SignOrUnsignWrap =
2205       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2206
2207   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2208   auto IsKnownNonNegative = [&](const SCEV *S) {
2209     return SE->isKnownNonNegative(S);
2210   };
2211
2212   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2213     Flags =
2214         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2215
2216   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2217
2218   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2219       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2220
2221     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2222     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2223
2224     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2225     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2226       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2227           Instruction::Add, C, OBO::NoSignedWrap);
2228       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2229         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2230     }
2231     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2232       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2233           Instruction::Add, C, OBO::NoUnsignedWrap);
2234       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2235         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2236     }
2237   }
2238
2239   return Flags;
2240 }
2241
2242 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2243   if (!isLoopInvariant(S, L))
2244     return false;
2245   // If a value depends on a SCEVUnknown which is defined after the loop, we
2246   // conservatively assume that we cannot calculate it at the loop's entry.
2247   struct FindDominatedSCEVUnknown {
2248     bool Found = false;
2249     const Loop *L;
2250     DominatorTree &DT;
2251     LoopInfo &LI;
2252
2253     FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2254         : L(L), DT(DT), LI(LI) {}
2255
2256     bool checkSCEVUnknown(const SCEVUnknown *SU) {
2257       if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2258         if (DT.dominates(L->getHeader(), I->getParent()))
2259           Found = true;
2260         else
2261           assert(DT.dominates(I->getParent(), L->getHeader()) &&
2262                  "No dominance relationship between SCEV and loop?");
2263       }
2264       return false;
2265     }
2266
2267     bool follow(const SCEV *S) {
2268       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2269       case scConstant:
2270         return false;
2271       case scAddRecExpr:
2272       case scTruncate:
2273       case scZeroExtend:
2274       case scSignExtend:
2275       case scAddExpr:
2276       case scMulExpr:
2277       case scUMaxExpr:
2278       case scSMaxExpr:
2279       case scUDivExpr:
2280         return true;
2281       case scUnknown:
2282         return checkSCEVUnknown(cast<SCEVUnknown>(S));
2283       case scCouldNotCompute:
2284         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2285       }
2286       return false;
2287     }
2288
2289     bool isDone() { return Found; }
2290   };
2291
2292   FindDominatedSCEVUnknown FSU(L, DT, LI);
2293   SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2294   ST.visitAll(S);
2295   return !FSU.Found;
2296 }
2297
2298 /// Get a canonical add expression, or something simpler if possible.
2299 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2300                                         SCEV::NoWrapFlags Flags,
2301                                         unsigned Depth) {
2302   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2303          "only nuw or nsw allowed");
2304   assert(!Ops.empty() && "Cannot get empty add!");
2305   if (Ops.size() == 1) return Ops[0];
2306 #ifndef NDEBUG
2307   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2308   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2309     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2310            "SCEVAddExpr operand types don't match!");
2311 #endif
2312
2313   // Sort by complexity, this groups all similar expression types together.
2314   GroupByComplexity(Ops, &LI, DT);
2315
2316   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2317
2318   // If there are any constants, fold them together.
2319   unsigned Idx = 0;
2320   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2321     ++Idx;
2322     assert(Idx < Ops.size());
2323     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2324       // We found two constants, fold them together!
2325       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2326       if (Ops.size() == 2) return Ops[0];
2327       Ops.erase(Ops.begin()+1);  // Erase the folded element
2328       LHSC = cast<SCEVConstant>(Ops[0]);
2329     }
2330
2331     // If we are left with a constant zero being added, strip it off.
2332     if (LHSC->getValue()->isZero()) {
2333       Ops.erase(Ops.begin());
2334       --Idx;
2335     }
2336
2337     if (Ops.size() == 1) return Ops[0];
2338   }
2339
2340   // Limit recursion calls depth.
2341   if (Depth > MaxArithDepth)
2342     return getOrCreateAddExpr(Ops, Flags);
2343
2344   // Okay, check to see if the same value occurs in the operand list more than
2345   // once.  If so, merge them together into an multiply expression.  Since we
2346   // sorted the list, these values are required to be adjacent.
2347   Type *Ty = Ops[0]->getType();
2348   bool FoundMatch = false;
2349   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2350     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2351       // Scan ahead to count how many equal operands there are.
2352       unsigned Count = 2;
2353       while (i+Count != e && Ops[i+Count] == Ops[i])
2354         ++Count;
2355       // Merge the values into a multiply.
2356       const SCEV *Scale = getConstant(Ty, Count);
2357       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2358       if (Ops.size() == Count)
2359         return Mul;
2360       Ops[i] = Mul;
2361       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2362       --i; e -= Count - 1;
2363       FoundMatch = true;
2364     }
2365   if (FoundMatch)
2366     return getAddExpr(Ops, Flags, Depth + 1);
2367
2368   // Check for truncates. If all the operands are truncated from the same
2369   // type, see if factoring out the truncate would permit the result to be
2370   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2371   // if the contents of the resulting outer trunc fold to something simple.
2372   auto FindTruncSrcType = [&]() -> Type * {
2373     // We're ultimately looking to fold an addrec of truncs and muls of only
2374     // constants and truncs, so if we find any other types of SCEV
2375     // as operands of the addrec then we bail and return nullptr here.
2376     // Otherwise, we return the type of the operand of a trunc that we find.
2377     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2378       return T->getOperand()->getType();
2379     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2380       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2381       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2382         return T->getOperand()->getType();
2383     }
2384     return nullptr;
2385   };
2386   if (auto *SrcType = FindTruncSrcType()) {
2387     SmallVector<const SCEV *, 8> LargeOps;
2388     bool Ok = true;
2389     // Check all the operands to see if they can be represented in the
2390     // source type of the truncate.
2391     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2392       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2393         if (T->getOperand()->getType() != SrcType) {
2394           Ok = false;
2395           break;
2396         }
2397         LargeOps.push_back(T->getOperand());
2398       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2399         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2400       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2401         SmallVector<const SCEV *, 8> LargeMulOps;
2402         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2403           if (const SCEVTruncateExpr *T =
2404                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2405             if (T->getOperand()->getType() != SrcType) {
2406               Ok = false;
2407               break;
2408             }
2409             LargeMulOps.push_back(T->getOperand());
2410           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2411             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2412           } else {
2413             Ok = false;
2414             break;
2415           }
2416         }
2417         if (Ok)
2418           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2419       } else {
2420         Ok = false;
2421         break;
2422       }
2423     }
2424     if (Ok) {
2425       // Evaluate the expression in the larger type.
2426       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2427       // If it folds to something simple, use it. Otherwise, don't.
2428       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2429         return getTruncateExpr(Fold, Ty);
2430     }
2431   }
2432
2433   // Skip past any other cast SCEVs.
2434   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2435     ++Idx;
2436
2437   // If there are add operands they would be next.
2438   if (Idx < Ops.size()) {
2439     bool DeletedAdd = false;
2440     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2441       if (Ops.size() > AddOpsInlineThreshold ||
2442           Add->getNumOperands() > AddOpsInlineThreshold)
2443         break;
2444       // If we have an add, expand the add operands onto the end of the operands
2445       // list.
2446       Ops.erase(Ops.begin()+Idx);
2447       Ops.append(Add->op_begin(), Add->op_end());
2448       DeletedAdd = true;
2449     }
2450
2451     // If we deleted at least one add, we added operands to the end of the list,
2452     // and they are not necessarily sorted.  Recurse to resort and resimplify
2453     // any operands we just acquired.
2454     if (DeletedAdd)
2455       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2456   }
2457
2458   // Skip over the add expression until we get to a multiply.
2459   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2460     ++Idx;
2461
2462   // Check to see if there are any folding opportunities present with
2463   // operands multiplied by constant values.
2464   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2465     uint64_t BitWidth = getTypeSizeInBits(Ty);
2466     DenseMap<const SCEV *, APInt> M;
2467     SmallVector<const SCEV *, 8> NewOps;
2468     APInt AccumulatedConstant(BitWidth, 0);
2469     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2470                                      Ops.data(), Ops.size(),
2471                                      APInt(BitWidth, 1), *this)) {
2472       struct APIntCompare {
2473         bool operator()(const APInt &LHS, const APInt &RHS) const {
2474           return LHS.ult(RHS);
2475         }
2476       };
2477
2478       // Some interesting folding opportunity is present, so its worthwhile to
2479       // re-generate the operands list. Group the operands by constant scale,
2480       // to avoid multiplying by the same constant scale multiple times.
2481       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2482       for (const SCEV *NewOp : NewOps)
2483         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2484       // Re-generate the operands list.
2485       Ops.clear();
2486       if (AccumulatedConstant != 0)
2487         Ops.push_back(getConstant(AccumulatedConstant));
2488       for (auto &MulOp : MulOpLists)
2489         if (MulOp.first != 0)
2490           Ops.push_back(getMulExpr(
2491               getConstant(MulOp.first),
2492               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2493               SCEV::FlagAnyWrap, Depth + 1));
2494       if (Ops.empty())
2495         return getZero(Ty);
2496       if (Ops.size() == 1)
2497         return Ops[0];
2498       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2499     }
2500   }
2501
2502   // If we are adding something to a multiply expression, make sure the
2503   // something is not already an operand of the multiply.  If so, merge it into
2504   // the multiply.
2505   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2506     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2507     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2508       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2509       if (isa<SCEVConstant>(MulOpSCEV))
2510         continue;
2511       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2512         if (MulOpSCEV == Ops[AddOp]) {
2513           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2514           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2515           if (Mul->getNumOperands() != 2) {
2516             // If the multiply has more than two operands, we must get the
2517             // Y*Z term.
2518             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2519                                                 Mul->op_begin()+MulOp);
2520             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2521             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2522           }
2523           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2524           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2525           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2526                                             SCEV::FlagAnyWrap, Depth + 1);
2527           if (Ops.size() == 2) return OuterMul;
2528           if (AddOp < Idx) {
2529             Ops.erase(Ops.begin()+AddOp);
2530             Ops.erase(Ops.begin()+Idx-1);
2531           } else {
2532             Ops.erase(Ops.begin()+Idx);
2533             Ops.erase(Ops.begin()+AddOp-1);
2534           }
2535           Ops.push_back(OuterMul);
2536           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2537         }
2538
2539       // Check this multiply against other multiplies being added together.
2540       for (unsigned OtherMulIdx = Idx+1;
2541            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2542            ++OtherMulIdx) {
2543         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2544         // If MulOp occurs in OtherMul, we can fold the two multiplies
2545         // together.
2546         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2547              OMulOp != e; ++OMulOp)
2548           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2549             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2550             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2551             if (Mul->getNumOperands() != 2) {
2552               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2553                                                   Mul->op_begin()+MulOp);
2554               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2555               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2556             }
2557             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2558             if (OtherMul->getNumOperands() != 2) {
2559               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2560                                                   OtherMul->op_begin()+OMulOp);
2561               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2562               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2563             }
2564             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2565             const SCEV *InnerMulSum =
2566                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2567             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2568                                               SCEV::FlagAnyWrap, Depth + 1);
2569             if (Ops.size() == 2) return OuterMul;
2570             Ops.erase(Ops.begin()+Idx);
2571             Ops.erase(Ops.begin()+OtherMulIdx-1);
2572             Ops.push_back(OuterMul);
2573             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2574           }
2575       }
2576     }
2577   }
2578
2579   // If there are any add recurrences in the operands list, see if any other
2580   // added values are loop invariant.  If so, we can fold them into the
2581   // recurrence.
2582   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2583     ++Idx;
2584
2585   // Scan over all recurrences, trying to fold loop invariants into them.
2586   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2587     // Scan all of the other operands to this add and add them to the vector if
2588     // they are loop invariant w.r.t. the recurrence.
2589     SmallVector<const SCEV *, 8> LIOps;
2590     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2591     const Loop *AddRecLoop = AddRec->getLoop();
2592     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2593       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2594         LIOps.push_back(Ops[i]);
2595         Ops.erase(Ops.begin()+i);
2596         --i; --e;
2597       }
2598
2599     // If we found some loop invariants, fold them into the recurrence.
2600     if (!LIOps.empty()) {
2601       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2602       LIOps.push_back(AddRec->getStart());
2603
2604       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2605                                              AddRec->op_end());
2606       // This follows from the fact that the no-wrap flags on the outer add
2607       // expression are applicable on the 0th iteration, when the add recurrence
2608       // will be equal to its start value.
2609       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2610
2611       // Build the new addrec. Propagate the NUW and NSW flags if both the
2612       // outer add and the inner addrec are guaranteed to have no overflow.
2613       // Always propagate NW.
2614       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2615       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2616
2617       // If all of the other operands were loop invariant, we are done.
2618       if (Ops.size() == 1) return NewRec;
2619
2620       // Otherwise, add the folded AddRec by the non-invariant parts.
2621       for (unsigned i = 0;; ++i)
2622         if (Ops[i] == AddRec) {
2623           Ops[i] = NewRec;
2624           break;
2625         }
2626       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2627     }
2628
2629     // Okay, if there weren't any loop invariants to be folded, check to see if
2630     // there are multiple AddRec's with the same loop induction variable being
2631     // added together.  If so, we can fold them.
2632     for (unsigned OtherIdx = Idx+1;
2633          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2634          ++OtherIdx) {
2635       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2636       // so that the 1st found AddRecExpr is dominated by all others.
2637       assert(DT.dominates(
2638            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2639            AddRec->getLoop()->getHeader()) &&
2640         "AddRecExprs are not sorted in reverse dominance order?");
2641       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2642         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2643         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2644                                                AddRec->op_end());
2645         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2646              ++OtherIdx) {
2647           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2648           if (OtherAddRec->getLoop() == AddRecLoop) {
2649             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2650                  i != e; ++i) {
2651               if (i >= AddRecOps.size()) {
2652                 AddRecOps.append(OtherAddRec->op_begin()+i,
2653                                  OtherAddRec->op_end());
2654                 break;
2655               }
2656               SmallVector<const SCEV *, 2> TwoOps = {
2657                   AddRecOps[i], OtherAddRec->getOperand(i)};
2658               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2659             }
2660             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2661           }
2662         }
2663         // Step size has changed, so we cannot guarantee no self-wraparound.
2664         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2665         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2666       }
2667     }
2668
2669     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2670     // next one.
2671   }
2672
2673   // Okay, it looks like we really DO need an add expr.  Check to see if we
2674   // already have one, otherwise create a new one.
2675   return getOrCreateAddExpr(Ops, Flags);
2676 }
2677
2678 const SCEV *
2679 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2680                                     SCEV::NoWrapFlags Flags) {
2681   FoldingSetNodeID ID;
2682   ID.AddInteger(scAddExpr);
2683   for (const SCEV *Op : Ops)
2684     ID.AddPointer(Op);
2685   void *IP = nullptr;
2686   SCEVAddExpr *S =
2687       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2688   if (!S) {
2689     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2690     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2691     S = new (SCEVAllocator)
2692         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2693     UniqueSCEVs.InsertNode(S, IP);
2694     addToLoopUseLists(S);
2695   }
2696   S->setNoWrapFlags(Flags);
2697   return S;
2698 }
2699
2700 const SCEV *
2701 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2702                                     SCEV::NoWrapFlags Flags) {
2703   FoldingSetNodeID ID;
2704   ID.AddInteger(scMulExpr);
2705   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2706     ID.AddPointer(Ops[i]);
2707   void *IP = nullptr;
2708   SCEVMulExpr *S =
2709     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2710   if (!S) {
2711     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2712     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2713     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2714                                         O, Ops.size());
2715     UniqueSCEVs.InsertNode(S, IP);
2716     addToLoopUseLists(S);
2717   }
2718   S->setNoWrapFlags(Flags);
2719   return S;
2720 }
2721
2722 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2723   uint64_t k = i*j;
2724   if (j > 1 && k / j != i) Overflow = true;
2725   return k;
2726 }
2727
2728 /// Compute the result of "n choose k", the binomial coefficient.  If an
2729 /// intermediate computation overflows, Overflow will be set and the return will
2730 /// be garbage. Overflow is not cleared on absence of overflow.
2731 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2732   // We use the multiplicative formula:
2733   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2734   // At each iteration, we take the n-th term of the numeral and divide by the
2735   // (k-n)th term of the denominator.  This division will always produce an
2736   // integral result, and helps reduce the chance of overflow in the
2737   // intermediate computations. However, we can still overflow even when the
2738   // final result would fit.
2739
2740   if (n == 0 || n == k) return 1;
2741   if (k > n) return 0;
2742
2743   if (k > n/2)
2744     k = n-k;
2745
2746   uint64_t r = 1;
2747   for (uint64_t i = 1; i <= k; ++i) {
2748     r = umul_ov(r, n-(i-1), Overflow);
2749     r /= i;
2750   }
2751   return r;
2752 }
2753
2754 /// Determine if any of the operands in this SCEV are a constant or if
2755 /// any of the add or multiply expressions in this SCEV contain a constant.
2756 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2757   struct FindConstantInAddMulChain {
2758     bool FoundConstant = false;
2759
2760     bool follow(const SCEV *S) {
2761       FoundConstant |= isa<SCEVConstant>(S);
2762       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2763     }
2764
2765     bool isDone() const {
2766       return FoundConstant;
2767     }
2768   };
2769
2770   FindConstantInAddMulChain F;
2771   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2772   ST.visitAll(StartExpr);
2773   return F.FoundConstant;
2774 }
2775
2776 /// Get a canonical multiply expression, or something simpler if possible.
2777 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2778                                         SCEV::NoWrapFlags Flags,
2779                                         unsigned Depth) {
2780   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2781          "only nuw or nsw allowed");
2782   assert(!Ops.empty() && "Cannot get empty mul!");
2783   if (Ops.size() == 1) return Ops[0];
2784 #ifndef NDEBUG
2785   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2786   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2787     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2788            "SCEVMulExpr operand types don't match!");
2789 #endif
2790
2791   // Sort by complexity, this groups all similar expression types together.
2792   GroupByComplexity(Ops, &LI, DT);
2793
2794   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2795
2796   // Limit recursion calls depth.
2797   if (Depth > MaxArithDepth)
2798     return getOrCreateMulExpr(Ops, Flags);
2799
2800   // If there are any constants, fold them together.
2801   unsigned Idx = 0;
2802   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2803
2804     // C1*(C2+V) -> C1*C2 + C1*V
2805     if (Ops.size() == 2)
2806         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2807           // If any of Add's ops are Adds or Muls with a constant,
2808           // apply this transformation as well.
2809           if (Add->getNumOperands() == 2)
2810             // TODO: There are some cases where this transformation is not
2811             // profitable, for example:
2812             // Add = (C0 + X) * Y + Z.
2813             // Maybe the scope of this transformation should be narrowed down.
2814             if (containsConstantInAddMulChain(Add))
2815               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2816                                            SCEV::FlagAnyWrap, Depth + 1),
2817                                 getMulExpr(LHSC, Add->getOperand(1),
2818                                            SCEV::FlagAnyWrap, Depth + 1),
2819                                 SCEV::FlagAnyWrap, Depth + 1);
2820
2821     ++Idx;
2822     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2823       // We found two constants, fold them together!
2824       ConstantInt *Fold =
2825           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2826       Ops[0] = getConstant(Fold);
2827       Ops.erase(Ops.begin()+1);  // Erase the folded element
2828       if (Ops.size() == 1) return Ops[0];
2829       LHSC = cast<SCEVConstant>(Ops[0]);
2830     }
2831
2832     // If we are left with a constant one being multiplied, strip it off.
2833     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2834       Ops.erase(Ops.begin());
2835       --Idx;
2836     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2837       // If we have a multiply of zero, it will always be zero.
2838       return Ops[0];
2839     } else if (Ops[0]->isAllOnesValue()) {
2840       // If we have a mul by -1 of an add, try distributing the -1 among the
2841       // add operands.
2842       if (Ops.size() == 2) {
2843         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2844           SmallVector<const SCEV *, 4> NewOps;
2845           bool AnyFolded = false;
2846           for (const SCEV *AddOp : Add->operands()) {
2847             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2848                                          Depth + 1);
2849             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2850             NewOps.push_back(Mul);
2851           }
2852           if (AnyFolded)
2853             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2854         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2855           // Negation preserves a recurrence's no self-wrap property.
2856           SmallVector<const SCEV *, 4> Operands;
2857           for (const SCEV *AddRecOp : AddRec->operands())
2858             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2859                                           Depth + 1));
2860
2861           return getAddRecExpr(Operands, AddRec->getLoop(),
2862                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2863         }
2864       }
2865     }
2866
2867     if (Ops.size() == 1)
2868       return Ops[0];
2869   }
2870
2871   // Skip over the add expression until we get to a multiply.
2872   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2873     ++Idx;
2874
2875   // If there are mul operands inline them all into this expression.
2876   if (Idx < Ops.size()) {
2877     bool DeletedMul = false;
2878     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2879       if (Ops.size() > MulOpsInlineThreshold)
2880         break;
2881       // If we have an mul, expand the mul operands onto the end of the
2882       // operands list.
2883       Ops.erase(Ops.begin()+Idx);
2884       Ops.append(Mul->op_begin(), Mul->op_end());
2885       DeletedMul = true;
2886     }
2887
2888     // If we deleted at least one mul, we added operands to the end of the
2889     // list, and they are not necessarily sorted.  Recurse to resort and
2890     // resimplify any operands we just acquired.
2891     if (DeletedMul)
2892       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2893   }
2894
2895   // If there are any add recurrences in the operands list, see if any other
2896   // added values are loop invariant.  If so, we can fold them into the
2897   // recurrence.
2898   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2899     ++Idx;
2900
2901   // Scan over all recurrences, trying to fold loop invariants into them.
2902   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2903     // Scan all of the other operands to this mul and add them to the vector
2904     // if they are loop invariant w.r.t. the recurrence.
2905     SmallVector<const SCEV *, 8> LIOps;
2906     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2907     const Loop *AddRecLoop = AddRec->getLoop();
2908     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2909       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2910         LIOps.push_back(Ops[i]);
2911         Ops.erase(Ops.begin()+i);
2912         --i; --e;
2913       }
2914
2915     // If we found some loop invariants, fold them into the recurrence.
2916     if (!LIOps.empty()) {
2917       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2918       SmallVector<const SCEV *, 4> NewOps;
2919       NewOps.reserve(AddRec->getNumOperands());
2920       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2921       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2922         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2923                                     SCEV::FlagAnyWrap, Depth + 1));
2924
2925       // Build the new addrec. Propagate the NUW and NSW flags if both the
2926       // outer mul and the inner addrec are guaranteed to have no overflow.
2927       //
2928       // No self-wrap cannot be guaranteed after changing the step size, but
2929       // will be inferred if either NUW or NSW is true.
2930       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2931       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2932
2933       // If all of the other operands were loop invariant, we are done.
2934       if (Ops.size() == 1) return NewRec;
2935
2936       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2937       for (unsigned i = 0;; ++i)
2938         if (Ops[i] == AddRec) {
2939           Ops[i] = NewRec;
2940           break;
2941         }
2942       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2943     }
2944
2945     // Okay, if there weren't any loop invariants to be folded, check to see
2946     // if there are multiple AddRec's with the same loop induction variable
2947     // being multiplied together.  If so, we can fold them.
2948
2949     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2950     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2951     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2952     //   ]]],+,...up to x=2n}.
2953     // Note that the arguments to choose() are always integers with values
2954     // known at compile time, never SCEV objects.
2955     //
2956     // The implementation avoids pointless extra computations when the two
2957     // addrec's are of different length (mathematically, it's equivalent to
2958     // an infinite stream of zeros on the right).
2959     bool OpsModified = false;
2960     for (unsigned OtherIdx = Idx+1;
2961          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2962          ++OtherIdx) {
2963       const SCEVAddRecExpr *OtherAddRec =
2964         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2965       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2966         continue;
2967
2968       // Limit max number of arguments to avoid creation of unreasonably big
2969       // SCEVAddRecs with very complex operands.
2970       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2971           MaxAddRecSize)
2972         continue;
2973
2974       bool Overflow = false;
2975       Type *Ty = AddRec->getType();
2976       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2977       SmallVector<const SCEV*, 7> AddRecOps;
2978       for (int x = 0, xe = AddRec->getNumOperands() +
2979              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2980         const SCEV *Term = getZero(Ty);
2981         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2982           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2983           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2984                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2985                z < ze && !Overflow; ++z) {
2986             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2987             uint64_t Coeff;
2988             if (LargerThan64Bits)
2989               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2990             else
2991               Coeff = Coeff1*Coeff2;
2992             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2993             const SCEV *Term1 = AddRec->getOperand(y-z);
2994             const SCEV *Term2 = OtherAddRec->getOperand(z);
2995             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2996                                                SCEV::FlagAnyWrap, Depth + 1),
2997                               SCEV::FlagAnyWrap, Depth + 1);
2998           }
2999         }
3000         AddRecOps.push_back(Term);
3001       }
3002       if (!Overflow) {
3003         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3004                                               SCEV::FlagAnyWrap);
3005         if (Ops.size() == 2) return NewAddRec;
3006         Ops[Idx] = NewAddRec;
3007         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3008         OpsModified = true;
3009         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3010         if (!AddRec)
3011           break;
3012       }
3013     }
3014     if (OpsModified)
3015       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3016
3017     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3018     // next one.
3019   }
3020
3021   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3022   // already have one, otherwise create a new one.
3023   return getOrCreateMulExpr(Ops, Flags);
3024 }
3025
3026 /// Represents an unsigned remainder expression based on unsigned division.
3027 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3028                                          const SCEV *RHS) {
3029   assert(getEffectiveSCEVType(LHS->getType()) ==
3030          getEffectiveSCEVType(RHS->getType()) &&
3031          "SCEVURemExpr operand types don't match!");
3032
3033   // Short-circuit easy cases
3034   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3035     // If constant is one, the result is trivial
3036     if (RHSC->getValue()->isOne())
3037       return getZero(LHS->getType()); // X urem 1 --> 0
3038
3039     // If constant is a power of two, fold into a zext(trunc(LHS)).
3040     if (RHSC->getAPInt().isPowerOf2()) {
3041       Type *FullTy = LHS->getType();
3042       Type *TruncTy =
3043           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3044       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3045     }
3046   }
3047
3048   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3049   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3050   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3051   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3052 }
3053
3054 /// Get a canonical unsigned division expression, or something simpler if
3055 /// possible.
3056 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3057                                          const SCEV *RHS) {
3058   assert(getEffectiveSCEVType(LHS->getType()) ==
3059          getEffectiveSCEVType(RHS->getType()) &&
3060          "SCEVUDivExpr operand types don't match!");
3061
3062   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3063     if (RHSC->getValue()->isOne())
3064       return LHS;                               // X udiv 1 --> x
3065     // If the denominator is zero, the result of the udiv is undefined. Don't
3066     // try to analyze it, because the resolution chosen here may differ from
3067     // the resolution chosen in other parts of the compiler.
3068     if (!RHSC->getValue()->isZero()) {
3069       // Determine if the division can be folded into the operands of
3070       // its operands.
3071       // TODO: Generalize this to non-constants by using known-bits information.
3072       Type *Ty = LHS->getType();
3073       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3074       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3075       // For non-power-of-two values, effectively round the value up to the
3076       // nearest power of two.
3077       if (!RHSC->getAPInt().isPowerOf2())
3078         ++MaxShiftAmt;
3079       IntegerType *ExtTy =
3080         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3081       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3082         if (const SCEVConstant *Step =
3083             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3084           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3085           const APInt &StepInt = Step->getAPInt();
3086           const APInt &DivInt = RHSC->getAPInt();
3087           if (!StepInt.urem(DivInt) &&
3088               getZeroExtendExpr(AR, ExtTy) ==
3089               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3090                             getZeroExtendExpr(Step, ExtTy),
3091                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3092             SmallVector<const SCEV *, 4> Operands;
3093             for (const SCEV *Op : AR->operands())
3094               Operands.push_back(getUDivExpr(Op, RHS));
3095             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3096           }
3097           /// Get a canonical UDivExpr for a recurrence.
3098           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3099           // We can currently only fold X%N if X is constant.
3100           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3101           if (StartC && !DivInt.urem(StepInt) &&
3102               getZeroExtendExpr(AR, ExtTy) ==
3103               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3104                             getZeroExtendExpr(Step, ExtTy),
3105                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3106             const APInt &StartInt = StartC->getAPInt();
3107             const APInt &StartRem = StartInt.urem(StepInt);
3108             if (StartRem != 0)
3109               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3110                                   AR->getLoop(), SCEV::FlagNW);
3111           }
3112         }
3113       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3114       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3115         SmallVector<const SCEV *, 4> Operands;
3116         for (const SCEV *Op : M->operands())
3117           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3118         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3119           // Find an operand that's safely divisible.
3120           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3121             const SCEV *Op = M->getOperand(i);
3122             const SCEV *Div = getUDivExpr(Op, RHSC);
3123             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3124               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3125                                                       M->op_end());
3126               Operands[i] = Div;
3127               return getMulExpr(Operands);
3128             }
3129           }
3130       }
3131       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3132       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3133         SmallVector<const SCEV *, 4> Operands;
3134         for (const SCEV *Op : A->operands())
3135           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3136         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3137           Operands.clear();
3138           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3139             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3140             if (isa<SCEVUDivExpr>(Op) ||
3141                 getMulExpr(Op, RHS) != A->getOperand(i))
3142               break;
3143             Operands.push_back(Op);
3144           }
3145           if (Operands.size() == A->getNumOperands())
3146             return getAddExpr(Operands);
3147         }
3148       }
3149
3150       // Fold if both operands are constant.
3151       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3152         Constant *LHSCV = LHSC->getValue();
3153         Constant *RHSCV = RHSC->getValue();
3154         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3155                                                                    RHSCV)));
3156       }
3157     }
3158   }
3159
3160   FoldingSetNodeID ID;
3161   ID.AddInteger(scUDivExpr);
3162   ID.AddPointer(LHS);
3163   ID.AddPointer(RHS);
3164   void *IP = nullptr;
3165   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3166   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3167                                              LHS, RHS);
3168   UniqueSCEVs.InsertNode(S, IP);
3169   addToLoopUseLists(S);
3170   return S;
3171 }
3172
3173 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3174   APInt A = C1->getAPInt().abs();
3175   APInt B = C2->getAPInt().abs();
3176   uint32_t ABW = A.getBitWidth();
3177   uint32_t BBW = B.getBitWidth();
3178
3179   if (ABW > BBW)
3180     B = B.zext(ABW);
3181   else if (ABW < BBW)
3182     A = A.zext(BBW);
3183
3184   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3185 }
3186
3187 /// Get a canonical unsigned division expression, or something simpler if
3188 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3189 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3190 /// it's not exact because the udiv may be clearing bits.
3191 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3192                                               const SCEV *RHS) {
3193   // TODO: we could try to find factors in all sorts of things, but for now we
3194   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3195   // end of this file for inspiration.
3196
3197   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3198   if (!Mul || !Mul->hasNoUnsignedWrap())
3199     return getUDivExpr(LHS, RHS);
3200
3201   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3202     // If the mulexpr multiplies by a constant, then that constant must be the
3203     // first element of the mulexpr.
3204     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3205       if (LHSCst == RHSCst) {
3206         SmallVector<const SCEV *, 2> Operands;
3207         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3208         return getMulExpr(Operands);
3209       }
3210
3211       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3212       // that there's a factor provided by one of the other terms. We need to
3213       // check.
3214       APInt Factor = gcd(LHSCst, RHSCst);
3215       if (!Factor.isIntN(1)) {
3216         LHSCst =
3217             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3218         RHSCst =
3219             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3220         SmallVector<const SCEV *, 2> Operands;
3221         Operands.push_back(LHSCst);
3222         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3223         LHS = getMulExpr(Operands);
3224         RHS = RHSCst;
3225         Mul = dyn_cast<SCEVMulExpr>(LHS);
3226         if (!Mul)
3227           return getUDivExactExpr(LHS, RHS);
3228       }
3229     }
3230   }
3231
3232   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3233     if (Mul->getOperand(i) == RHS) {
3234       SmallVector<const SCEV *, 2> Operands;
3235       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3236       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3237       return getMulExpr(Operands);
3238     }
3239   }
3240
3241   return getUDivExpr(LHS, RHS);
3242 }
3243
3244 /// Get an add recurrence expression for the specified loop.  Simplify the
3245 /// expression as much as possible.
3246 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3247                                            const Loop *L,
3248                                            SCEV::NoWrapFlags Flags) {
3249   SmallVector<const SCEV *, 4> Operands;
3250   Operands.push_back(Start);
3251   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3252     if (StepChrec->getLoop() == L) {
3253       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3254       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3255     }
3256
3257   Operands.push_back(Step);
3258   return getAddRecExpr(Operands, L, Flags);
3259 }
3260
3261 /// Get an add recurrence expression for the specified loop.  Simplify the
3262 /// expression as much as possible.
3263 const SCEV *
3264 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3265                                const Loop *L, SCEV::NoWrapFlags Flags) {
3266   if (Operands.size() == 1) return Operands[0];
3267 #ifndef NDEBUG
3268   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3269   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3270     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3271            "SCEVAddRecExpr operand types don't match!");
3272   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3273     assert(isLoopInvariant(Operands[i], L) &&
3274            "SCEVAddRecExpr operand is not loop-invariant!");
3275 #endif
3276
3277   if (Operands.back()->isZero()) {
3278     Operands.pop_back();
3279     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3280   }
3281
3282   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3283   // use that information to infer NUW and NSW flags. However, computing a
3284   // BE count requires calling getAddRecExpr, so we may not yet have a
3285   // meaningful BE count at this point (and if we don't, we'd be stuck
3286   // with a SCEVCouldNotCompute as the cached BE count).
3287
3288   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3289
3290   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3291   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3292     const Loop *NestedLoop = NestedAR->getLoop();
3293     if (L->contains(NestedLoop)
3294             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3295             : (!NestedLoop->contains(L) &&
3296                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3297       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3298                                                   NestedAR->op_end());
3299       Operands[0] = NestedAR->getStart();
3300       // AddRecs require their operands be loop-invariant with respect to their
3301       // loops. Don't perform this transformation if it would break this
3302       // requirement.
3303       bool AllInvariant = all_of(
3304           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3305
3306       if (AllInvariant) {
3307         // Create a recurrence for the outer loop with the same step size.
3308         //
3309         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3310         // inner recurrence has the same property.
3311         SCEV::NoWrapFlags OuterFlags =
3312           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3313
3314         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3315         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3316           return isLoopInvariant(Op, NestedLoop);
3317         });
3318
3319         if (AllInvariant) {
3320           // Ok, both add recurrences are valid after the transformation.
3321           //
3322           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3323           // the outer recurrence has the same property.
3324           SCEV::NoWrapFlags InnerFlags =
3325             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3326           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3327         }
3328       }
3329       // Reset Operands to its original state.
3330       Operands[0] = NestedAR;
3331     }
3332   }
3333
3334   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3335   // already have one, otherwise create a new one.
3336   FoldingSetNodeID ID;
3337   ID.AddInteger(scAddRecExpr);
3338   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3339     ID.AddPointer(Operands[i]);
3340   ID.AddPointer(L);
3341   void *IP = nullptr;
3342   SCEVAddRecExpr *S =
3343     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3344   if (!S) {
3345     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3346     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3347     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3348                                            O, Operands.size(), L);
3349     UniqueSCEVs.InsertNode(S, IP);
3350     addToLoopUseLists(S);
3351   }
3352   S->setNoWrapFlags(Flags);
3353   return S;
3354 }
3355
3356 const SCEV *
3357 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3358                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3359   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3360   // getSCEV(Base)->getType() has the same address space as Base->getType()
3361   // because SCEV::getType() preserves the address space.
3362   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3363   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3364   // instruction to its SCEV, because the Instruction may be guarded by control
3365   // flow and the no-overflow bits may not be valid for the expression in any
3366   // context. This can be fixed similarly to how these flags are handled for
3367   // adds.
3368   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3369                                              : SCEV::FlagAnyWrap;
3370
3371   const SCEV *TotalOffset = getZero(IntPtrTy);
3372   // The array size is unimportant. The first thing we do on CurTy is getting
3373   // its element type.
3374   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3375   for (const SCEV *IndexExpr : IndexExprs) {
3376     // Compute the (potentially symbolic) offset in bytes for this index.
3377     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3378       // For a struct, add the member offset.
3379       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3380       unsigned FieldNo = Index->getZExtValue();
3381       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3382
3383       // Add the field offset to the running total offset.
3384       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3385
3386       // Update CurTy to the type of the field at Index.
3387       CurTy = STy->getTypeAtIndex(Index);
3388     } else {
3389       // Update CurTy to its element type.
3390       CurTy = cast<SequentialType>(CurTy)->getElementType();
3391       // For an array, add the element offset, explicitly scaled.
3392       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3393       // Getelementptr indices are signed.
3394       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3395
3396       // Multiply the index by the element size to compute the element offset.
3397       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3398
3399       // Add the element offset to the running total offset.
3400       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3401     }
3402   }
3403
3404   // Add the total offset from all the GEP indices to the base.
3405   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3406 }
3407
3408 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3409                                          const SCEV *RHS) {
3410   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3411   return getSMaxExpr(Ops);
3412 }
3413
3414 const SCEV *
3415 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3416   assert(!Ops.empty() && "Cannot get empty smax!");
3417   if (Ops.size() == 1) return Ops[0];
3418 #ifndef NDEBUG
3419   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3420   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3421     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3422            "SCEVSMaxExpr operand types don't match!");
3423 #endif
3424
3425   // Sort by complexity, this groups all similar expression types together.
3426   GroupByComplexity(Ops, &LI, DT);
3427
3428   // If there are any constants, fold them together.
3429   unsigned Idx = 0;
3430   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3431     ++Idx;
3432     assert(Idx < Ops.size());
3433     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3434       // We found two constants, fold them together!
3435       ConstantInt *Fold = ConstantInt::get(
3436           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3437       Ops[0] = getConstant(Fold);
3438       Ops.erase(Ops.begin()+1);  // Erase the folded element
3439       if (Ops.size() == 1) return Ops[0];
3440       LHSC = cast<SCEVConstant>(Ops[0]);
3441     }
3442
3443     // If we are left with a constant minimum-int, strip it off.
3444     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3445       Ops.erase(Ops.begin());
3446       --Idx;
3447     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3448       // If we have an smax with a constant maximum-int, it will always be
3449       // maximum-int.
3450       return Ops[0];
3451     }
3452
3453     if (Ops.size() == 1) return Ops[0];
3454   }
3455
3456   // Find the first SMax
3457   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3458     ++Idx;
3459
3460   // Check to see if one of the operands is an SMax. If so, expand its operands
3461   // onto our operand list, and recurse to simplify.
3462   if (Idx < Ops.size()) {
3463     bool DeletedSMax = false;
3464     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3465       Ops.erase(Ops.begin()+Idx);
3466       Ops.append(SMax->op_begin(), SMax->op_end());
3467       DeletedSMax = true;
3468     }
3469
3470     if (DeletedSMax)
3471       return getSMaxExpr(Ops);
3472   }
3473
3474   // Okay, check to see if the same value occurs in the operand list twice.  If
3475   // so, delete one.  Since we sorted the list, these values are required to
3476   // be adjacent.
3477   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3478     //  X smax Y smax Y  -->  X smax Y
3479     //  X smax Y         -->  X, if X is always greater than Y
3480     if (Ops[i] == Ops[i+1] ||
3481         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3482       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3483       --i; --e;
3484     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3485       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3486       --i; --e;
3487     }
3488
3489   if (Ops.size() == 1) return Ops[0];
3490
3491   assert(!Ops.empty() && "Reduced smax down to nothing!");
3492
3493   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3494   // already have one, otherwise create a new one.
3495   FoldingSetNodeID ID;
3496   ID.AddInteger(scSMaxExpr);
3497   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3498     ID.AddPointer(Ops[i]);
3499   void *IP = nullptr;
3500   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3501   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3502   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3503   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3504                                              O, Ops.size());
3505   UniqueSCEVs.InsertNode(S, IP);
3506   addToLoopUseLists(S);
3507   return S;
3508 }
3509
3510 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3511                                          const SCEV *RHS) {
3512   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3513   return getUMaxExpr(Ops);
3514 }
3515
3516 const SCEV *
3517 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3518   assert(!Ops.empty() && "Cannot get empty umax!");
3519   if (Ops.size() == 1) return Ops[0];
3520 #ifndef NDEBUG
3521   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3522   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3523     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3524            "SCEVUMaxExpr operand types don't match!");
3525 #endif
3526
3527   // Sort by complexity, this groups all similar expression types together.
3528   GroupByComplexity(Ops, &LI, DT);
3529
3530   // If there are any constants, fold them together.
3531   unsigned Idx = 0;
3532   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3533     ++Idx;
3534     assert(Idx < Ops.size());
3535     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3536       // We found two constants, fold them together!
3537       ConstantInt *Fold = ConstantInt::get(
3538           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3539       Ops[0] = getConstant(Fold);
3540       Ops.erase(Ops.begin()+1);  // Erase the folded element
3541       if (Ops.size() == 1) return Ops[0];
3542       LHSC = cast<SCEVConstant>(Ops[0]);
3543     }
3544
3545     // If we are left with a constant minimum-int, strip it off.
3546     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3547       Ops.erase(Ops.begin());
3548       --Idx;
3549     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3550       // If we have an umax with a constant maximum-int, it will always be
3551       // maximum-int.
3552       return Ops[0];
3553     }
3554
3555     if (Ops.size() == 1) return Ops[0];
3556   }
3557
3558   // Find the first UMax
3559   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3560     ++Idx;
3561
3562   // Check to see if one of the operands is a UMax. If so, expand its operands
3563   // onto our operand list, and recurse to simplify.
3564   if (Idx < Ops.size()) {
3565     bool DeletedUMax = false;
3566     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3567       Ops.erase(Ops.begin()+Idx);
3568       Ops.append(UMax->op_begin(), UMax->op_end());
3569       DeletedUMax = true;
3570     }
3571
3572     if (DeletedUMax)
3573       return getUMaxExpr(Ops);
3574   }
3575
3576   // Okay, check to see if the same value occurs in the operand list twice.  If
3577   // so, delete one.  Since we sorted the list, these values are required to
3578   // be adjacent.
3579   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3580     //  X umax Y umax Y  -->  X umax Y
3581     //  X umax Y         -->  X, if X is always greater than Y
3582     if (Ops[i] == Ops[i+1] ||
3583         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3584       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3585       --i; --e;
3586     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3587       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3588       --i; --e;
3589     }
3590
3591   if (Ops.size() == 1) return Ops[0];
3592
3593   assert(!Ops.empty() && "Reduced umax down to nothing!");
3594
3595   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3596   // already have one, otherwise create a new one.
3597   FoldingSetNodeID ID;
3598   ID.AddInteger(scUMaxExpr);
3599   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3600     ID.AddPointer(Ops[i]);
3601   void *IP = nullptr;
3602   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3603   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3604   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3605   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3606                                              O, Ops.size());
3607   UniqueSCEVs.InsertNode(S, IP);
3608   addToLoopUseLists(S);
3609   return S;
3610 }
3611
3612 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3613                                          const SCEV *RHS) {
3614   // ~smax(~x, ~y) == smin(x, y).
3615   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3616 }
3617
3618 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3619                                          const SCEV *RHS) {
3620   // ~umax(~x, ~y) == umin(x, y)
3621   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3622 }
3623
3624 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3625   // We can bypass creating a target-independent
3626   // constant expression and then folding it back into a ConstantInt.
3627   // This is just a compile-time optimization.
3628   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3629 }
3630
3631 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3632                                              StructType *STy,
3633                                              unsigned FieldNo) {
3634   // We can bypass creating a target-independent
3635   // constant expression and then folding it back into a ConstantInt.
3636   // This is just a compile-time optimization.
3637   return getConstant(
3638       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3639 }
3640
3641 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3642   // Don't attempt to do anything other than create a SCEVUnknown object
3643   // here.  createSCEV only calls getUnknown after checking for all other
3644   // interesting possibilities, and any other code that calls getUnknown
3645   // is doing so in order to hide a value from SCEV canonicalization.
3646
3647   FoldingSetNodeID ID;
3648   ID.AddInteger(scUnknown);
3649   ID.AddPointer(V);
3650   void *IP = nullptr;
3651   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3652     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3653            "Stale SCEVUnknown in uniquing map!");
3654     return S;
3655   }
3656   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3657                                             FirstUnknown);
3658   FirstUnknown = cast<SCEVUnknown>(S);
3659   UniqueSCEVs.InsertNode(S, IP);
3660   return S;
3661 }
3662
3663 //===----------------------------------------------------------------------===//
3664 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3665 //
3666
3667 /// Test if values of the given type are analyzable within the SCEV
3668 /// framework. This primarily includes integer types, and it can optionally
3669 /// include pointer types if the ScalarEvolution class has access to
3670 /// target-specific information.
3671 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3672   // Integers and pointers are always SCEVable.
3673   return Ty->isIntegerTy() || Ty->isPointerTy();
3674 }
3675
3676 /// Return the size in bits of the specified type, for which isSCEVable must
3677 /// return true.
3678 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3679   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3680   return getDataLayout().getTypeSizeInBits(Ty);
3681 }
3682
3683 /// Return a type with the same bitwidth as the given type and which represents
3684 /// how SCEV will treat the given type, for which isSCEVable must return
3685 /// true. For pointer types, this is the pointer-sized integer type.
3686 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3687   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3688
3689   if (Ty->isIntegerTy())
3690     return Ty;
3691
3692   // The only other support type is pointer.
3693   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3694   return getDataLayout().getIntPtrType(Ty);
3695 }
3696
3697 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3698   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3699 }
3700
3701 const SCEV *ScalarEvolution::getCouldNotCompute() {
3702   return CouldNotCompute.get();
3703 }
3704
3705 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3706   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3707     auto *SU = dyn_cast<SCEVUnknown>(S);
3708     return SU && SU->getValue() == nullptr;
3709   });
3710
3711   return !ContainsNulls;
3712 }
3713
3714 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3715   HasRecMapType::iterator I = HasRecMap.find(S);
3716   if (I != HasRecMap.end())
3717     return I->second;
3718
3719   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3720   HasRecMap.insert({S, FoundAddRec});
3721   return FoundAddRec;
3722 }
3723
3724 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3725 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3726 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3727 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3728   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3729   if (!Add)
3730     return {S, nullptr};
3731
3732   if (Add->getNumOperands() != 2)
3733     return {S, nullptr};
3734
3735   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3736   if (!ConstOp)
3737     return {S, nullptr};
3738
3739   return {Add->getOperand(1), ConstOp->getValue()};
3740 }
3741
3742 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3743 /// by the value and offset from any ValueOffsetPair in the set.
3744 SetVector<ScalarEvolution::ValueOffsetPair> *
3745 ScalarEvolution::getSCEVValues(const SCEV *S) {
3746   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3747   if (SI == ExprValueMap.end())
3748     return nullptr;
3749 #ifndef NDEBUG
3750   if (VerifySCEVMap) {
3751     // Check there is no dangling Value in the set returned.
3752     for (const auto &VE : SI->second)
3753       assert(ValueExprMap.count(VE.first));
3754   }
3755 #endif
3756   return &SI->second;
3757 }
3758
3759 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3760 /// cannot be used separately. eraseValueFromMap should be used to remove
3761 /// V from ValueExprMap and ExprValueMap at the same time.
3762 void ScalarEvolution::eraseValueFromMap(Value *V) {
3763   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3764   if (I != ValueExprMap.end()) {
3765     const SCEV *S = I->second;
3766     // Remove {V, 0} from the set of ExprValueMap[S]
3767     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3768       SV->remove({V, nullptr});
3769
3770     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3771     const SCEV *Stripped;
3772     ConstantInt *Offset;
3773     std::tie(Stripped, Offset) = splitAddExpr(S);
3774     if (Offset != nullptr) {
3775       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3776         SV->remove({V, Offset});
3777     }
3778     ValueExprMap.erase(V);
3779   }
3780 }
3781
3782 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3783 /// create a new one.
3784 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3785   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3786
3787   const SCEV *S = getExistingSCEV(V);
3788   if (S == nullptr) {
3789     S = createSCEV(V);
3790     // During PHI resolution, it is possible to create two SCEVs for the same
3791     // V, so it is needed to double check whether V->S is inserted into
3792     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3793     std::pair<ValueExprMapType::iterator, bool> Pair =
3794         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3795     if (Pair.second) {
3796       ExprValueMap[S].insert({V, nullptr});
3797
3798       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3799       // ExprValueMap.
3800       const SCEV *Stripped = S;
3801       ConstantInt *Offset = nullptr;
3802       std::tie(Stripped, Offset) = splitAddExpr(S);
3803       // If stripped is SCEVUnknown, don't bother to save
3804       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3805       // increase the complexity of the expansion code.
3806       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3807       // because it may generate add/sub instead of GEP in SCEV expansion.
3808       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3809           !isa<GetElementPtrInst>(V))
3810         ExprValueMap[Stripped].insert({V, Offset});
3811     }
3812   }
3813   return S;
3814 }
3815
3816 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3817   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3818
3819   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3820   if (I != ValueExprMap.end()) {
3821     const SCEV *S = I->second;
3822     if (checkValidity(S))
3823       return S;
3824     eraseValueFromMap(V);
3825     forgetMemoizedResults(S);
3826   }
3827   return nullptr;
3828 }
3829
3830 /// Return a SCEV corresponding to -V = -1*V
3831 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3832                                              SCEV::NoWrapFlags Flags) {
3833   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3834     return getConstant(
3835                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3836
3837   Type *Ty = V->getType();
3838   Ty = getEffectiveSCEVType(Ty);
3839   return getMulExpr(
3840       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3841 }
3842
3843 /// Return a SCEV corresponding to ~V = -1-V
3844 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3845   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3846     return getConstant(
3847                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3848
3849   Type *Ty = V->getType();
3850   Ty = getEffectiveSCEVType(Ty);
3851   const SCEV *AllOnes =
3852                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3853   return getMinusSCEV(AllOnes, V);
3854 }
3855
3856 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3857                                           SCEV::NoWrapFlags Flags,
3858                                           unsigned Depth) {
3859   // Fast path: X - X --> 0.
3860   if (LHS == RHS)
3861     return getZero(LHS->getType());
3862
3863   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3864   // makes it so that we cannot make much use of NUW.
3865   auto AddFlags = SCEV::FlagAnyWrap;
3866   const bool RHSIsNotMinSigned =
3867       !getSignedRangeMin(RHS).isMinSignedValue();
3868   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3869     // Let M be the minimum representable signed value. Then (-1)*RHS
3870     // signed-wraps if and only if RHS is M. That can happen even for
3871     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3872     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3873     // (-1)*RHS, we need to prove that RHS != M.
3874     //
3875     // If LHS is non-negative and we know that LHS - RHS does not
3876     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3877     // either by proving that RHS > M or that LHS >= 0.
3878     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3879       AddFlags = SCEV::FlagNSW;
3880     }
3881   }
3882
3883   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3884   // RHS is NSW and LHS >= 0.
3885   //
3886   // The difficulty here is that the NSW flag may have been proven
3887   // relative to a loop that is to be found in a recurrence in LHS and
3888   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3889   // larger scope than intended.
3890   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3891
3892   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3893 }
3894
3895 const SCEV *
3896 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3897   Type *SrcTy = V->getType();
3898   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3899          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3900          "Cannot truncate or zero extend with non-integer arguments!");
3901   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3902     return V;  // No conversion
3903   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3904     return getTruncateExpr(V, Ty);
3905   return getZeroExtendExpr(V, Ty);
3906 }
3907
3908 const SCEV *
3909 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3910                                          Type *Ty) {
3911   Type *SrcTy = V->getType();
3912   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3913          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3914          "Cannot truncate or zero extend with non-integer arguments!");
3915   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3916     return V;  // No conversion
3917   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3918     return getTruncateExpr(V, Ty);
3919   return getSignExtendExpr(V, Ty);
3920 }
3921
3922 const SCEV *
3923 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3924   Type *SrcTy = V->getType();
3925   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3926          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3927          "Cannot noop or zero extend with non-integer arguments!");
3928   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3929          "getNoopOrZeroExtend cannot truncate!");
3930   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3931     return V;  // No conversion
3932   return getZeroExtendExpr(V, Ty);
3933 }
3934
3935 const SCEV *
3936 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3937   Type *SrcTy = V->getType();
3938   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3939          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3940          "Cannot noop or sign extend with non-integer arguments!");
3941   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3942          "getNoopOrSignExtend cannot truncate!");
3943   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3944     return V;  // No conversion
3945   return getSignExtendExpr(V, Ty);
3946 }
3947
3948 const SCEV *
3949 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3950   Type *SrcTy = V->getType();
3951   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3952          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3953          "Cannot noop or any extend with non-integer arguments!");
3954   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3955          "getNoopOrAnyExtend cannot truncate!");
3956   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3957     return V;  // No conversion
3958   return getAnyExtendExpr(V, Ty);
3959 }
3960
3961 const SCEV *
3962 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3963   Type *SrcTy = V->getType();
3964   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3965          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3966          "Cannot truncate or noop with non-integer arguments!");
3967   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3968          "getTruncateOrNoop cannot extend!");
3969   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3970     return V;  // No conversion
3971   return getTruncateExpr(V, Ty);
3972 }
3973
3974 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3975                                                         const SCEV *RHS) {
3976   const SCEV *PromotedLHS = LHS;
3977   const SCEV *PromotedRHS = RHS;
3978
3979   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3980     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3981   else
3982     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3983
3984   return getUMaxExpr(PromotedLHS, PromotedRHS);
3985 }
3986
3987 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3988                                                         const SCEV *RHS) {
3989   const SCEV *PromotedLHS = LHS;
3990   const SCEV *PromotedRHS = RHS;
3991
3992   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3993     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3994   else
3995     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3996
3997   return getUMinExpr(PromotedLHS, PromotedRHS);
3998 }
3999
4000 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4001   // A pointer operand may evaluate to a nonpointer expression, such as null.
4002   if (!V->getType()->isPointerTy())
4003     return V;
4004
4005   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4006     return getPointerBase(Cast->getOperand());
4007   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4008     const SCEV *PtrOp = nullptr;
4009     for (const SCEV *NAryOp : NAry->operands()) {
4010       if (NAryOp->getType()->isPointerTy()) {
4011         // Cannot find the base of an expression with multiple pointer operands.
4012         if (PtrOp)
4013           return V;
4014         PtrOp = NAryOp;
4015       }
4016     }
4017     if (!PtrOp)
4018       return V;
4019     return getPointerBase(PtrOp);
4020   }
4021   return V;
4022 }
4023
4024 /// Push users of the given Instruction onto the given Worklist.
4025 static void
4026 PushDefUseChildren(Instruction *I,
4027                    SmallVectorImpl<Instruction *> &Worklist) {
4028   // Push the def-use children onto the Worklist stack.
4029   for (User *U : I->users())
4030     Worklist.push_back(cast<Instruction>(U));
4031 }
4032
4033 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4034   SmallVector<Instruction *, 16> Worklist;
4035   PushDefUseChildren(PN, Worklist);
4036
4037   SmallPtrSet<Instruction *, 8> Visited;
4038   Visited.insert(PN);
4039   while (!Worklist.empty()) {
4040     Instruction *I = Worklist.pop_back_val();
4041     if (!Visited.insert(I).second)
4042       continue;
4043
4044     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4045     if (It != ValueExprMap.end()) {
4046       const SCEV *Old = It->second;
4047
4048       // Short-circuit the def-use traversal if the symbolic name
4049       // ceases to appear in expressions.
4050       if (Old != SymName && !hasOperand(Old, SymName))
4051         continue;
4052
4053       // SCEVUnknown for a PHI either means that it has an unrecognized
4054       // structure, it's a PHI that's in the progress of being computed
4055       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4056       // additional loop trip count information isn't going to change anything.
4057       // In the second case, createNodeForPHI will perform the necessary
4058       // updates on its own when it gets to that point. In the third, we do
4059       // want to forget the SCEVUnknown.
4060       if (!isa<PHINode>(I) ||
4061           !isa<SCEVUnknown>(Old) ||
4062           (I != PN && Old == SymName)) {
4063         eraseValueFromMap(It->first);
4064         forgetMemoizedResults(Old);
4065       }
4066     }
4067
4068     PushDefUseChildren(I, Worklist);
4069   }
4070 }
4071
4072 namespace {
4073
4074 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4075 public:
4076   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4077                              ScalarEvolution &SE) {
4078     SCEVInitRewriter Rewriter(L, SE);
4079     const SCEV *Result = Rewriter.visit(S);
4080     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4081   }
4082
4083   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4084     if (!SE.isLoopInvariant(Expr, L))
4085       Valid = false;
4086     return Expr;
4087   }
4088
4089   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4090     // Only allow AddRecExprs for this loop.
4091     if (Expr->getLoop() == L)
4092       return Expr->getStart();
4093     Valid = false;
4094     return Expr;
4095   }
4096
4097   bool isValid() { return Valid; }
4098
4099 private:
4100   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4101       : SCEVRewriteVisitor(SE), L(L) {}
4102
4103   const Loop *L;
4104   bool Valid = true;
4105 };
4106
4107 /// This class evaluates the compare condition by matching it against the
4108 /// condition of loop latch. If there is a match we assume a true value
4109 /// for the condition while building SCEV nodes.
4110 class SCEVBackedgeConditionFolder
4111     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4112 public:
4113   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4114                              ScalarEvolution &SE) {
4115     bool IsPosBECond = false;
4116     Value *BECond = nullptr;
4117     if (BasicBlock *Latch = L->getLoopLatch()) {
4118       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4119       if (BI && BI->isConditional()) {
4120         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4121                "Both outgoing branches should not target same header!");
4122         BECond = BI->getCondition();
4123         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4124       } else {
4125         return S;
4126       }
4127     }
4128     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4129     return Rewriter.visit(S);
4130   }
4131
4132   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4133     const SCEV *Result = Expr;
4134     bool InvariantF = SE.isLoopInvariant(Expr, L);
4135
4136     if (!InvariantF) {
4137       Instruction *I = cast<Instruction>(Expr->getValue());
4138       switch (I->getOpcode()) {
4139       case Instruction::Select: {
4140         SelectInst *SI = cast<SelectInst>(I);
4141         Optional<const SCEV *> Res =
4142             compareWithBackedgeCondition(SI->getCondition());
4143         if (Res.hasValue()) {
4144           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4145           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4146         }
4147         break;
4148       }
4149       default: {
4150         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4151         if (Res.hasValue())
4152           Result = Res.getValue();
4153         break;
4154       }
4155       }
4156     }
4157     return Result;
4158   }
4159
4160 private:
4161   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4162                                        bool IsPosBECond, ScalarEvolution &SE)
4163       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4164         IsPositiveBECond(IsPosBECond) {}
4165
4166   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4167
4168   const Loop *L;
4169   /// Loop back condition.
4170   Value *BackedgeCond = nullptr;
4171   /// Set to true if loop back is on positive branch condition.
4172   bool IsPositiveBECond;
4173 };
4174
4175 Optional<const SCEV *>
4176 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4177
4178   // If value matches the backedge condition for loop latch,
4179   // then return a constant evolution node based on loopback
4180   // branch taken.
4181   if (BackedgeCond == IC)
4182     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4183                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4184   return None;
4185 }
4186
4187 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4188 public:
4189   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4190                              ScalarEvolution &SE) {
4191     SCEVShiftRewriter Rewriter(L, SE);
4192     const SCEV *Result = Rewriter.visit(S);
4193     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4194   }
4195
4196   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4197     // Only allow AddRecExprs for this loop.
4198     if (!SE.isLoopInvariant(Expr, L))
4199       Valid = false;
4200     return Expr;
4201   }
4202
4203   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4204     if (Expr->getLoop() == L && Expr->isAffine())
4205       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4206     Valid = false;
4207     return Expr;
4208   }
4209
4210   bool isValid() { return Valid; }
4211
4212 private:
4213   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4214       : SCEVRewriteVisitor(SE), L(L) {}
4215
4216   const Loop *L;
4217   bool Valid = true;
4218 };
4219
4220 } // end anonymous namespace
4221
4222 SCEV::NoWrapFlags
4223 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4224   if (!AR->isAffine())
4225     return SCEV::FlagAnyWrap;
4226
4227   using OBO = OverflowingBinaryOperator;
4228
4229   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4230
4231   if (!AR->hasNoSignedWrap()) {
4232     ConstantRange AddRecRange = getSignedRange(AR);
4233     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4234
4235     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4236         Instruction::Add, IncRange, OBO::NoSignedWrap);
4237     if (NSWRegion.contains(AddRecRange))
4238       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4239   }
4240
4241   if (!AR->hasNoUnsignedWrap()) {
4242     ConstantRange AddRecRange = getUnsignedRange(AR);
4243     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4244
4245     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4246         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4247     if (NUWRegion.contains(AddRecRange))
4248       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4249   }
4250
4251   return Result;
4252 }
4253
4254 namespace {
4255
4256 /// Represents an abstract binary operation.  This may exist as a
4257 /// normal instruction or constant expression, or may have been
4258 /// derived from an expression tree.
4259 struct BinaryOp {
4260   unsigned Opcode;
4261   Value *LHS;
4262   Value *RHS;
4263   bool IsNSW = false;
4264   bool IsNUW = false;
4265
4266   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4267   /// constant expression.
4268   Operator *Op = nullptr;
4269
4270   explicit BinaryOp(Operator *Op)
4271       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4272         Op(Op) {
4273     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4274       IsNSW = OBO->hasNoSignedWrap();
4275       IsNUW = OBO->hasNoUnsignedWrap();
4276     }
4277   }
4278
4279   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4280                     bool IsNUW = false)
4281       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4282 };
4283
4284 } // end anonymous namespace
4285
4286 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4287 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4288   auto *Op = dyn_cast<Operator>(V);
4289   if (!Op)
4290     return None;
4291
4292   // Implementation detail: all the cleverness here should happen without
4293   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4294   // SCEV expressions when possible, and we should not break that.
4295
4296   switch (Op->getOpcode()) {
4297   case Instruction::Add:
4298   case Instruction::Sub:
4299   case Instruction::Mul:
4300   case Instruction::UDiv:
4301   case Instruction::URem:
4302   case Instruction::And:
4303   case Instruction::Or:
4304   case Instruction::AShr:
4305   case Instruction::Shl:
4306     return BinaryOp(Op);
4307
4308   case Instruction::Xor:
4309     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4310       // If the RHS of the xor is a signmask, then this is just an add.
4311       // Instcombine turns add of signmask into xor as a strength reduction step.
4312       if (RHSC->getValue().isSignMask())
4313         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4314     return BinaryOp(Op);
4315
4316   case Instruction::LShr:
4317     // Turn logical shift right of a constant into a unsigned divide.
4318     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4319       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4320
4321       // If the shift count is not less than the bitwidth, the result of
4322       // the shift is undefined. Don't try to analyze it, because the
4323       // resolution chosen here may differ from the resolution chosen in
4324       // other parts of the compiler.
4325       if (SA->getValue().ult(BitWidth)) {
4326         Constant *X =
4327             ConstantInt::get(SA->getContext(),
4328                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4329         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4330       }
4331     }
4332     return BinaryOp(Op);
4333
4334   case Instruction::ExtractValue: {
4335     auto *EVI = cast<ExtractValueInst>(Op);
4336     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4337       break;
4338
4339     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4340     if (!CI)
4341       break;
4342
4343     if (auto *F = CI->getCalledFunction())
4344       switch (F->getIntrinsicID()) {
4345       case Intrinsic::sadd_with_overflow:
4346       case Intrinsic::uadd_with_overflow:
4347         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4348           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4349                           CI->getArgOperand(1));
4350
4351         // Now that we know that all uses of the arithmetic-result component of
4352         // CI are guarded by the overflow check, we can go ahead and pretend
4353         // that the arithmetic is non-overflowing.
4354         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4355           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4356                           CI->getArgOperand(1), /* IsNSW = */ true,
4357                           /* IsNUW = */ false);
4358         else
4359           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4360                           CI->getArgOperand(1), /* IsNSW = */ false,
4361                           /* IsNUW*/ true);
4362       case Intrinsic::ssub_with_overflow:
4363       case Intrinsic::usub_with_overflow:
4364         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4365           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4366                           CI->getArgOperand(1));
4367
4368         // The same reasoning as sadd/uadd above.
4369         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4370           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4371                           CI->getArgOperand(1), /* IsNSW = */ true,
4372                           /* IsNUW = */ false);
4373         else
4374           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4375                           CI->getArgOperand(1), /* IsNSW = */ false,
4376                           /* IsNUW = */ true);
4377       case Intrinsic::smul_with_overflow:
4378       case Intrinsic::umul_with_overflow:
4379         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4380                         CI->getArgOperand(1));
4381       default:
4382         break;
4383       }
4384     break;
4385   }
4386
4387   default:
4388     break;
4389   }
4390
4391   return None;
4392 }
4393
4394 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4395 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4396 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4397 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4398 /// follows one of the following patterns:
4399 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4400 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4401 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4402 /// we return the type of the truncation operation, and indicate whether the
4403 /// truncated type should be treated as signed/unsigned by setting
4404 /// \p Signed to true/false, respectively.
4405 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4406                                bool &Signed, ScalarEvolution &SE) {
4407   // The case where Op == SymbolicPHI (that is, with no type conversions on
4408   // the way) is handled by the regular add recurrence creating logic and
4409   // would have already been triggered in createAddRecForPHI. Reaching it here
4410   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4411   // because one of the other operands of the SCEVAddExpr updating this PHI is
4412   // not invariant).
4413   //
4414   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4415   // this case predicates that allow us to prove that Op == SymbolicPHI will
4416   // be added.
4417   if (Op == SymbolicPHI)
4418     return nullptr;
4419
4420   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4421   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4422   if (SourceBits != NewBits)
4423     return nullptr;
4424
4425   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4426   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4427   if (!SExt && !ZExt)
4428     return nullptr;
4429   const SCEVTruncateExpr *Trunc =
4430       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4431            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4432   if (!Trunc)
4433     return nullptr;
4434   const SCEV *X = Trunc->getOperand();
4435   if (X != SymbolicPHI)
4436     return nullptr;
4437   Signed = SExt != nullptr;
4438   return Trunc->getType();
4439 }
4440
4441 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4442   if (!PN->getType()->isIntegerTy())
4443     return nullptr;
4444   const Loop *L = LI.getLoopFor(PN->getParent());
4445   if (!L || L->getHeader() != PN->getParent())
4446     return nullptr;
4447   return L;
4448 }
4449
4450 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4451 // computation that updates the phi follows the following pattern:
4452 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4453 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4454 // If so, try to see if it can be rewritten as an AddRecExpr under some
4455 // Predicates. If successful, return them as a pair. Also cache the results
4456 // of the analysis.
4457 //
4458 // Example usage scenario:
4459 //    Say the Rewriter is called for the following SCEV:
4460 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4461 //    where:
4462 //         %X = phi i64 (%Start, %BEValue)
4463 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4464 //    and call this function with %SymbolicPHI = %X.
4465 //
4466 //    The analysis will find that the value coming around the backedge has
4467 //    the following SCEV:
4468 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4469 //    Upon concluding that this matches the desired pattern, the function
4470 //    will return the pair {NewAddRec, SmallPredsVec} where:
4471 //         NewAddRec = {%Start,+,%Step}
4472 //         SmallPredsVec = {P1, P2, P3} as follows:
4473 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4474 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4475 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4476 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4477 //    under the predicates {P1,P2,P3}.
4478 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4479 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4480 //
4481 // TODO's:
4482 //
4483 // 1) Extend the Induction descriptor to also support inductions that involve
4484 //    casts: When needed (namely, when we are called in the context of the
4485 //    vectorizer induction analysis), a Set of cast instructions will be
4486 //    populated by this method, and provided back to isInductionPHI. This is
4487 //    needed to allow the vectorizer to properly record them to be ignored by
4488 //    the cost model and to avoid vectorizing them (otherwise these casts,
4489 //    which are redundant under the runtime overflow checks, will be
4490 //    vectorized, which can be costly).
4491 //
4492 // 2) Support additional induction/PHISCEV patterns: We also want to support
4493 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4494 //    after the induction update operation (the induction increment):
4495 //
4496 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4497 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4498 //
4499 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4500 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4501 //
4502 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4503 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4504 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4505   SmallVector<const SCEVPredicate *, 3> Predicates;
4506
4507   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4508   // return an AddRec expression under some predicate.
4509
4510   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4511   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4512   assert(L && "Expecting an integer loop header phi");
4513
4514   // The loop may have multiple entrances or multiple exits; we can analyze
4515   // this phi as an addrec if it has a unique entry value and a unique
4516   // backedge value.
4517   Value *BEValueV = nullptr, *StartValueV = nullptr;
4518   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4519     Value *V = PN->getIncomingValue(i);
4520     if (L->contains(PN->getIncomingBlock(i))) {
4521       if (!BEValueV) {
4522         BEValueV = V;
4523       } else if (BEValueV != V) {
4524         BEValueV = nullptr;
4525         break;
4526       }
4527     } else if (!StartValueV) {
4528       StartValueV = V;
4529     } else if (StartValueV != V) {
4530       StartValueV = nullptr;
4531       break;
4532     }
4533   }
4534   if (!BEValueV || !StartValueV)
4535     return None;
4536
4537   const SCEV *BEValue = getSCEV(BEValueV);
4538
4539   // If the value coming around the backedge is an add with the symbolic
4540   // value we just inserted, possibly with casts that we can ignore under
4541   // an appropriate runtime guard, then we found a simple induction variable!
4542   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4543   if (!Add)
4544     return None;
4545
4546   // If there is a single occurrence of the symbolic value, possibly
4547   // casted, replace it with a recurrence.
4548   unsigned FoundIndex = Add->getNumOperands();
4549   Type *TruncTy = nullptr;
4550   bool Signed;
4551   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4552     if ((TruncTy =
4553              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4554       if (FoundIndex == e) {
4555         FoundIndex = i;
4556         break;
4557       }
4558
4559   if (FoundIndex == Add->getNumOperands())
4560     return None;
4561
4562   // Create an add with everything but the specified operand.
4563   SmallVector<const SCEV *, 8> Ops;
4564   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4565     if (i != FoundIndex)
4566       Ops.push_back(Add->getOperand(i));
4567   const SCEV *Accum = getAddExpr(Ops);
4568
4569   // The runtime checks will not be valid if the step amount is
4570   // varying inside the loop.
4571   if (!isLoopInvariant(Accum, L))
4572     return None;
4573
4574   // *** Part2: Create the predicates
4575
4576   // Analysis was successful: we have a phi-with-cast pattern for which we
4577   // can return an AddRec expression under the following predicates:
4578   //
4579   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4580   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4581   // P2: An Equal predicate that guarantees that
4582   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4583   // P3: An Equal predicate that guarantees that
4584   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4585   //
4586   // As we next prove, the above predicates guarantee that:
4587   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4588   //
4589   //
4590   // More formally, we want to prove that:
4591   //     Expr(i+1) = Start + (i+1) * Accum
4592   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4593   //
4594   // Given that:
4595   // 1) Expr(0) = Start
4596   // 2) Expr(1) = Start + Accum
4597   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4598   // 3) Induction hypothesis (step i):
4599   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4600   //
4601   // Proof:
4602   //  Expr(i+1) =
4603   //   = Start + (i+1)*Accum
4604   //   = (Start + i*Accum) + Accum
4605   //   = Expr(i) + Accum
4606   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4607   //                                                             :: from step i
4608   //
4609   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4610   //
4611   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4612   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4613   //     + Accum                                                     :: from P3
4614   //
4615   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4616   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4617   //
4618   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4619   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4620   //
4621   // By induction, the same applies to all iterations 1<=i<n:
4622   //
4623
4624   // Create a truncated addrec for which we will add a no overflow check (P1).
4625   const SCEV *StartVal = getSCEV(StartValueV);
4626   const SCEV *PHISCEV =
4627       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4628                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4629
4630   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4631   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4632   // will be constant.
4633   //
4634   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4635   // add P1.
4636   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4637     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4638         Signed ? SCEVWrapPredicate::IncrementNSSW
4639                : SCEVWrapPredicate::IncrementNUSW;
4640     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4641     Predicates.push_back(AddRecPred);
4642   }
4643
4644   // Create the Equal Predicates P2,P3:
4645
4646   // It is possible that the predicates P2 and/or P3 are computable at
4647   // compile time due to StartVal and/or Accum being constants.
4648   // If either one is, then we can check that now and escape if either P2
4649   // or P3 is false.
4650
4651   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4652   // for each of StartVal and Accum
4653   auto getExtendedExpr = [&](const SCEV *Expr, 
4654                              bool CreateSignExtend) -> const SCEV * {
4655     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4656     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4657     const SCEV *ExtendedExpr =
4658         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4659                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4660     return ExtendedExpr;
4661   };
4662
4663   // Given:
4664   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4665   //               = getExtendedExpr(Expr)
4666   // Determine whether the predicate P: Expr == ExtendedExpr
4667   // is known to be false at compile time
4668   auto PredIsKnownFalse = [&](const SCEV *Expr,
4669                               const SCEV *ExtendedExpr) -> bool {
4670     return Expr != ExtendedExpr &&
4671            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4672   };
4673
4674   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4675   if (PredIsKnownFalse(StartVal, StartExtended)) {
4676     DEBUG(dbgs() << "P2 is compile-time false\n";);
4677     return None;
4678   }
4679
4680   // The Step is always Signed (because the overflow checks are either
4681   // NSSW or NUSW)
4682   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4683   if (PredIsKnownFalse(Accum, AccumExtended)) {
4684     DEBUG(dbgs() << "P3 is compile-time false\n";);
4685     return None;
4686   }
4687
4688   auto AppendPredicate = [&](const SCEV *Expr,
4689                              const SCEV *ExtendedExpr) -> void {
4690     if (Expr != ExtendedExpr &&
4691         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4692       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4693       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4694       Predicates.push_back(Pred);
4695     }
4696   };
4697
4698   AppendPredicate(StartVal, StartExtended);
4699   AppendPredicate(Accum, AccumExtended);
4700
4701   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4702   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4703   // into NewAR if it will also add the runtime overflow checks specified in
4704   // Predicates.
4705   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4706
4707   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4708       std::make_pair(NewAR, Predicates);
4709   // Remember the result of the analysis for this SCEV at this locayyytion.
4710   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4711   return PredRewrite;
4712 }
4713
4714 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4715 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4716   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4717   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4718   if (!L)
4719     return None;
4720
4721   // Check to see if we already analyzed this PHI.
4722   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4723   if (I != PredicatedSCEVRewrites.end()) {
4724     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4725         I->second;
4726     // Analysis was done before and failed to create an AddRec:
4727     if (Rewrite.first == SymbolicPHI)
4728       return None;
4729     // Analysis was done before and succeeded to create an AddRec under
4730     // a predicate:
4731     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4732     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4733     return Rewrite;
4734   }
4735
4736   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4737     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4738
4739   // Record in the cache that the analysis failed
4740   if (!Rewrite) {
4741     SmallVector<const SCEVPredicate *, 3> Predicates;
4742     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4743     return None;
4744   }
4745
4746   return Rewrite;
4747 }
4748
4749 // FIXME: This utility is currently required because the Rewriter currently 
4750 // does not rewrite this expression: 
4751 // {0, +, (sext ix (trunc iy to ix) to iy)} 
4752 // into {0, +, %step},
4753 // even when the following Equal predicate exists: 
4754 // "%step == (sext ix (trunc iy to ix) to iy)".
4755 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4756     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4757   if (AR1 == AR2)
4758     return true;
4759
4760   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4761     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4762         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4763       return false;
4764     return true;
4765   };
4766
4767   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4768       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4769     return false;
4770   return true;
4771 }
4772
4773 /// A helper function for createAddRecFromPHI to handle simple cases.
4774 ///
4775 /// This function tries to find an AddRec expression for the simplest (yet most
4776 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4777 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4778 /// technique for finding the AddRec expression.
4779 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4780                                                       Value *BEValueV,
4781                                                       Value *StartValueV) {
4782   const Loop *L = LI.getLoopFor(PN->getParent());
4783   assert(L && L->getHeader() == PN->getParent());
4784   assert(BEValueV && StartValueV);
4785
4786   auto BO = MatchBinaryOp(BEValueV, DT);
4787   if (!BO)
4788     return nullptr;
4789
4790   if (BO->Opcode != Instruction::Add)
4791     return nullptr;
4792
4793   const SCEV *Accum = nullptr;
4794   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4795     Accum = getSCEV(BO->RHS);
4796   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4797     Accum = getSCEV(BO->LHS);
4798
4799   if (!Accum)
4800     return nullptr;
4801
4802   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4803   if (BO->IsNUW)
4804     Flags = setFlags(Flags, SCEV::FlagNUW);
4805   if (BO->IsNSW)
4806     Flags = setFlags(Flags, SCEV::FlagNSW);
4807
4808   const SCEV *StartVal = getSCEV(StartValueV);
4809   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4810
4811   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4812
4813   // We can add Flags to the post-inc expression only if we
4814   // know that it is *undefined behavior* for BEValueV to
4815   // overflow.
4816   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4817     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4818       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4819
4820   return PHISCEV;
4821 }
4822
4823 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4824   const Loop *L = LI.getLoopFor(PN->getParent());
4825   if (!L || L->getHeader() != PN->getParent())
4826     return nullptr;
4827
4828   // The loop may have multiple entrances or multiple exits; we can analyze
4829   // this phi as an addrec if it has a unique entry value and a unique
4830   // backedge value.
4831   Value *BEValueV = nullptr, *StartValueV = nullptr;
4832   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4833     Value *V = PN->getIncomingValue(i);
4834     if (L->contains(PN->getIncomingBlock(i))) {
4835       if (!BEValueV) {
4836         BEValueV = V;
4837       } else if (BEValueV != V) {
4838         BEValueV = nullptr;
4839         break;
4840       }
4841     } else if (!StartValueV) {
4842       StartValueV = V;
4843     } else if (StartValueV != V) {
4844       StartValueV = nullptr;
4845       break;
4846     }
4847   }
4848   if (!BEValueV || !StartValueV)
4849     return nullptr;
4850
4851   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4852          "PHI node already processed?");
4853
4854   // First, try to find AddRec expression without creating a fictituos symbolic
4855   // value for PN.
4856   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4857     return S;
4858
4859   // Handle PHI node value symbolically.
4860   const SCEV *SymbolicName = getUnknown(PN);
4861   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4862
4863   // Using this symbolic name for the PHI, analyze the value coming around
4864   // the back-edge.
4865   const SCEV *BEValue = getSCEV(BEValueV);
4866
4867   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4868   // has a special value for the first iteration of the loop.
4869
4870   // If the value coming around the backedge is an add with the symbolic
4871   // value we just inserted, then we found a simple induction variable!
4872   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4873     // If there is a single occurrence of the symbolic value, replace it
4874     // with a recurrence.
4875     unsigned FoundIndex = Add->getNumOperands();
4876     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4877       if (Add->getOperand(i) == SymbolicName)
4878         if (FoundIndex == e) {
4879           FoundIndex = i;
4880           break;
4881         }
4882
4883     if (FoundIndex != Add->getNumOperands()) {
4884       // Create an add with everything but the specified operand.
4885       SmallVector<const SCEV *, 8> Ops;
4886       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4887         if (i != FoundIndex)
4888           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4889                                                              L, *this));
4890       const SCEV *Accum = getAddExpr(Ops);
4891
4892       // This is not a valid addrec if the step amount is varying each
4893       // loop iteration, but is not itself an addrec in this loop.
4894       if (isLoopInvariant(Accum, L) ||
4895           (isa<SCEVAddRecExpr>(Accum) &&
4896            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4897         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4898
4899         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4900           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4901             if (BO->IsNUW)
4902               Flags = setFlags(Flags, SCEV::FlagNUW);
4903             if (BO->IsNSW)
4904               Flags = setFlags(Flags, SCEV::FlagNSW);
4905           }
4906         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4907           // If the increment is an inbounds GEP, then we know the address
4908           // space cannot be wrapped around. We cannot make any guarantee
4909           // about signed or unsigned overflow because pointers are
4910           // unsigned but we may have a negative index from the base
4911           // pointer. We can guarantee that no unsigned wrap occurs if the
4912           // indices form a positive value.
4913           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4914             Flags = setFlags(Flags, SCEV::FlagNW);
4915
4916             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4917             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4918               Flags = setFlags(Flags, SCEV::FlagNUW);
4919           }
4920
4921           // We cannot transfer nuw and nsw flags from subtraction
4922           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4923           // for instance.
4924         }
4925
4926         const SCEV *StartVal = getSCEV(StartValueV);
4927         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4928
4929         // Okay, for the entire analysis of this edge we assumed the PHI
4930         // to be symbolic.  We now need to go back and purge all of the
4931         // entries for the scalars that use the symbolic expression.
4932         forgetSymbolicName(PN, SymbolicName);
4933         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4934
4935         // We can add Flags to the post-inc expression only if we
4936         // know that it is *undefined behavior* for BEValueV to
4937         // overflow.
4938         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4939           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4940             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4941
4942         return PHISCEV;
4943       }
4944     }
4945   } else {
4946     // Otherwise, this could be a loop like this:
4947     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4948     // In this case, j = {1,+,1}  and BEValue is j.
4949     // Because the other in-value of i (0) fits the evolution of BEValue
4950     // i really is an addrec evolution.
4951     //
4952     // We can generalize this saying that i is the shifted value of BEValue
4953     // by one iteration:
4954     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4955     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4956     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4957     if (Shifted != getCouldNotCompute() &&
4958         Start != getCouldNotCompute()) {
4959       const SCEV *StartVal = getSCEV(StartValueV);
4960       if (Start == StartVal) {
4961         // Okay, for the entire analysis of this edge we assumed the PHI
4962         // to be symbolic.  We now need to go back and purge all of the
4963         // entries for the scalars that use the symbolic expression.
4964         forgetSymbolicName(PN, SymbolicName);
4965         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4966         return Shifted;
4967       }
4968     }
4969   }
4970
4971   // Remove the temporary PHI node SCEV that has been inserted while intending
4972   // to create an AddRecExpr for this PHI node. We can not keep this temporary
4973   // as it will prevent later (possibly simpler) SCEV expressions to be added
4974   // to the ValueExprMap.
4975   eraseValueFromMap(PN);
4976
4977   return nullptr;
4978 }
4979
4980 // Checks if the SCEV S is available at BB.  S is considered available at BB
4981 // if S can be materialized at BB without introducing a fault.
4982 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4983                                BasicBlock *BB) {
4984   struct CheckAvailable {
4985     bool TraversalDone = false;
4986     bool Available = true;
4987
4988     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4989     BasicBlock *BB = nullptr;
4990     DominatorTree &DT;
4991
4992     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4993       : L(L), BB(BB), DT(DT) {}
4994
4995     bool setUnavailable() {
4996       TraversalDone = true;
4997       Available = false;
4998       return false;
4999     }
5000
5001     bool follow(const SCEV *S) {
5002       switch (S->getSCEVType()) {
5003       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5004       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5005         // These expressions are available if their operand(s) is/are.
5006         return true;
5007
5008       case scAddRecExpr: {
5009         // We allow add recurrences that are on the loop BB is in, or some
5010         // outer loop.  This guarantees availability because the value of the
5011         // add recurrence at BB is simply the "current" value of the induction
5012         // variable.  We can relax this in the future; for instance an add
5013         // recurrence on a sibling dominating loop is also available at BB.
5014         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5015         if (L && (ARLoop == L || ARLoop->contains(L)))
5016           return true;
5017
5018         return setUnavailable();
5019       }
5020
5021       case scUnknown: {
5022         // For SCEVUnknown, we check for simple dominance.
5023         const auto *SU = cast<SCEVUnknown>(S);
5024         Value *V = SU->getValue();
5025
5026         if (isa<Argument>(V))
5027           return false;
5028
5029         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5030           return false;
5031
5032         return setUnavailable();
5033       }
5034
5035       case scUDivExpr:
5036       case scCouldNotCompute:
5037         // We do not try to smart about these at all.
5038         return setUnavailable();
5039       }
5040       llvm_unreachable("switch should be fully covered!");
5041     }
5042
5043     bool isDone() { return TraversalDone; }
5044   };
5045
5046   CheckAvailable CA(L, BB, DT);
5047   SCEVTraversal<CheckAvailable> ST(CA);
5048
5049   ST.visitAll(S);
5050   return CA.Available;
5051 }
5052
5053 // Try to match a control flow sequence that branches out at BI and merges back
5054 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5055 // match.
5056 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5057                           Value *&C, Value *&LHS, Value *&RHS) {
5058   C = BI->getCondition();
5059
5060   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5061   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5062
5063   if (!LeftEdge.isSingleEdge())
5064     return false;
5065
5066   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5067
5068   Use &LeftUse = Merge->getOperandUse(0);
5069   Use &RightUse = Merge->getOperandUse(1);
5070
5071   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5072     LHS = LeftUse;
5073     RHS = RightUse;
5074     return true;
5075   }
5076
5077   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5078     LHS = RightUse;
5079     RHS = LeftUse;
5080     return true;
5081   }
5082
5083   return false;
5084 }
5085
5086 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5087   auto IsReachable =
5088       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5089   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5090     const Loop *L = LI.getLoopFor(PN->getParent());
5091
5092     // We don't want to break LCSSA, even in a SCEV expression tree.
5093     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5094       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5095         return nullptr;
5096
5097     // Try to match
5098     //
5099     //  br %cond, label %left, label %right
5100     // left:
5101     //  br label %merge
5102     // right:
5103     //  br label %merge
5104     // merge:
5105     //  V = phi [ %x, %left ], [ %y, %right ]
5106     //
5107     // as "select %cond, %x, %y"
5108
5109     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5110     assert(IDom && "At least the entry block should dominate PN");
5111
5112     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5113     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5114
5115     if (BI && BI->isConditional() &&
5116         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5117         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5118         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5119       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5120   }
5121
5122   return nullptr;
5123 }
5124
5125 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5126   if (const SCEV *S = createAddRecFromPHI(PN))
5127     return S;
5128
5129   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5130     return S;
5131
5132   // If the PHI has a single incoming value, follow that value, unless the
5133   // PHI's incoming blocks are in a different loop, in which case doing so
5134   // risks breaking LCSSA form. Instcombine would normally zap these, but
5135   // it doesn't have DominatorTree information, so it may miss cases.
5136   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5137     if (LI.replacementPreservesLCSSAForm(PN, V))
5138       return getSCEV(V);
5139
5140   // If it's not a loop phi, we can't handle it yet.
5141   return getUnknown(PN);
5142 }
5143
5144 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5145                                                       Value *Cond,
5146                                                       Value *TrueVal,
5147                                                       Value *FalseVal) {
5148   // Handle "constant" branch or select. This can occur for instance when a
5149   // loop pass transforms an inner loop and moves on to process the outer loop.
5150   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5151     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5152
5153   // Try to match some simple smax or umax patterns.
5154   auto *ICI = dyn_cast<ICmpInst>(Cond);
5155   if (!ICI)
5156     return getUnknown(I);
5157
5158   Value *LHS = ICI->getOperand(0);
5159   Value *RHS = ICI->getOperand(1);
5160
5161   switch (ICI->getPredicate()) {
5162   case ICmpInst::ICMP_SLT:
5163   case ICmpInst::ICMP_SLE:
5164     std::swap(LHS, RHS);
5165     LLVM_FALLTHROUGH;
5166   case ICmpInst::ICMP_SGT:
5167   case ICmpInst::ICMP_SGE:
5168     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5169     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5170     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5171       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5172       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5173       const SCEV *LA = getSCEV(TrueVal);
5174       const SCEV *RA = getSCEV(FalseVal);
5175       const SCEV *LDiff = getMinusSCEV(LA, LS);
5176       const SCEV *RDiff = getMinusSCEV(RA, RS);
5177       if (LDiff == RDiff)
5178         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5179       LDiff = getMinusSCEV(LA, RS);
5180       RDiff = getMinusSCEV(RA, LS);
5181       if (LDiff == RDiff)
5182         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5183     }
5184     break;
5185   case ICmpInst::ICMP_ULT:
5186   case ICmpInst::ICMP_ULE:
5187     std::swap(LHS, RHS);
5188     LLVM_FALLTHROUGH;
5189   case ICmpInst::ICMP_UGT:
5190   case ICmpInst::ICMP_UGE:
5191     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5192     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5193     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5194       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5195       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5196       const SCEV *LA = getSCEV(TrueVal);
5197       const SCEV *RA = getSCEV(FalseVal);
5198       const SCEV *LDiff = getMinusSCEV(LA, LS);
5199       const SCEV *RDiff = getMinusSCEV(RA, RS);
5200       if (LDiff == RDiff)
5201         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5202       LDiff = getMinusSCEV(LA, RS);
5203       RDiff = getMinusSCEV(RA, LS);
5204       if (LDiff == RDiff)
5205         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5206     }
5207     break;
5208   case ICmpInst::ICMP_NE:
5209     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5210     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5211         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5212       const SCEV *One = getOne(I->getType());
5213       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5214       const SCEV *LA = getSCEV(TrueVal);
5215       const SCEV *RA = getSCEV(FalseVal);
5216       const SCEV *LDiff = getMinusSCEV(LA, LS);
5217       const SCEV *RDiff = getMinusSCEV(RA, One);
5218       if (LDiff == RDiff)
5219         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5220     }
5221     break;
5222   case ICmpInst::ICMP_EQ:
5223     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5224     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5225         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5226       const SCEV *One = getOne(I->getType());
5227       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5228       const SCEV *LA = getSCEV(TrueVal);
5229       const SCEV *RA = getSCEV(FalseVal);
5230       const SCEV *LDiff = getMinusSCEV(LA, One);
5231       const SCEV *RDiff = getMinusSCEV(RA, LS);
5232       if (LDiff == RDiff)
5233         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5234     }
5235     break;
5236   default:
5237     break;
5238   }
5239
5240   return getUnknown(I);
5241 }
5242
5243 /// Expand GEP instructions into add and multiply operations. This allows them
5244 /// to be analyzed by regular SCEV code.
5245 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5246   // Don't attempt to analyze GEPs over unsized objects.
5247   if (!GEP->getSourceElementType()->isSized())
5248     return getUnknown(GEP);
5249
5250   SmallVector<const SCEV *, 4> IndexExprs;
5251   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5252     IndexExprs.push_back(getSCEV(*Index));
5253   return getGEPExpr(GEP, IndexExprs);
5254 }
5255
5256 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5257   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5258     return C->getAPInt().countTrailingZeros();
5259
5260   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5261     return std::min(GetMinTrailingZeros(T->getOperand()),
5262                     (uint32_t)getTypeSizeInBits(T->getType()));
5263
5264   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5265     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5266     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5267                ? getTypeSizeInBits(E->getType())
5268                : OpRes;
5269   }
5270
5271   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5272     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5273     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5274                ? getTypeSizeInBits(E->getType())
5275                : OpRes;
5276   }
5277
5278   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5279     // The result is the min of all operands results.
5280     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5281     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5282       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5283     return MinOpRes;
5284   }
5285
5286   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5287     // The result is the sum of all operands results.
5288     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5289     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5290     for (unsigned i = 1, e = M->getNumOperands();
5291          SumOpRes != BitWidth && i != e; ++i)
5292       SumOpRes =
5293           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5294     return SumOpRes;
5295   }
5296
5297   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5298     // The result is the min of all operands results.
5299     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5300     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5301       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5302     return MinOpRes;
5303   }
5304
5305   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5306     // The result is the min of all operands results.
5307     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5308     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5309       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5310     return MinOpRes;
5311   }
5312
5313   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5314     // The result is the min of all operands results.
5315     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5316     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5317       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5318     return MinOpRes;
5319   }
5320
5321   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5322     // For a SCEVUnknown, ask ValueTracking.
5323     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5324     return Known.countMinTrailingZeros();
5325   }
5326
5327   // SCEVUDivExpr
5328   return 0;
5329 }
5330
5331 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5332   auto I = MinTrailingZerosCache.find(S);
5333   if (I != MinTrailingZerosCache.end())
5334     return I->second;
5335
5336   uint32_t Result = GetMinTrailingZerosImpl(S);
5337   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5338   assert(InsertPair.second && "Should insert a new key");
5339   return InsertPair.first->second;
5340 }
5341
5342 /// Helper method to assign a range to V from metadata present in the IR.
5343 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5344   if (Instruction *I = dyn_cast<Instruction>(V))
5345     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5346       return getConstantRangeFromMetadata(*MD);
5347
5348   return None;
5349 }
5350
5351 /// Determine the range for a particular SCEV.  If SignHint is
5352 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5353 /// with a "cleaner" unsigned (resp. signed) representation.
5354 const ConstantRange &
5355 ScalarEvolution::getRangeRef(const SCEV *S,
5356                              ScalarEvolution::RangeSignHint SignHint) {
5357   DenseMap<const SCEV *, ConstantRange> &Cache =
5358       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5359                                                        : SignedRanges;
5360
5361   // See if we've computed this range already.
5362   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5363   if (I != Cache.end())
5364     return I->second;
5365
5366   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5367     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5368
5369   unsigned BitWidth = getTypeSizeInBits(S->getType());
5370   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5371
5372   // If the value has known zeros, the maximum value will have those known zeros
5373   // as well.
5374   uint32_t TZ = GetMinTrailingZeros(S);
5375   if (TZ != 0) {
5376     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5377       ConservativeResult =
5378           ConstantRange(APInt::getMinValue(BitWidth),
5379                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5380     else
5381       ConservativeResult = ConstantRange(
5382           APInt::getSignedMinValue(BitWidth),
5383           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5384   }
5385
5386   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5387     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5388     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5389       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5390     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5391   }
5392
5393   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5394     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5395     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5396       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5397     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5398   }
5399
5400   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5401     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5402     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5403       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5404     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5405   }
5406
5407   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5408     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5409     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5410       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5411     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5412   }
5413
5414   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5415     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5416     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5417     return setRange(UDiv, SignHint,
5418                     ConservativeResult.intersectWith(X.udiv(Y)));
5419   }
5420
5421   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5422     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5423     return setRange(ZExt, SignHint,
5424                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5425   }
5426
5427   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5428     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5429     return setRange(SExt, SignHint,
5430                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5431   }
5432
5433   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5434     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5435     return setRange(Trunc, SignHint,
5436                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5437   }
5438
5439   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5440     // If there's no unsigned wrap, the value will never be less than its
5441     // initial value.
5442     if (AddRec->hasNoUnsignedWrap())
5443       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5444         if (!C->getValue()->isZero())
5445           ConservativeResult = ConservativeResult.intersectWith(
5446               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5447
5448     // If there's no signed wrap, and all the operands have the same sign or
5449     // zero, the value won't ever change sign.
5450     if (AddRec->hasNoSignedWrap()) {
5451       bool AllNonNeg = true;
5452       bool AllNonPos = true;
5453       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5454         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5455         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5456       }
5457       if (AllNonNeg)
5458         ConservativeResult = ConservativeResult.intersectWith(
5459           ConstantRange(APInt(BitWidth, 0),
5460                         APInt::getSignedMinValue(BitWidth)));
5461       else if (AllNonPos)
5462         ConservativeResult = ConservativeResult.intersectWith(
5463           ConstantRange(APInt::getSignedMinValue(BitWidth),
5464                         APInt(BitWidth, 1)));
5465     }
5466
5467     // TODO: non-affine addrec
5468     if (AddRec->isAffine()) {
5469       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5470       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5471           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5472         auto RangeFromAffine = getRangeForAffineAR(
5473             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5474             BitWidth);
5475         if (!RangeFromAffine.isFullSet())
5476           ConservativeResult =
5477               ConservativeResult.intersectWith(RangeFromAffine);
5478
5479         auto RangeFromFactoring = getRangeViaFactoring(
5480             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5481             BitWidth);
5482         if (!RangeFromFactoring.isFullSet())
5483           ConservativeResult =
5484               ConservativeResult.intersectWith(RangeFromFactoring);
5485       }
5486     }
5487
5488     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5489   }
5490
5491   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5492     // Check if the IR explicitly contains !range metadata.
5493     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5494     if (MDRange.hasValue())
5495       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5496
5497     // Split here to avoid paying the compile-time cost of calling both
5498     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5499     // if needed.
5500     const DataLayout &DL = getDataLayout();
5501     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5502       // For a SCEVUnknown, ask ValueTracking.
5503       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5504       if (Known.One != ~Known.Zero + 1)
5505         ConservativeResult =
5506             ConservativeResult.intersectWith(ConstantRange(Known.One,
5507                                                            ~Known.Zero + 1));
5508     } else {
5509       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5510              "generalize as needed!");
5511       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5512       if (NS > 1)
5513         ConservativeResult = ConservativeResult.intersectWith(
5514             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5515                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5516     }
5517
5518     return setRange(U, SignHint, std::move(ConservativeResult));
5519   }
5520
5521   return setRange(S, SignHint, std::move(ConservativeResult));
5522 }
5523
5524 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5525 // values that the expression can take. Initially, the expression has a value
5526 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5527 // argument defines if we treat Step as signed or unsigned.
5528 static ConstantRange getRangeForAffineARHelper(APInt Step,
5529                                                const ConstantRange &StartRange,
5530                                                const APInt &MaxBECount,
5531                                                unsigned BitWidth, bool Signed) {
5532   // If either Step or MaxBECount is 0, then the expression won't change, and we
5533   // just need to return the initial range.
5534   if (Step == 0 || MaxBECount == 0)
5535     return StartRange;
5536
5537   // If we don't know anything about the initial value (i.e. StartRange is
5538   // FullRange), then we don't know anything about the final range either.
5539   // Return FullRange.
5540   if (StartRange.isFullSet())
5541     return ConstantRange(BitWidth, /* isFullSet = */ true);
5542
5543   // If Step is signed and negative, then we use its absolute value, but we also
5544   // note that we're moving in the opposite direction.
5545   bool Descending = Signed && Step.isNegative();
5546
5547   if (Signed)
5548     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5549     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5550     // This equations hold true due to the well-defined wrap-around behavior of
5551     // APInt.
5552     Step = Step.abs();
5553
5554   // Check if Offset is more than full span of BitWidth. If it is, the
5555   // expression is guaranteed to overflow.
5556   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5557     return ConstantRange(BitWidth, /* isFullSet = */ true);
5558
5559   // Offset is by how much the expression can change. Checks above guarantee no
5560   // overflow here.
5561   APInt Offset = Step * MaxBECount;
5562
5563   // Minimum value of the final range will match the minimal value of StartRange
5564   // if the expression is increasing and will be decreased by Offset otherwise.
5565   // Maximum value of the final range will match the maximal value of StartRange
5566   // if the expression is decreasing and will be increased by Offset otherwise.
5567   APInt StartLower = StartRange.getLower();
5568   APInt StartUpper = StartRange.getUpper() - 1;
5569   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5570                                    : (StartUpper + std::move(Offset));
5571
5572   // It's possible that the new minimum/maximum value will fall into the initial
5573   // range (due to wrap around). This means that the expression can take any
5574   // value in this bitwidth, and we have to return full range.
5575   if (StartRange.contains(MovedBoundary))
5576     return ConstantRange(BitWidth, /* isFullSet = */ true);
5577
5578   APInt NewLower =
5579       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5580   APInt NewUpper =
5581       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5582   NewUpper += 1;
5583
5584   // If we end up with full range, return a proper full range.
5585   if (NewLower == NewUpper)
5586     return ConstantRange(BitWidth, /* isFullSet = */ true);
5587
5588   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5589   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5590 }
5591
5592 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5593                                                    const SCEV *Step,
5594                                                    const SCEV *MaxBECount,
5595                                                    unsigned BitWidth) {
5596   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5597          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5598          "Precondition!");
5599
5600   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5601   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5602
5603   // First, consider step signed.
5604   ConstantRange StartSRange = getSignedRange(Start);
5605   ConstantRange StepSRange = getSignedRange(Step);
5606
5607   // If Step can be both positive and negative, we need to find ranges for the
5608   // maximum absolute step values in both directions and union them.
5609   ConstantRange SR =
5610       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5611                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5612   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5613                                               StartSRange, MaxBECountValue,
5614                                               BitWidth, /* Signed = */ true));
5615
5616   // Next, consider step unsigned.
5617   ConstantRange UR = getRangeForAffineARHelper(
5618       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5619       MaxBECountValue, BitWidth, /* Signed = */ false);
5620
5621   // Finally, intersect signed and unsigned ranges.
5622   return SR.intersectWith(UR);
5623 }
5624
5625 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5626                                                     const SCEV *Step,
5627                                                     const SCEV *MaxBECount,
5628                                                     unsigned BitWidth) {
5629   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5630   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5631
5632   struct SelectPattern {
5633     Value *Condition = nullptr;
5634     APInt TrueValue;
5635     APInt FalseValue;
5636
5637     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5638                            const SCEV *S) {
5639       Optional<unsigned> CastOp;
5640       APInt Offset(BitWidth, 0);
5641
5642       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5643              "Should be!");
5644
5645       // Peel off a constant offset:
5646       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5647         // In the future we could consider being smarter here and handle
5648         // {Start+Step,+,Step} too.
5649         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5650           return;
5651
5652         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5653         S = SA->getOperand(1);
5654       }
5655
5656       // Peel off a cast operation
5657       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5658         CastOp = SCast->getSCEVType();
5659         S = SCast->getOperand();
5660       }
5661
5662       using namespace llvm::PatternMatch;
5663
5664       auto *SU = dyn_cast<SCEVUnknown>(S);
5665       const APInt *TrueVal, *FalseVal;
5666       if (!SU ||
5667           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5668                                           m_APInt(FalseVal)))) {
5669         Condition = nullptr;
5670         return;
5671       }
5672
5673       TrueValue = *TrueVal;
5674       FalseValue = *FalseVal;
5675
5676       // Re-apply the cast we peeled off earlier
5677       if (CastOp.hasValue())
5678         switch (*CastOp) {
5679         default:
5680           llvm_unreachable("Unknown SCEV cast type!");
5681
5682         case scTruncate:
5683           TrueValue = TrueValue.trunc(BitWidth);
5684           FalseValue = FalseValue.trunc(BitWidth);
5685           break;
5686         case scZeroExtend:
5687           TrueValue = TrueValue.zext(BitWidth);
5688           FalseValue = FalseValue.zext(BitWidth);
5689           break;
5690         case scSignExtend:
5691           TrueValue = TrueValue.sext(BitWidth);
5692           FalseValue = FalseValue.sext(BitWidth);
5693           break;
5694         }
5695
5696       // Re-apply the constant offset we peeled off earlier
5697       TrueValue += Offset;
5698       FalseValue += Offset;
5699     }
5700
5701     bool isRecognized() { return Condition != nullptr; }
5702   };
5703
5704   SelectPattern StartPattern(*this, BitWidth, Start);
5705   if (!StartPattern.isRecognized())
5706     return ConstantRange(BitWidth, /* isFullSet = */ true);
5707
5708   SelectPattern StepPattern(*this, BitWidth, Step);
5709   if (!StepPattern.isRecognized())
5710     return ConstantRange(BitWidth, /* isFullSet = */ true);
5711
5712   if (StartPattern.Condition != StepPattern.Condition) {
5713     // We don't handle this case today; but we could, by considering four
5714     // possibilities below instead of two. I'm not sure if there are cases where
5715     // that will help over what getRange already does, though.
5716     return ConstantRange(BitWidth, /* isFullSet = */ true);
5717   }
5718
5719   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5720   // construct arbitrary general SCEV expressions here.  This function is called
5721   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5722   // say) can end up caching a suboptimal value.
5723
5724   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5725   // C2352 and C2512 (otherwise it isn't needed).
5726
5727   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5728   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5729   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5730   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5731
5732   ConstantRange TrueRange =
5733       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5734   ConstantRange FalseRange =
5735       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5736
5737   return TrueRange.unionWith(FalseRange);
5738 }
5739
5740 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5741   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5742   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5743
5744   // Return early if there are no flags to propagate to the SCEV.
5745   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5746   if (BinOp->hasNoUnsignedWrap())
5747     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5748   if (BinOp->hasNoSignedWrap())
5749     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5750   if (Flags == SCEV::FlagAnyWrap)
5751     return SCEV::FlagAnyWrap;
5752
5753   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5754 }
5755
5756 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5757   // Here we check that I is in the header of the innermost loop containing I,
5758   // since we only deal with instructions in the loop header. The actual loop we
5759   // need to check later will come from an add recurrence, but getting that
5760   // requires computing the SCEV of the operands, which can be expensive. This
5761   // check we can do cheaply to rule out some cases early.
5762   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5763   if (InnermostContainingLoop == nullptr ||
5764       InnermostContainingLoop->getHeader() != I->getParent())
5765     return false;
5766
5767   // Only proceed if we can prove that I does not yield poison.
5768   if (!programUndefinedIfFullPoison(I))
5769     return false;
5770
5771   // At this point we know that if I is executed, then it does not wrap
5772   // according to at least one of NSW or NUW. If I is not executed, then we do
5773   // not know if the calculation that I represents would wrap. Multiple
5774   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5775   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5776   // derived from other instructions that map to the same SCEV. We cannot make
5777   // that guarantee for cases where I is not executed. So we need to find the
5778   // loop that I is considered in relation to and prove that I is executed for
5779   // every iteration of that loop. That implies that the value that I
5780   // calculates does not wrap anywhere in the loop, so then we can apply the
5781   // flags to the SCEV.
5782   //
5783   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5784   // from different loops, so that we know which loop to prove that I is
5785   // executed in.
5786   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5787     // I could be an extractvalue from a call to an overflow intrinsic.
5788     // TODO: We can do better here in some cases.
5789     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5790       return false;
5791     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5792     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5793       bool AllOtherOpsLoopInvariant = true;
5794       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5795            ++OtherOpIndex) {
5796         if (OtherOpIndex != OpIndex) {
5797           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5798           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5799             AllOtherOpsLoopInvariant = false;
5800             break;
5801           }
5802         }
5803       }
5804       if (AllOtherOpsLoopInvariant &&
5805           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5806         return true;
5807     }
5808   }
5809   return false;
5810 }
5811
5812 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5813   // If we know that \c I can never be poison period, then that's enough.
5814   if (isSCEVExprNeverPoison(I))
5815     return true;
5816
5817   // For an add recurrence specifically, we assume that infinite loops without
5818   // side effects are undefined behavior, and then reason as follows:
5819   //
5820   // If the add recurrence is poison in any iteration, it is poison on all
5821   // future iterations (since incrementing poison yields poison). If the result
5822   // of the add recurrence is fed into the loop latch condition and the loop
5823   // does not contain any throws or exiting blocks other than the latch, we now
5824   // have the ability to "choose" whether the backedge is taken or not (by
5825   // choosing a sufficiently evil value for the poison feeding into the branch)
5826   // for every iteration including and after the one in which \p I first became
5827   // poison.  There are two possibilities (let's call the iteration in which \p
5828   // I first became poison as K):
5829   //
5830   //  1. In the set of iterations including and after K, the loop body executes
5831   //     no side effects.  In this case executing the backege an infinte number
5832   //     of times will yield undefined behavior.
5833   //
5834   //  2. In the set of iterations including and after K, the loop body executes
5835   //     at least one side effect.  In this case, that specific instance of side
5836   //     effect is control dependent on poison, which also yields undefined
5837   //     behavior.
5838
5839   auto *ExitingBB = L->getExitingBlock();
5840   auto *LatchBB = L->getLoopLatch();
5841   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5842     return false;
5843
5844   SmallPtrSet<const Instruction *, 16> Pushed;
5845   SmallVector<const Instruction *, 8> PoisonStack;
5846
5847   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5848   // things that are known to be fully poison under that assumption go on the
5849   // PoisonStack.
5850   Pushed.insert(I);
5851   PoisonStack.push_back(I);
5852
5853   bool LatchControlDependentOnPoison = false;
5854   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5855     const Instruction *Poison = PoisonStack.pop_back_val();
5856
5857     for (auto *PoisonUser : Poison->users()) {
5858       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5859         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5860           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5861       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5862         assert(BI->isConditional() && "Only possibility!");
5863         if (BI->getParent() == LatchBB) {
5864           LatchControlDependentOnPoison = true;
5865           break;
5866         }
5867       }
5868     }
5869   }
5870
5871   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5872 }
5873
5874 ScalarEvolution::LoopProperties
5875 ScalarEvolution::getLoopProperties(const Loop *L) {
5876   using LoopProperties = ScalarEvolution::LoopProperties;
5877
5878   auto Itr = LoopPropertiesCache.find(L);
5879   if (Itr == LoopPropertiesCache.end()) {
5880     auto HasSideEffects = [](Instruction *I) {
5881       if (auto *SI = dyn_cast<StoreInst>(I))
5882         return !SI->isSimple();
5883
5884       return I->mayHaveSideEffects();
5885     };
5886
5887     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5888                          /*HasNoSideEffects*/ true};
5889
5890     for (auto *BB : L->getBlocks())
5891       for (auto &I : *BB) {
5892         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5893           LP.HasNoAbnormalExits = false;
5894         if (HasSideEffects(&I))
5895           LP.HasNoSideEffects = false;
5896         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5897           break; // We're already as pessimistic as we can get.
5898       }
5899
5900     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5901     assert(InsertPair.second && "We just checked!");
5902     Itr = InsertPair.first;
5903   }
5904
5905   return Itr->second;
5906 }
5907
5908 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5909   if (!isSCEVable(V->getType()))
5910     return getUnknown(V);
5911
5912   if (Instruction *I = dyn_cast<Instruction>(V)) {
5913     // Don't attempt to analyze instructions in blocks that aren't
5914     // reachable. Such instructions don't matter, and they aren't required
5915     // to obey basic rules for definitions dominating uses which this
5916     // analysis depends on.
5917     if (!DT.isReachableFromEntry(I->getParent()))
5918       return getUnknown(V);
5919   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5920     return getConstant(CI);
5921   else if (isa<ConstantPointerNull>(V))
5922     return getZero(V->getType());
5923   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5924     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5925   else if (!isa<ConstantExpr>(V))
5926     return getUnknown(V);
5927
5928   Operator *U = cast<Operator>(V);
5929   if (auto BO = MatchBinaryOp(U, DT)) {
5930     switch (BO->Opcode) {
5931     case Instruction::Add: {
5932       // The simple thing to do would be to just call getSCEV on both operands
5933       // and call getAddExpr with the result. However if we're looking at a
5934       // bunch of things all added together, this can be quite inefficient,
5935       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5936       // Instead, gather up all the operands and make a single getAddExpr call.
5937       // LLVM IR canonical form means we need only traverse the left operands.
5938       SmallVector<const SCEV *, 4> AddOps;
5939       do {
5940         if (BO->Op) {
5941           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5942             AddOps.push_back(OpSCEV);
5943             break;
5944           }
5945
5946           // If a NUW or NSW flag can be applied to the SCEV for this
5947           // addition, then compute the SCEV for this addition by itself
5948           // with a separate call to getAddExpr. We need to do that
5949           // instead of pushing the operands of the addition onto AddOps,
5950           // since the flags are only known to apply to this particular
5951           // addition - they may not apply to other additions that can be
5952           // formed with operands from AddOps.
5953           const SCEV *RHS = getSCEV(BO->RHS);
5954           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5955           if (Flags != SCEV::FlagAnyWrap) {
5956             const SCEV *LHS = getSCEV(BO->LHS);
5957             if (BO->Opcode == Instruction::Sub)
5958               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5959             else
5960               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5961             break;
5962           }
5963         }
5964
5965         if (BO->Opcode == Instruction::Sub)
5966           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5967         else
5968           AddOps.push_back(getSCEV(BO->RHS));
5969
5970         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5971         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5972                        NewBO->Opcode != Instruction::Sub)) {
5973           AddOps.push_back(getSCEV(BO->LHS));
5974           break;
5975         }
5976         BO = NewBO;
5977       } while (true);
5978
5979       return getAddExpr(AddOps);
5980     }
5981
5982     case Instruction::Mul: {
5983       SmallVector<const SCEV *, 4> MulOps;
5984       do {
5985         if (BO->Op) {
5986           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5987             MulOps.push_back(OpSCEV);
5988             break;
5989           }
5990
5991           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5992           if (Flags != SCEV::FlagAnyWrap) {
5993             MulOps.push_back(
5994                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5995             break;
5996           }
5997         }
5998
5999         MulOps.push_back(getSCEV(BO->RHS));
6000         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6001         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6002           MulOps.push_back(getSCEV(BO->LHS));
6003           break;
6004         }
6005         BO = NewBO;
6006       } while (true);
6007
6008       return getMulExpr(MulOps);
6009     }
6010     case Instruction::UDiv:
6011       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6012     case Instruction::URem:
6013       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6014     case Instruction::Sub: {
6015       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6016       if (BO->Op)
6017         Flags = getNoWrapFlagsFromUB(BO->Op);
6018       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6019     }
6020     case Instruction::And:
6021       // For an expression like x&255 that merely masks off the high bits,
6022       // use zext(trunc(x)) as the SCEV expression.
6023       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6024         if (CI->isZero())
6025           return getSCEV(BO->RHS);
6026         if (CI->isMinusOne())
6027           return getSCEV(BO->LHS);
6028         const APInt &A = CI->getValue();
6029
6030         // Instcombine's ShrinkDemandedConstant may strip bits out of
6031         // constants, obscuring what would otherwise be a low-bits mask.
6032         // Use computeKnownBits to compute what ShrinkDemandedConstant
6033         // knew about to reconstruct a low-bits mask value.
6034         unsigned LZ = A.countLeadingZeros();
6035         unsigned TZ = A.countTrailingZeros();
6036         unsigned BitWidth = A.getBitWidth();
6037         KnownBits Known(BitWidth);
6038         computeKnownBits(BO->LHS, Known, getDataLayout(),
6039                          0, &AC, nullptr, &DT);
6040
6041         APInt EffectiveMask =
6042             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6043         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6044           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6045           const SCEV *LHS = getSCEV(BO->LHS);
6046           const SCEV *ShiftedLHS = nullptr;
6047           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6048             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6049               // For an expression like (x * 8) & 8, simplify the multiply.
6050               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6051               unsigned GCD = std::min(MulZeros, TZ);
6052               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6053               SmallVector<const SCEV*, 4> MulOps;
6054               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6055               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6056               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6057               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6058             }
6059           }
6060           if (!ShiftedLHS)
6061             ShiftedLHS = getUDivExpr(LHS, MulCount);
6062           return getMulExpr(
6063               getZeroExtendExpr(
6064                   getTruncateExpr(ShiftedLHS,
6065                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6066                   BO->LHS->getType()),
6067               MulCount);
6068         }
6069       }
6070       break;
6071
6072     case Instruction::Or:
6073       // If the RHS of the Or is a constant, we may have something like:
6074       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6075       // optimizations will transparently handle this case.
6076       //
6077       // In order for this transformation to be safe, the LHS must be of the
6078       // form X*(2^n) and the Or constant must be less than 2^n.
6079       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6080         const SCEV *LHS = getSCEV(BO->LHS);
6081         const APInt &CIVal = CI->getValue();
6082         if (GetMinTrailingZeros(LHS) >=
6083             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6084           // Build a plain add SCEV.
6085           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6086           // If the LHS of the add was an addrec and it has no-wrap flags,
6087           // transfer the no-wrap flags, since an or won't introduce a wrap.
6088           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6089             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6090             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6091                 OldAR->getNoWrapFlags());
6092           }
6093           return S;
6094         }
6095       }
6096       break;
6097
6098     case Instruction::Xor:
6099       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6100         // If the RHS of xor is -1, then this is a not operation.
6101         if (CI->isMinusOne())
6102           return getNotSCEV(getSCEV(BO->LHS));
6103
6104         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6105         // This is a variant of the check for xor with -1, and it handles
6106         // the case where instcombine has trimmed non-demanded bits out
6107         // of an xor with -1.
6108         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6109           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6110             if (LBO->getOpcode() == Instruction::And &&
6111                 LCI->getValue() == CI->getValue())
6112               if (const SCEVZeroExtendExpr *Z =
6113                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6114                 Type *UTy = BO->LHS->getType();
6115                 const SCEV *Z0 = Z->getOperand();
6116                 Type *Z0Ty = Z0->getType();
6117                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6118
6119                 // If C is a low-bits mask, the zero extend is serving to
6120                 // mask off the high bits. Complement the operand and
6121                 // re-apply the zext.
6122                 if (CI->getValue().isMask(Z0TySize))
6123                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6124
6125                 // If C is a single bit, it may be in the sign-bit position
6126                 // before the zero-extend. In this case, represent the xor
6127                 // using an add, which is equivalent, and re-apply the zext.
6128                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6129                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6130                     Trunc.isSignMask())
6131                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6132                                            UTy);
6133               }
6134       }
6135       break;
6136
6137   case Instruction::Shl:
6138     // Turn shift left of a constant amount into a multiply.
6139     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6140       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6141
6142       // If the shift count is not less than the bitwidth, the result of
6143       // the shift is undefined. Don't try to analyze it, because the
6144       // resolution chosen here may differ from the resolution chosen in
6145       // other parts of the compiler.
6146       if (SA->getValue().uge(BitWidth))
6147         break;
6148
6149       // It is currently not resolved how to interpret NSW for left
6150       // shift by BitWidth - 1, so we avoid applying flags in that
6151       // case. Remove this check (or this comment) once the situation
6152       // is resolved. See
6153       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6154       // and http://reviews.llvm.org/D8890 .
6155       auto Flags = SCEV::FlagAnyWrap;
6156       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6157         Flags = getNoWrapFlagsFromUB(BO->Op);
6158
6159       Constant *X = ConstantInt::get(getContext(),
6160         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6161       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6162     }
6163     break;
6164
6165     case Instruction::AShr: {
6166       // AShr X, C, where C is a constant.
6167       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6168       if (!CI)
6169         break;
6170
6171       Type *OuterTy = BO->LHS->getType();
6172       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6173       // If the shift count is not less than the bitwidth, the result of
6174       // the shift is undefined. Don't try to analyze it, because the
6175       // resolution chosen here may differ from the resolution chosen in
6176       // other parts of the compiler.
6177       if (CI->getValue().uge(BitWidth))
6178         break;
6179
6180       if (CI->isZero())
6181         return getSCEV(BO->LHS); // shift by zero --> noop
6182
6183       uint64_t AShrAmt = CI->getZExtValue();
6184       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6185
6186       Operator *L = dyn_cast<Operator>(BO->LHS);
6187       if (L && L->getOpcode() == Instruction::Shl) {
6188         // X = Shl A, n
6189         // Y = AShr X, m
6190         // Both n and m are constant.
6191
6192         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6193         if (L->getOperand(1) == BO->RHS)
6194           // For a two-shift sext-inreg, i.e. n = m,
6195           // use sext(trunc(x)) as the SCEV expression.
6196           return getSignExtendExpr(
6197               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6198
6199         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6200         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6201           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6202           if (ShlAmt > AShrAmt) {
6203             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6204             // expression. We already checked that ShlAmt < BitWidth, so
6205             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6206             // ShlAmt - AShrAmt < Amt.
6207             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6208                                             ShlAmt - AShrAmt);
6209             return getSignExtendExpr(
6210                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6211                 getConstant(Mul)), OuterTy);
6212           }
6213         }
6214       }
6215       break;
6216     }
6217     }
6218   }
6219
6220   switch (U->getOpcode()) {
6221   case Instruction::Trunc:
6222     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6223
6224   case Instruction::ZExt:
6225     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6226
6227   case Instruction::SExt:
6228     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6229       // The NSW flag of a subtract does not always survive the conversion to
6230       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6231       // more likely to preserve NSW and allow later AddRec optimisations.
6232       //
6233       // NOTE: This is effectively duplicating this logic from getSignExtend:
6234       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6235       // but by that point the NSW information has potentially been lost.
6236       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6237         Type *Ty = U->getType();
6238         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6239         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6240         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6241       }
6242     }
6243     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6244
6245   case Instruction::BitCast:
6246     // BitCasts are no-op casts so we just eliminate the cast.
6247     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6248       return getSCEV(U->getOperand(0));
6249     break;
6250
6251   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6252   // lead to pointer expressions which cannot safely be expanded to GEPs,
6253   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6254   // simplifying integer expressions.
6255
6256   case Instruction::GetElementPtr:
6257     return createNodeForGEP(cast<GEPOperator>(U));
6258
6259   case Instruction::PHI:
6260     return createNodeForPHI(cast<PHINode>(U));
6261
6262   case Instruction::Select:
6263     // U can also be a select constant expr, which let fall through.  Since
6264     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6265     // constant expressions cannot have instructions as operands, we'd have
6266     // returned getUnknown for a select constant expressions anyway.
6267     if (isa<Instruction>(U))
6268       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6269                                       U->getOperand(1), U->getOperand(2));
6270     break;
6271
6272   case Instruction::Call:
6273   case Instruction::Invoke:
6274     if (Value *RV = CallSite(U).getReturnedArgOperand())
6275       return getSCEV(RV);
6276     break;
6277   }
6278
6279   return getUnknown(V);
6280 }
6281
6282 //===----------------------------------------------------------------------===//
6283 //                   Iteration Count Computation Code
6284 //
6285
6286 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6287   if (!ExitCount)
6288     return 0;
6289
6290   ConstantInt *ExitConst = ExitCount->getValue();
6291
6292   // Guard against huge trip counts.
6293   if (ExitConst->getValue().getActiveBits() > 32)
6294     return 0;
6295
6296   // In case of integer overflow, this returns 0, which is correct.
6297   return ((unsigned)ExitConst->getZExtValue()) + 1;
6298 }
6299
6300 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6301   if (BasicBlock *ExitingBB = L->getExitingBlock())
6302     return getSmallConstantTripCount(L, ExitingBB);
6303
6304   // No trip count information for multiple exits.
6305   return 0;
6306 }
6307
6308 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6309                                                     BasicBlock *ExitingBlock) {
6310   assert(ExitingBlock && "Must pass a non-null exiting block!");
6311   assert(L->isLoopExiting(ExitingBlock) &&
6312          "Exiting block must actually branch out of the loop!");
6313   const SCEVConstant *ExitCount =
6314       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6315   return getConstantTripCount(ExitCount);
6316 }
6317
6318 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6319   const auto *MaxExitCount =
6320       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6321   return getConstantTripCount(MaxExitCount);
6322 }
6323
6324 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6325   if (BasicBlock *ExitingBB = L->getExitingBlock())
6326     return getSmallConstantTripMultiple(L, ExitingBB);
6327
6328   // No trip multiple information for multiple exits.
6329   return 0;
6330 }
6331
6332 /// Returns the largest constant divisor of the trip count of this loop as a
6333 /// normal unsigned value, if possible. This means that the actual trip count is
6334 /// always a multiple of the returned value (don't forget the trip count could
6335 /// very well be zero as well!).
6336 ///
6337 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6338 /// multiple of a constant (which is also the case if the trip count is simply
6339 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6340 /// if the trip count is very large (>= 2^32).
6341 ///
6342 /// As explained in the comments for getSmallConstantTripCount, this assumes
6343 /// that control exits the loop via ExitingBlock.
6344 unsigned
6345 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6346                                               BasicBlock *ExitingBlock) {
6347   assert(ExitingBlock && "Must pass a non-null exiting block!");
6348   assert(L->isLoopExiting(ExitingBlock) &&
6349          "Exiting block must actually branch out of the loop!");
6350   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6351   if (ExitCount == getCouldNotCompute())
6352     return 1;
6353
6354   // Get the trip count from the BE count by adding 1.
6355   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6356
6357   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6358   if (!TC)
6359     // Attempt to factor more general cases. Returns the greatest power of
6360     // two divisor. If overflow happens, the trip count expression is still
6361     // divisible by the greatest power of 2 divisor returned.
6362     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6363
6364   ConstantInt *Result = TC->getValue();
6365
6366   // Guard against huge trip counts (this requires checking
6367   // for zero to handle the case where the trip count == -1 and the
6368   // addition wraps).
6369   if (!Result || Result->getValue().getActiveBits() > 32 ||
6370       Result->getValue().getActiveBits() == 0)
6371     return 1;
6372
6373   return (unsigned)Result->getZExtValue();
6374 }
6375
6376 /// Get the expression for the number of loop iterations for which this loop is
6377 /// guaranteed not to exit via ExitingBlock. Otherwise return
6378 /// SCEVCouldNotCompute.
6379 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6380                                           BasicBlock *ExitingBlock) {
6381   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6382 }
6383
6384 const SCEV *
6385 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6386                                                  SCEVUnionPredicate &Preds) {
6387   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6388 }
6389
6390 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6391   return getBackedgeTakenInfo(L).getExact(this);
6392 }
6393
6394 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6395 /// known never to be less than the actual backedge taken count.
6396 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6397   return getBackedgeTakenInfo(L).getMax(this);
6398 }
6399
6400 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6401   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6402 }
6403
6404 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6405 static void
6406 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6407   BasicBlock *Header = L->getHeader();
6408
6409   // Push all Loop-header PHIs onto the Worklist stack.
6410   for (PHINode &PN : Header->phis())
6411     Worklist.push_back(&PN);
6412 }
6413
6414 const ScalarEvolution::BackedgeTakenInfo &
6415 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6416   auto &BTI = getBackedgeTakenInfo(L);
6417   if (BTI.hasFullInfo())
6418     return BTI;
6419
6420   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6421
6422   if (!Pair.second)
6423     return Pair.first->second;
6424
6425   BackedgeTakenInfo Result =
6426       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6427
6428   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6429 }
6430
6431 const ScalarEvolution::BackedgeTakenInfo &
6432 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6433   // Initially insert an invalid entry for this loop. If the insertion
6434   // succeeds, proceed to actually compute a backedge-taken count and
6435   // update the value. The temporary CouldNotCompute value tells SCEV
6436   // code elsewhere that it shouldn't attempt to request a new
6437   // backedge-taken count, which could result in infinite recursion.
6438   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6439       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6440   if (!Pair.second)
6441     return Pair.first->second;
6442
6443   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6444   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6445   // must be cleared in this scope.
6446   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6447
6448   if (Result.getExact(this) != getCouldNotCompute()) {
6449     assert(isLoopInvariant(Result.getExact(this), L) &&
6450            isLoopInvariant(Result.getMax(this), L) &&
6451            "Computed backedge-taken count isn't loop invariant for loop!");
6452     ++NumTripCountsComputed;
6453   }
6454   else if (Result.getMax(this) == getCouldNotCompute() &&
6455            isa<PHINode>(L->getHeader()->begin())) {
6456     // Only count loops that have phi nodes as not being computable.
6457     ++NumTripCountsNotComputed;
6458   }
6459
6460   // Now that we know more about the trip count for this loop, forget any
6461   // existing SCEV values for PHI nodes in this loop since they are only
6462   // conservative estimates made without the benefit of trip count
6463   // information. This is similar to the code in forgetLoop, except that
6464   // it handles SCEVUnknown PHI nodes specially.
6465   if (Result.hasAnyInfo()) {
6466     SmallVector<Instruction *, 16> Worklist;
6467     PushLoopPHIs(L, Worklist);
6468
6469     SmallPtrSet<Instruction *, 8> Discovered;
6470     while (!Worklist.empty()) {
6471       Instruction *I = Worklist.pop_back_val();
6472
6473       ValueExprMapType::iterator It =
6474         ValueExprMap.find_as(static_cast<Value *>(I));
6475       if (It != ValueExprMap.end()) {
6476         const SCEV *Old = It->second;
6477
6478         // SCEVUnknown for a PHI either means that it has an unrecognized
6479         // structure, or it's a PHI that's in the progress of being computed
6480         // by createNodeForPHI.  In the former case, additional loop trip
6481         // count information isn't going to change anything. In the later
6482         // case, createNodeForPHI will perform the necessary updates on its
6483         // own when it gets to that point.
6484         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6485           eraseValueFromMap(It->first);
6486           forgetMemoizedResults(Old);
6487         }
6488         if (PHINode *PN = dyn_cast<PHINode>(I))
6489           ConstantEvolutionLoopExitValue.erase(PN);
6490       }
6491
6492       // Since we don't need to invalidate anything for correctness and we're
6493       // only invalidating to make SCEV's results more precise, we get to stop
6494       // early to avoid invalidating too much.  This is especially important in
6495       // cases like:
6496       //
6497       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6498       // loop0:
6499       //   %pn0 = phi
6500       //   ...
6501       // loop1:
6502       //   %pn1 = phi
6503       //   ...
6504       //
6505       // where both loop0 and loop1's backedge taken count uses the SCEV
6506       // expression for %v.  If we don't have the early stop below then in cases
6507       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6508       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6509       // count for loop1, effectively nullifying SCEV's trip count cache.
6510       for (auto *U : I->users())
6511         if (auto *I = dyn_cast<Instruction>(U)) {
6512           auto *LoopForUser = LI.getLoopFor(I->getParent());
6513           if (LoopForUser && L->contains(LoopForUser) &&
6514               Discovered.insert(I).second)
6515             Worklist.push_back(I);
6516         }
6517     }
6518   }
6519
6520   // Re-lookup the insert position, since the call to
6521   // computeBackedgeTakenCount above could result in a
6522   // recusive call to getBackedgeTakenInfo (on a different
6523   // loop), which would invalidate the iterator computed
6524   // earlier.
6525   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6526 }
6527
6528 void ScalarEvolution::forgetLoop(const Loop *L) {
6529   // Drop any stored trip count value.
6530   auto RemoveLoopFromBackedgeMap =
6531       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6532         auto BTCPos = Map.find(L);
6533         if (BTCPos != Map.end()) {
6534           BTCPos->second.clear();
6535           Map.erase(BTCPos);
6536         }
6537       };
6538
6539   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6540   SmallVector<Instruction *, 32> Worklist;
6541   SmallPtrSet<Instruction *, 16> Visited;
6542
6543   // Iterate over all the loops and sub-loops to drop SCEV information.
6544   while (!LoopWorklist.empty()) {
6545     auto *CurrL = LoopWorklist.pop_back_val();
6546
6547     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6548     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6549
6550     // Drop information about predicated SCEV rewrites for this loop.
6551     for (auto I = PredicatedSCEVRewrites.begin();
6552          I != PredicatedSCEVRewrites.end();) {
6553       std::pair<const SCEV *, const Loop *> Entry = I->first;
6554       if (Entry.second == CurrL)
6555         PredicatedSCEVRewrites.erase(I++);
6556       else
6557         ++I;
6558     }
6559
6560     auto LoopUsersItr = LoopUsers.find(CurrL);
6561     if (LoopUsersItr != LoopUsers.end()) {
6562       for (auto *S : LoopUsersItr->second)
6563         forgetMemoizedResults(S);
6564       LoopUsers.erase(LoopUsersItr);
6565     }
6566
6567     // Drop information about expressions based on loop-header PHIs.
6568     PushLoopPHIs(CurrL, Worklist);
6569
6570     while (!Worklist.empty()) {
6571       Instruction *I = Worklist.pop_back_val();
6572       if (!Visited.insert(I).second)
6573         continue;
6574
6575       ValueExprMapType::iterator It =
6576           ValueExprMap.find_as(static_cast<Value *>(I));
6577       if (It != ValueExprMap.end()) {
6578         eraseValueFromMap(It->first);
6579         forgetMemoizedResults(It->second);
6580         if (PHINode *PN = dyn_cast<PHINode>(I))
6581           ConstantEvolutionLoopExitValue.erase(PN);
6582       }
6583
6584       PushDefUseChildren(I, Worklist);
6585     }
6586
6587     LoopPropertiesCache.erase(CurrL);
6588     // Forget all contained loops too, to avoid dangling entries in the
6589     // ValuesAtScopes map.
6590     LoopWorklist.append(CurrL->begin(), CurrL->end());
6591   }
6592 }
6593
6594 void ScalarEvolution::forgetValue(Value *V) {
6595   Instruction *I = dyn_cast<Instruction>(V);
6596   if (!I) return;
6597
6598   // Drop information about expressions based on loop-header PHIs.
6599   SmallVector<Instruction *, 16> Worklist;
6600   Worklist.push_back(I);
6601
6602   SmallPtrSet<Instruction *, 8> Visited;
6603   while (!Worklist.empty()) {
6604     I = Worklist.pop_back_val();
6605     if (!Visited.insert(I).second)
6606       continue;
6607
6608     ValueExprMapType::iterator It =
6609       ValueExprMap.find_as(static_cast<Value *>(I));
6610     if (It != ValueExprMap.end()) {
6611       eraseValueFromMap(It->first);
6612       forgetMemoizedResults(It->second);
6613       if (PHINode *PN = dyn_cast<PHINode>(I))
6614         ConstantEvolutionLoopExitValue.erase(PN);
6615     }
6616
6617     PushDefUseChildren(I, Worklist);
6618   }
6619 }
6620
6621 /// Get the exact loop backedge taken count considering all loop exits. A
6622 /// computable result can only be returned for loops with a single exit.
6623 /// Returning the minimum taken count among all exits is incorrect because one
6624 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6625 /// the limit of each loop test is never skipped. This is a valid assumption as
6626 /// long as the loop exits via that test. For precise results, it is the
6627 /// caller's responsibility to specify the relevant loop exit using
6628 /// getExact(ExitingBlock, SE).
6629 const SCEV *
6630 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6631                                              SCEVUnionPredicate *Preds) const {
6632   // If any exits were not computable, the loop is not computable.
6633   if (!isComplete() || ExitNotTaken.empty())
6634     return SE->getCouldNotCompute();
6635
6636   const SCEV *BECount = nullptr;
6637   for (auto &ENT : ExitNotTaken) {
6638     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
6639
6640     if (!BECount)
6641       BECount = ENT.ExactNotTaken;
6642     else if (BECount != ENT.ExactNotTaken)
6643       return SE->getCouldNotCompute();
6644     if (Preds && !ENT.hasAlwaysTruePredicate())
6645       Preds->add(ENT.Predicate.get());
6646
6647     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6648            "Predicate should be always true!");
6649   }
6650
6651   assert(BECount && "Invalid not taken count for loop exit");
6652   return BECount;
6653 }
6654
6655 /// Get the exact not taken count for this loop exit.
6656 const SCEV *
6657 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6658                                              ScalarEvolution *SE) const {
6659   for (auto &ENT : ExitNotTaken)
6660     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6661       return ENT.ExactNotTaken;
6662
6663   return SE->getCouldNotCompute();
6664 }
6665
6666 /// getMax - Get the max backedge taken count for the loop.
6667 const SCEV *
6668 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6669   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6670     return !ENT.hasAlwaysTruePredicate();
6671   };
6672
6673   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6674     return SE->getCouldNotCompute();
6675
6676   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6677          "No point in having a non-constant max backedge taken count!");
6678   return getMax();
6679 }
6680
6681 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6682   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6683     return !ENT.hasAlwaysTruePredicate();
6684   };
6685   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6686 }
6687
6688 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6689                                                     ScalarEvolution *SE) const {
6690   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6691       SE->hasOperand(getMax(), S))
6692     return true;
6693
6694   for (auto &ENT : ExitNotTaken)
6695     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6696         SE->hasOperand(ENT.ExactNotTaken, S))
6697       return true;
6698
6699   return false;
6700 }
6701
6702 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6703     : ExactNotTaken(E), MaxNotTaken(E) {
6704   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6705           isa<SCEVConstant>(MaxNotTaken)) &&
6706          "No point in having a non-constant max backedge taken count!");
6707 }
6708
6709 ScalarEvolution::ExitLimit::ExitLimit(
6710     const SCEV *E, const SCEV *M, bool MaxOrZero,
6711     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6712     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6713   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6714           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6715          "Exact is not allowed to be less precise than Max");
6716   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6717           isa<SCEVConstant>(MaxNotTaken)) &&
6718          "No point in having a non-constant max backedge taken count!");
6719   for (auto *PredSet : PredSetList)
6720     for (auto *P : *PredSet)
6721       addPredicate(P);
6722 }
6723
6724 ScalarEvolution::ExitLimit::ExitLimit(
6725     const SCEV *E, const SCEV *M, bool MaxOrZero,
6726     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6727     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6728   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6729           isa<SCEVConstant>(MaxNotTaken)) &&
6730          "No point in having a non-constant max backedge taken count!");
6731 }
6732
6733 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6734                                       bool MaxOrZero)
6735     : ExitLimit(E, M, MaxOrZero, None) {
6736   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6737           isa<SCEVConstant>(MaxNotTaken)) &&
6738          "No point in having a non-constant max backedge taken count!");
6739 }
6740
6741 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6742 /// computable exit into a persistent ExitNotTakenInfo array.
6743 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6744     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6745         &&ExitCounts,
6746     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6747     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6748   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6749
6750   ExitNotTaken.reserve(ExitCounts.size());
6751   std::transform(
6752       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6753       [&](const EdgeExitInfo &EEI) {
6754         BasicBlock *ExitBB = EEI.first;
6755         const ExitLimit &EL = EEI.second;
6756         if (EL.Predicates.empty())
6757           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6758
6759         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6760         for (auto *Pred : EL.Predicates)
6761           Predicate->add(Pred);
6762
6763         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6764       });
6765   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6766          "No point in having a non-constant max backedge taken count!");
6767 }
6768
6769 /// Invalidate this result and free the ExitNotTakenInfo array.
6770 void ScalarEvolution::BackedgeTakenInfo::clear() {
6771   ExitNotTaken.clear();
6772 }
6773
6774 /// Compute the number of times the backedge of the specified loop will execute.
6775 ScalarEvolution::BackedgeTakenInfo
6776 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6777                                            bool AllowPredicates) {
6778   SmallVector<BasicBlock *, 8> ExitingBlocks;
6779   L->getExitingBlocks(ExitingBlocks);
6780
6781   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6782
6783   SmallVector<EdgeExitInfo, 4> ExitCounts;
6784   bool CouldComputeBECount = true;
6785   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6786   const SCEV *MustExitMaxBECount = nullptr;
6787   const SCEV *MayExitMaxBECount = nullptr;
6788   bool MustExitMaxOrZero = false;
6789
6790   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6791   // and compute maxBECount.
6792   // Do a union of all the predicates here.
6793   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6794     BasicBlock *ExitBB = ExitingBlocks[i];
6795     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6796
6797     assert((AllowPredicates || EL.Predicates.empty()) &&
6798            "Predicated exit limit when predicates are not allowed!");
6799
6800     // 1. For each exit that can be computed, add an entry to ExitCounts.
6801     // CouldComputeBECount is true only if all exits can be computed.
6802     if (EL.ExactNotTaken == getCouldNotCompute())
6803       // We couldn't compute an exact value for this exit, so
6804       // we won't be able to compute an exact value for the loop.
6805       CouldComputeBECount = false;
6806     else
6807       ExitCounts.emplace_back(ExitBB, EL);
6808
6809     // 2. Derive the loop's MaxBECount from each exit's max number of
6810     // non-exiting iterations. Partition the loop exits into two kinds:
6811     // LoopMustExits and LoopMayExits.
6812     //
6813     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6814     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6815     // MaxBECount is the minimum EL.MaxNotTaken of computable
6816     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6817     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6818     // computable EL.MaxNotTaken.
6819     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6820         DT.dominates(ExitBB, Latch)) {
6821       if (!MustExitMaxBECount) {
6822         MustExitMaxBECount = EL.MaxNotTaken;
6823         MustExitMaxOrZero = EL.MaxOrZero;
6824       } else {
6825         MustExitMaxBECount =
6826             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6827       }
6828     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6829       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6830         MayExitMaxBECount = EL.MaxNotTaken;
6831       else {
6832         MayExitMaxBECount =
6833             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6834       }
6835     }
6836   }
6837   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6838     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6839   // The loop backedge will be taken the maximum or zero times if there's
6840   // a single exit that must be taken the maximum or zero times.
6841   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6842   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6843                            MaxBECount, MaxOrZero);
6844 }
6845
6846 ScalarEvolution::ExitLimit
6847 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6848                                       bool AllowPredicates) {
6849   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6850   // at this block and remember the exit block and whether all other targets
6851   // lead to the loop header.
6852   bool MustExecuteLoopHeader = true;
6853   BasicBlock *Exit = nullptr;
6854   for (auto *SBB : successors(ExitingBlock))
6855     if (!L->contains(SBB)) {
6856       if (Exit) // Multiple exit successors.
6857         return getCouldNotCompute();
6858       Exit = SBB;
6859     } else if (SBB != L->getHeader()) {
6860       MustExecuteLoopHeader = false;
6861     }
6862
6863   // At this point, we know we have a conditional branch that determines whether
6864   // the loop is exited.  However, we don't know if the branch is executed each
6865   // time through the loop.  If not, then the execution count of the branch will
6866   // not be equal to the trip count of the loop.
6867   //
6868   // Currently we check for this by checking to see if the Exit branch goes to
6869   // the loop header.  If so, we know it will always execute the same number of
6870   // times as the loop.  We also handle the case where the exit block *is* the
6871   // loop header.  This is common for un-rotated loops.
6872   //
6873   // If both of those tests fail, walk up the unique predecessor chain to the
6874   // header, stopping if there is an edge that doesn't exit the loop. If the
6875   // header is reached, the execution count of the branch will be equal to the
6876   // trip count of the loop.
6877   //
6878   //  More extensive analysis could be done to handle more cases here.
6879   //
6880   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6881     // The simple checks failed, try climbing the unique predecessor chain
6882     // up to the header.
6883     bool Ok = false;
6884     for (BasicBlock *BB = ExitingBlock; BB; ) {
6885       BasicBlock *Pred = BB->getUniquePredecessor();
6886       if (!Pred)
6887         return getCouldNotCompute();
6888       TerminatorInst *PredTerm = Pred->getTerminator();
6889       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6890         if (PredSucc == BB)
6891           continue;
6892         // If the predecessor has a successor that isn't BB and isn't
6893         // outside the loop, assume the worst.
6894         if (L->contains(PredSucc))
6895           return getCouldNotCompute();
6896       }
6897       if (Pred == L->getHeader()) {
6898         Ok = true;
6899         break;
6900       }
6901       BB = Pred;
6902     }
6903     if (!Ok)
6904       return getCouldNotCompute();
6905   }
6906
6907   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6908   TerminatorInst *Term = ExitingBlock->getTerminator();
6909   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6910     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6911     // Proceed to the next level to examine the exit condition expression.
6912     return computeExitLimitFromCond(
6913         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6914         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6915   }
6916
6917   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6918     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6919                                                 /*ControlsExit=*/IsOnlyExit);
6920
6921   return getCouldNotCompute();
6922 }
6923
6924 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6925     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6926     bool ControlsExit, bool AllowPredicates) {
6927   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6928   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6929                                         ControlsExit, AllowPredicates);
6930 }
6931
6932 Optional<ScalarEvolution::ExitLimit>
6933 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6934                                       BasicBlock *TBB, BasicBlock *FBB,
6935                                       bool ControlsExit, bool AllowPredicates) {
6936   (void)this->L;
6937   (void)this->TBB;
6938   (void)this->FBB;
6939   (void)this->AllowPredicates;
6940
6941   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6942          this->AllowPredicates == AllowPredicates &&
6943          "Variance in assumed invariant key components!");
6944   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6945   if (Itr == TripCountMap.end())
6946     return None;
6947   return Itr->second;
6948 }
6949
6950 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6951                                              BasicBlock *TBB, BasicBlock *FBB,
6952                                              bool ControlsExit,
6953                                              bool AllowPredicates,
6954                                              const ExitLimit &EL) {
6955   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6956          this->AllowPredicates == AllowPredicates &&
6957          "Variance in assumed invariant key components!");
6958
6959   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6960   assert(InsertResult.second && "Expected successful insertion!");
6961   (void)InsertResult;
6962 }
6963
6964 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6965     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6966     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6967
6968   if (auto MaybeEL =
6969           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6970     return *MaybeEL;
6971
6972   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6973                                               ControlsExit, AllowPredicates);
6974   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6975   return EL;
6976 }
6977
6978 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6979     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6980     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6981   // Check if the controlling expression for this loop is an And or Or.
6982   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6983     if (BO->getOpcode() == Instruction::And) {
6984       // Recurse on the operands of the and.
6985       bool EitherMayExit = L->contains(TBB);
6986       ExitLimit EL0 = computeExitLimitFromCondCached(
6987           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6988           AllowPredicates);
6989       ExitLimit EL1 = computeExitLimitFromCondCached(
6990           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6991           AllowPredicates);
6992       const SCEV *BECount = getCouldNotCompute();
6993       const SCEV *MaxBECount = getCouldNotCompute();
6994       if (EitherMayExit) {
6995         // Both conditions must be true for the loop to continue executing.
6996         // Choose the less conservative count.
6997         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6998             EL1.ExactNotTaken == getCouldNotCompute())
6999           BECount = getCouldNotCompute();
7000         else
7001           BECount =
7002               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7003         if (EL0.MaxNotTaken == getCouldNotCompute())
7004           MaxBECount = EL1.MaxNotTaken;
7005         else if (EL1.MaxNotTaken == getCouldNotCompute())
7006           MaxBECount = EL0.MaxNotTaken;
7007         else
7008           MaxBECount =
7009               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7010       } else {
7011         // Both conditions must be true at the same time for the loop to exit.
7012         // For now, be conservative.
7013         assert(L->contains(FBB) && "Loop block has no successor in loop!");
7014         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7015           MaxBECount = EL0.MaxNotTaken;
7016         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7017           BECount = EL0.ExactNotTaken;
7018       }
7019
7020       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7021       // to be more aggressive when computing BECount than when computing
7022       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7023       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7024       // to not.
7025       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7026           !isa<SCEVCouldNotCompute>(BECount))
7027         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7028
7029       return ExitLimit(BECount, MaxBECount, false,
7030                        {&EL0.Predicates, &EL1.Predicates});
7031     }
7032     if (BO->getOpcode() == Instruction::Or) {
7033       // Recurse on the operands of the or.
7034       bool EitherMayExit = L->contains(FBB);
7035       ExitLimit EL0 = computeExitLimitFromCondCached(
7036           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
7037           AllowPredicates);
7038       ExitLimit EL1 = computeExitLimitFromCondCached(
7039           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
7040           AllowPredicates);
7041       const SCEV *BECount = getCouldNotCompute();
7042       const SCEV *MaxBECount = getCouldNotCompute();
7043       if (EitherMayExit) {
7044         // Both conditions must be false for the loop to continue executing.
7045         // Choose the less conservative count.
7046         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7047             EL1.ExactNotTaken == getCouldNotCompute())
7048           BECount = getCouldNotCompute();
7049         else
7050           BECount =
7051               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7052         if (EL0.MaxNotTaken == getCouldNotCompute())
7053           MaxBECount = EL1.MaxNotTaken;
7054         else if (EL1.MaxNotTaken == getCouldNotCompute())
7055           MaxBECount = EL0.MaxNotTaken;
7056         else
7057           MaxBECount =
7058               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7059       } else {
7060         // Both conditions must be false at the same time for the loop to exit.
7061         // For now, be conservative.
7062         assert(L->contains(TBB) && "Loop block has no successor in loop!");
7063         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7064           MaxBECount = EL0.MaxNotTaken;
7065         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7066           BECount = EL0.ExactNotTaken;
7067       }
7068
7069       return ExitLimit(BECount, MaxBECount, false,
7070                        {&EL0.Predicates, &EL1.Predicates});
7071     }
7072   }
7073
7074   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7075   // Proceed to the next level to examine the icmp.
7076   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7077     ExitLimit EL =
7078         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
7079     if (EL.hasFullInfo() || !AllowPredicates)
7080       return EL;
7081
7082     // Try again, but use SCEV predicates this time.
7083     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
7084                                     /*AllowPredicates=*/true);
7085   }
7086
7087   // Check for a constant condition. These are normally stripped out by
7088   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7089   // preserve the CFG and is temporarily leaving constant conditions
7090   // in place.
7091   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7092     if (L->contains(FBB) == !CI->getZExtValue())
7093       // The backedge is always taken.
7094       return getCouldNotCompute();
7095     else
7096       // The backedge is never taken.
7097       return getZero(CI->getType());
7098   }
7099
7100   // If it's not an integer or pointer comparison then compute it the hard way.
7101   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7102 }
7103
7104 ScalarEvolution::ExitLimit
7105 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7106                                           ICmpInst *ExitCond,
7107                                           BasicBlock *TBB,
7108                                           BasicBlock *FBB,
7109                                           bool ControlsExit,
7110                                           bool AllowPredicates) {
7111   // If the condition was exit on true, convert the condition to exit on false
7112   ICmpInst::Predicate Pred;
7113   if (!L->contains(FBB))
7114     Pred = ExitCond->getPredicate();
7115   else
7116     Pred = ExitCond->getInversePredicate();
7117   const ICmpInst::Predicate OriginalPred = Pred;
7118
7119   // Handle common loops like: for (X = "string"; *X; ++X)
7120   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7121     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7122       ExitLimit ItCnt =
7123         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7124       if (ItCnt.hasAnyInfo())
7125         return ItCnt;
7126     }
7127
7128   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7129   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7130
7131   // Try to evaluate any dependencies out of the loop.
7132   LHS = getSCEVAtScope(LHS, L);
7133   RHS = getSCEVAtScope(RHS, L);
7134
7135   // At this point, we would like to compute how many iterations of the
7136   // loop the predicate will return true for these inputs.
7137   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7138     // If there is a loop-invariant, force it into the RHS.
7139     std::swap(LHS, RHS);
7140     Pred = ICmpInst::getSwappedPredicate(Pred);
7141   }
7142
7143   // Simplify the operands before analyzing them.
7144   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7145
7146   // If we have a comparison of a chrec against a constant, try to use value
7147   // ranges to answer this query.
7148   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7149     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7150       if (AddRec->getLoop() == L) {
7151         // Form the constant range.
7152         ConstantRange CompRange =
7153             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7154
7155         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7156         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7157       }
7158
7159   switch (Pred) {
7160   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7161     // Convert to: while (X-Y != 0)
7162     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7163                                 AllowPredicates);
7164     if (EL.hasAnyInfo()) return EL;
7165     break;
7166   }
7167   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7168     // Convert to: while (X-Y == 0)
7169     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7170     if (EL.hasAnyInfo()) return EL;
7171     break;
7172   }
7173   case ICmpInst::ICMP_SLT:
7174   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7175     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7176     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7177                                     AllowPredicates);
7178     if (EL.hasAnyInfo()) return EL;
7179     break;
7180   }
7181   case ICmpInst::ICMP_SGT:
7182   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7183     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7184     ExitLimit EL =
7185         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7186                             AllowPredicates);
7187     if (EL.hasAnyInfo()) return EL;
7188     break;
7189   }
7190   default:
7191     break;
7192   }
7193
7194   auto *ExhaustiveCount =
7195       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7196
7197   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7198     return ExhaustiveCount;
7199
7200   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7201                                       ExitCond->getOperand(1), L, OriginalPred);
7202 }
7203
7204 ScalarEvolution::ExitLimit
7205 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7206                                                       SwitchInst *Switch,
7207                                                       BasicBlock *ExitingBlock,
7208                                                       bool ControlsExit) {
7209   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7210
7211   // Give up if the exit is the default dest of a switch.
7212   if (Switch->getDefaultDest() == ExitingBlock)
7213     return getCouldNotCompute();
7214
7215   assert(L->contains(Switch->getDefaultDest()) &&
7216          "Default case must not exit the loop!");
7217   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7218   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7219
7220   // while (X != Y) --> while (X-Y != 0)
7221   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7222   if (EL.hasAnyInfo())
7223     return EL;
7224
7225   return getCouldNotCompute();
7226 }
7227
7228 static ConstantInt *
7229 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7230                                 ScalarEvolution &SE) {
7231   const SCEV *InVal = SE.getConstant(C);
7232   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7233   assert(isa<SCEVConstant>(Val) &&
7234          "Evaluation of SCEV at constant didn't fold correctly?");
7235   return cast<SCEVConstant>(Val)->getValue();
7236 }
7237
7238 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7239 /// compute the backedge execution count.
7240 ScalarEvolution::ExitLimit
7241 ScalarEvolution::computeLoadConstantCompareExitLimit(
7242   LoadInst *LI,
7243   Constant *RHS,
7244   const Loop *L,
7245   ICmpInst::Predicate predicate) {
7246   if (LI->isVolatile()) return getCouldNotCompute();
7247
7248   // Check to see if the loaded pointer is a getelementptr of a global.
7249   // TODO: Use SCEV instead of manually grubbing with GEPs.
7250   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7251   if (!GEP) return getCouldNotCompute();
7252
7253   // Make sure that it is really a constant global we are gepping, with an
7254   // initializer, and make sure the first IDX is really 0.
7255   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7256   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7257       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7258       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7259     return getCouldNotCompute();
7260
7261   // Okay, we allow one non-constant index into the GEP instruction.
7262   Value *VarIdx = nullptr;
7263   std::vector<Constant*> Indexes;
7264   unsigned VarIdxNum = 0;
7265   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7266     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7267       Indexes.push_back(CI);
7268     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7269       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7270       VarIdx = GEP->getOperand(i);
7271       VarIdxNum = i-2;
7272       Indexes.push_back(nullptr);
7273     }
7274
7275   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7276   if (!VarIdx)
7277     return getCouldNotCompute();
7278
7279   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7280   // Check to see if X is a loop variant variable value now.
7281   const SCEV *Idx = getSCEV(VarIdx);
7282   Idx = getSCEVAtScope(Idx, L);
7283
7284   // We can only recognize very limited forms of loop index expressions, in
7285   // particular, only affine AddRec's like {C1,+,C2}.
7286   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7287   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7288       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7289       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7290     return getCouldNotCompute();
7291
7292   unsigned MaxSteps = MaxBruteForceIterations;
7293   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7294     ConstantInt *ItCst = ConstantInt::get(
7295                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7296     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7297
7298     // Form the GEP offset.
7299     Indexes[VarIdxNum] = Val;
7300
7301     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7302                                                          Indexes);
7303     if (!Result) break;  // Cannot compute!
7304
7305     // Evaluate the condition for this iteration.
7306     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7307     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7308     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7309       ++NumArrayLenItCounts;
7310       return getConstant(ItCst);   // Found terminating iteration!
7311     }
7312   }
7313   return getCouldNotCompute();
7314 }
7315
7316 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7317     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7318   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7319   if (!RHS)
7320     return getCouldNotCompute();
7321
7322   const BasicBlock *Latch = L->getLoopLatch();
7323   if (!Latch)
7324     return getCouldNotCompute();
7325
7326   const BasicBlock *Predecessor = L->getLoopPredecessor();
7327   if (!Predecessor)
7328     return getCouldNotCompute();
7329
7330   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7331   // Return LHS in OutLHS and shift_opt in OutOpCode.
7332   auto MatchPositiveShift =
7333       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7334
7335     using namespace PatternMatch;
7336
7337     ConstantInt *ShiftAmt;
7338     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7339       OutOpCode = Instruction::LShr;
7340     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7341       OutOpCode = Instruction::AShr;
7342     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7343       OutOpCode = Instruction::Shl;
7344     else
7345       return false;
7346
7347     return ShiftAmt->getValue().isStrictlyPositive();
7348   };
7349
7350   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7351   //
7352   // loop:
7353   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7354   //   %iv.shifted = lshr i32 %iv, <positive constant>
7355   //
7356   // Return true on a successful match.  Return the corresponding PHI node (%iv
7357   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7358   auto MatchShiftRecurrence =
7359       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7360     Optional<Instruction::BinaryOps> PostShiftOpCode;
7361
7362     {
7363       Instruction::BinaryOps OpC;
7364       Value *V;
7365
7366       // If we encounter a shift instruction, "peel off" the shift operation,
7367       // and remember that we did so.  Later when we inspect %iv's backedge
7368       // value, we will make sure that the backedge value uses the same
7369       // operation.
7370       //
7371       // Note: the peeled shift operation does not have to be the same
7372       // instruction as the one feeding into the PHI's backedge value.  We only
7373       // really care about it being the same *kind* of shift instruction --
7374       // that's all that is required for our later inferences to hold.
7375       if (MatchPositiveShift(LHS, V, OpC)) {
7376         PostShiftOpCode = OpC;
7377         LHS = V;
7378       }
7379     }
7380
7381     PNOut = dyn_cast<PHINode>(LHS);
7382     if (!PNOut || PNOut->getParent() != L->getHeader())
7383       return false;
7384
7385     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7386     Value *OpLHS;
7387
7388     return
7389         // The backedge value for the PHI node must be a shift by a positive
7390         // amount
7391         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7392
7393         // of the PHI node itself
7394         OpLHS == PNOut &&
7395
7396         // and the kind of shift should be match the kind of shift we peeled
7397         // off, if any.
7398         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7399   };
7400
7401   PHINode *PN;
7402   Instruction::BinaryOps OpCode;
7403   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7404     return getCouldNotCompute();
7405
7406   const DataLayout &DL = getDataLayout();
7407
7408   // The key rationale for this optimization is that for some kinds of shift
7409   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7410   // within a finite number of iterations.  If the condition guarding the
7411   // backedge (in the sense that the backedge is taken if the condition is true)
7412   // is false for the value the shift recurrence stabilizes to, then we know
7413   // that the backedge is taken only a finite number of times.
7414
7415   ConstantInt *StableValue = nullptr;
7416   switch (OpCode) {
7417   default:
7418     llvm_unreachable("Impossible case!");
7419
7420   case Instruction::AShr: {
7421     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7422     // bitwidth(K) iterations.
7423     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7424     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7425                                        Predecessor->getTerminator(), &DT);
7426     auto *Ty = cast<IntegerType>(RHS->getType());
7427     if (Known.isNonNegative())
7428       StableValue = ConstantInt::get(Ty, 0);
7429     else if (Known.isNegative())
7430       StableValue = ConstantInt::get(Ty, -1, true);
7431     else
7432       return getCouldNotCompute();
7433
7434     break;
7435   }
7436   case Instruction::LShr:
7437   case Instruction::Shl:
7438     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7439     // stabilize to 0 in at most bitwidth(K) iterations.
7440     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7441     break;
7442   }
7443
7444   auto *Result =
7445       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7446   assert(Result->getType()->isIntegerTy(1) &&
7447          "Otherwise cannot be an operand to a branch instruction");
7448
7449   if (Result->isZeroValue()) {
7450     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7451     const SCEV *UpperBound =
7452         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7453     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7454   }
7455
7456   return getCouldNotCompute();
7457 }
7458
7459 /// Return true if we can constant fold an instruction of the specified type,
7460 /// assuming that all operands were constants.
7461 static bool CanConstantFold(const Instruction *I) {
7462   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7463       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7464       isa<LoadInst>(I))
7465     return true;
7466
7467   if (const CallInst *CI = dyn_cast<CallInst>(I))
7468     if (const Function *F = CI->getCalledFunction())
7469       return canConstantFoldCallTo(CI, F);
7470   return false;
7471 }
7472
7473 /// Determine whether this instruction can constant evolve within this loop
7474 /// assuming its operands can all constant evolve.
7475 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7476   // An instruction outside of the loop can't be derived from a loop PHI.
7477   if (!L->contains(I)) return false;
7478
7479   if (isa<PHINode>(I)) {
7480     // We don't currently keep track of the control flow needed to evaluate
7481     // PHIs, so we cannot handle PHIs inside of loops.
7482     return L->getHeader() == I->getParent();
7483   }
7484
7485   // If we won't be able to constant fold this expression even if the operands
7486   // are constants, bail early.
7487   return CanConstantFold(I);
7488 }
7489
7490 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7491 /// recursing through each instruction operand until reaching a loop header phi.
7492 static PHINode *
7493 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7494                                DenseMap<Instruction *, PHINode *> &PHIMap,
7495                                unsigned Depth) {
7496   if (Depth > MaxConstantEvolvingDepth)
7497     return nullptr;
7498
7499   // Otherwise, we can evaluate this instruction if all of its operands are
7500   // constant or derived from a PHI node themselves.
7501   PHINode *PHI = nullptr;
7502   for (Value *Op : UseInst->operands()) {
7503     if (isa<Constant>(Op)) continue;
7504
7505     Instruction *OpInst = dyn_cast<Instruction>(Op);
7506     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7507
7508     PHINode *P = dyn_cast<PHINode>(OpInst);
7509     if (!P)
7510       // If this operand is already visited, reuse the prior result.
7511       // We may have P != PHI if this is the deepest point at which the
7512       // inconsistent paths meet.
7513       P = PHIMap.lookup(OpInst);
7514     if (!P) {
7515       // Recurse and memoize the results, whether a phi is found or not.
7516       // This recursive call invalidates pointers into PHIMap.
7517       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7518       PHIMap[OpInst] = P;
7519     }
7520     if (!P)
7521       return nullptr;  // Not evolving from PHI
7522     if (PHI && PHI != P)
7523       return nullptr;  // Evolving from multiple different PHIs.
7524     PHI = P;
7525   }
7526   // This is a expression evolving from a constant PHI!
7527   return PHI;
7528 }
7529
7530 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7531 /// in the loop that V is derived from.  We allow arbitrary operations along the
7532 /// way, but the operands of an operation must either be constants or a value
7533 /// derived from a constant PHI.  If this expression does not fit with these
7534 /// constraints, return null.
7535 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7536   Instruction *I = dyn_cast<Instruction>(V);
7537   if (!I || !canConstantEvolve(I, L)) return nullptr;
7538
7539   if (PHINode *PN = dyn_cast<PHINode>(I))
7540     return PN;
7541
7542   // Record non-constant instructions contained by the loop.
7543   DenseMap<Instruction *, PHINode *> PHIMap;
7544   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7545 }
7546
7547 /// EvaluateExpression - Given an expression that passes the
7548 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7549 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7550 /// reason, return null.
7551 static Constant *EvaluateExpression(Value *V, const Loop *L,
7552                                     DenseMap<Instruction *, Constant *> &Vals,
7553                                     const DataLayout &DL,
7554                                     const TargetLibraryInfo *TLI) {
7555   // Convenient constant check, but redundant for recursive calls.
7556   if (Constant *C = dyn_cast<Constant>(V)) return C;
7557   Instruction *I = dyn_cast<Instruction>(V);
7558   if (!I) return nullptr;
7559
7560   if (Constant *C = Vals.lookup(I)) return C;
7561
7562   // An instruction inside the loop depends on a value outside the loop that we
7563   // weren't given a mapping for, or a value such as a call inside the loop.
7564   if (!canConstantEvolve(I, L)) return nullptr;
7565
7566   // An unmapped PHI can be due to a branch or another loop inside this loop,
7567   // or due to this not being the initial iteration through a loop where we
7568   // couldn't compute the evolution of this particular PHI last time.
7569   if (isa<PHINode>(I)) return nullptr;
7570
7571   std::vector<Constant*> Operands(I->getNumOperands());
7572
7573   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7574     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7575     if (!Operand) {
7576       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7577       if (!Operands[i]) return nullptr;
7578       continue;
7579     }
7580     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7581     Vals[Operand] = C;
7582     if (!C) return nullptr;
7583     Operands[i] = C;
7584   }
7585
7586   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7587     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7588                                            Operands[1], DL, TLI);
7589   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7590     if (!LI->isVolatile())
7591       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7592   }
7593   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7594 }
7595
7596
7597 // If every incoming value to PN except the one for BB is a specific Constant,
7598 // return that, else return nullptr.
7599 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7600   Constant *IncomingVal = nullptr;
7601
7602   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7603     if (PN->getIncomingBlock(i) == BB)
7604       continue;
7605
7606     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7607     if (!CurrentVal)
7608       return nullptr;
7609
7610     if (IncomingVal != CurrentVal) {
7611       if (IncomingVal)
7612         return nullptr;
7613       IncomingVal = CurrentVal;
7614     }
7615   }
7616
7617   return IncomingVal;
7618 }
7619
7620 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7621 /// in the header of its containing loop, we know the loop executes a
7622 /// constant number of times, and the PHI node is just a recurrence
7623 /// involving constants, fold it.
7624 Constant *
7625 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7626                                                    const APInt &BEs,
7627                                                    const Loop *L) {
7628   auto I = ConstantEvolutionLoopExitValue.find(PN);
7629   if (I != ConstantEvolutionLoopExitValue.end())
7630     return I->second;
7631
7632   if (BEs.ugt(MaxBruteForceIterations))
7633     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7634
7635   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7636
7637   DenseMap<Instruction *, Constant *> CurrentIterVals;
7638   BasicBlock *Header = L->getHeader();
7639   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7640
7641   BasicBlock *Latch = L->getLoopLatch();
7642   if (!Latch)
7643     return nullptr;
7644
7645   for (PHINode &PHI : Header->phis()) {
7646     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7647       CurrentIterVals[&PHI] = StartCST;
7648   }
7649   if (!CurrentIterVals.count(PN))
7650     return RetVal = nullptr;
7651
7652   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7653
7654   // Execute the loop symbolically to determine the exit value.
7655   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7656          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7657
7658   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7659   unsigned IterationNum = 0;
7660   const DataLayout &DL = getDataLayout();
7661   for (; ; ++IterationNum) {
7662     if (IterationNum == NumIterations)
7663       return RetVal = CurrentIterVals[PN];  // Got exit value!
7664
7665     // Compute the value of the PHIs for the next iteration.
7666     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7667     DenseMap<Instruction *, Constant *> NextIterVals;
7668     Constant *NextPHI =
7669         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7670     if (!NextPHI)
7671       return nullptr;        // Couldn't evaluate!
7672     NextIterVals[PN] = NextPHI;
7673
7674     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7675
7676     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7677     // cease to be able to evaluate one of them or if they stop evolving,
7678     // because that doesn't necessarily prevent us from computing PN.
7679     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7680     for (const auto &I : CurrentIterVals) {
7681       PHINode *PHI = dyn_cast<PHINode>(I.first);
7682       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7683       PHIsToCompute.emplace_back(PHI, I.second);
7684     }
7685     // We use two distinct loops because EvaluateExpression may invalidate any
7686     // iterators into CurrentIterVals.
7687     for (const auto &I : PHIsToCompute) {
7688       PHINode *PHI = I.first;
7689       Constant *&NextPHI = NextIterVals[PHI];
7690       if (!NextPHI) {   // Not already computed.
7691         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7692         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7693       }
7694       if (NextPHI != I.second)
7695         StoppedEvolving = false;
7696     }
7697
7698     // If all entries in CurrentIterVals == NextIterVals then we can stop
7699     // iterating, the loop can't continue to change.
7700     if (StoppedEvolving)
7701       return RetVal = CurrentIterVals[PN];
7702
7703     CurrentIterVals.swap(NextIterVals);
7704   }
7705 }
7706
7707 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7708                                                           Value *Cond,
7709                                                           bool ExitWhen) {
7710   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7711   if (!PN) return getCouldNotCompute();
7712
7713   // If the loop is canonicalized, the PHI will have exactly two entries.
7714   // That's the only form we support here.
7715   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7716
7717   DenseMap<Instruction *, Constant *> CurrentIterVals;
7718   BasicBlock *Header = L->getHeader();
7719   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7720
7721   BasicBlock *Latch = L->getLoopLatch();
7722   assert(Latch && "Should follow from NumIncomingValues == 2!");
7723
7724   for (PHINode &PHI : Header->phis()) {
7725     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7726       CurrentIterVals[&PHI] = StartCST;
7727   }
7728   if (!CurrentIterVals.count(PN))
7729     return getCouldNotCompute();
7730
7731   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7732   // the loop symbolically to determine when the condition gets a value of
7733   // "ExitWhen".
7734   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7735   const DataLayout &DL = getDataLayout();
7736   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7737     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7738         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7739
7740     // Couldn't symbolically evaluate.
7741     if (!CondVal) return getCouldNotCompute();
7742
7743     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7744       ++NumBruteForceTripCountsComputed;
7745       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7746     }
7747
7748     // Update all the PHI nodes for the next iteration.
7749     DenseMap<Instruction *, Constant *> NextIterVals;
7750
7751     // Create a list of which PHIs we need to compute. We want to do this before
7752     // calling EvaluateExpression on them because that may invalidate iterators
7753     // into CurrentIterVals.
7754     SmallVector<PHINode *, 8> PHIsToCompute;
7755     for (const auto &I : CurrentIterVals) {
7756       PHINode *PHI = dyn_cast<PHINode>(I.first);
7757       if (!PHI || PHI->getParent() != Header) continue;
7758       PHIsToCompute.push_back(PHI);
7759     }
7760     for (PHINode *PHI : PHIsToCompute) {
7761       Constant *&NextPHI = NextIterVals[PHI];
7762       if (NextPHI) continue;    // Already computed!
7763
7764       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7765       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7766     }
7767     CurrentIterVals.swap(NextIterVals);
7768   }
7769
7770   // Too many iterations were needed to evaluate.
7771   return getCouldNotCompute();
7772 }
7773
7774 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7775   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7776       ValuesAtScopes[V];
7777   // Check to see if we've folded this expression at this loop before.
7778   for (auto &LS : Values)
7779     if (LS.first == L)
7780       return LS.second ? LS.second : V;
7781
7782   Values.emplace_back(L, nullptr);
7783
7784   // Otherwise compute it.
7785   const SCEV *C = computeSCEVAtScope(V, L);
7786   for (auto &LS : reverse(ValuesAtScopes[V]))
7787     if (LS.first == L) {
7788       LS.second = C;
7789       break;
7790     }
7791   return C;
7792 }
7793
7794 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7795 /// will return Constants for objects which aren't represented by a
7796 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7797 /// Returns NULL if the SCEV isn't representable as a Constant.
7798 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7799   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7800     case scCouldNotCompute:
7801     case scAddRecExpr:
7802       break;
7803     case scConstant:
7804       return cast<SCEVConstant>(V)->getValue();
7805     case scUnknown:
7806       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7807     case scSignExtend: {
7808       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7809       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7810         return ConstantExpr::getSExt(CastOp, SS->getType());
7811       break;
7812     }
7813     case scZeroExtend: {
7814       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7815       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7816         return ConstantExpr::getZExt(CastOp, SZ->getType());
7817       break;
7818     }
7819     case scTruncate: {
7820       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7821       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7822         return ConstantExpr::getTrunc(CastOp, ST->getType());
7823       break;
7824     }
7825     case scAddExpr: {
7826       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7827       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7828         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7829           unsigned AS = PTy->getAddressSpace();
7830           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7831           C = ConstantExpr::getBitCast(C, DestPtrTy);
7832         }
7833         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7834           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7835           if (!C2) return nullptr;
7836
7837           // First pointer!
7838           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7839             unsigned AS = C2->getType()->getPointerAddressSpace();
7840             std::swap(C, C2);
7841             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7842             // The offsets have been converted to bytes.  We can add bytes to an
7843             // i8* by GEP with the byte count in the first index.
7844             C = ConstantExpr::getBitCast(C, DestPtrTy);
7845           }
7846
7847           // Don't bother trying to sum two pointers. We probably can't
7848           // statically compute a load that results from it anyway.
7849           if (C2->getType()->isPointerTy())
7850             return nullptr;
7851
7852           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7853             if (PTy->getElementType()->isStructTy())
7854               C2 = ConstantExpr::getIntegerCast(
7855                   C2, Type::getInt32Ty(C->getContext()), true);
7856             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7857           } else
7858             C = ConstantExpr::getAdd(C, C2);
7859         }
7860         return C;
7861       }
7862       break;
7863     }
7864     case scMulExpr: {
7865       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7866       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7867         // Don't bother with pointers at all.
7868         if (C->getType()->isPointerTy()) return nullptr;
7869         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7870           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7871           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7872           C = ConstantExpr::getMul(C, C2);
7873         }
7874         return C;
7875       }
7876       break;
7877     }
7878     case scUDivExpr: {
7879       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7880       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7881         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7882           if (LHS->getType() == RHS->getType())
7883             return ConstantExpr::getUDiv(LHS, RHS);
7884       break;
7885     }
7886     case scSMaxExpr:
7887     case scUMaxExpr:
7888       break; // TODO: smax, umax.
7889   }
7890   return nullptr;
7891 }
7892
7893 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7894   if (isa<SCEVConstant>(V)) return V;
7895
7896   // If this instruction is evolved from a constant-evolving PHI, compute the
7897   // exit value from the loop without using SCEVs.
7898   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7899     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7900       const Loop *LI = this->LI[I->getParent()];
7901       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7902         if (PHINode *PN = dyn_cast<PHINode>(I))
7903           if (PN->getParent() == LI->getHeader()) {
7904             // Okay, there is no closed form solution for the PHI node.  Check
7905             // to see if the loop that contains it has a known backedge-taken
7906             // count.  If so, we may be able to force computation of the exit
7907             // value.
7908             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7909             if (const SCEVConstant *BTCC =
7910                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7911
7912               // This trivial case can show up in some degenerate cases where
7913               // the incoming IR has not yet been fully simplified.
7914               if (BTCC->getValue()->isZero()) {
7915                 Value *InitValue = nullptr;
7916                 bool MultipleInitValues = false;
7917                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7918                   if (!LI->contains(PN->getIncomingBlock(i))) {
7919                     if (!InitValue)
7920                       InitValue = PN->getIncomingValue(i);
7921                     else if (InitValue != PN->getIncomingValue(i)) {
7922                       MultipleInitValues = true;
7923                       break;
7924                     }
7925                   }
7926                   if (!MultipleInitValues && InitValue)
7927                     return getSCEV(InitValue);
7928                 }
7929               }
7930               // Okay, we know how many times the containing loop executes.  If
7931               // this is a constant evolving PHI node, get the final value at
7932               // the specified iteration number.
7933               Constant *RV =
7934                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7935               if (RV) return getSCEV(RV);
7936             }
7937           }
7938
7939       // Okay, this is an expression that we cannot symbolically evaluate
7940       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7941       // the arguments into constants, and if so, try to constant propagate the
7942       // result.  This is particularly useful for computing loop exit values.
7943       if (CanConstantFold(I)) {
7944         SmallVector<Constant *, 4> Operands;
7945         bool MadeImprovement = false;
7946         for (Value *Op : I->operands()) {
7947           if (Constant *C = dyn_cast<Constant>(Op)) {
7948             Operands.push_back(C);
7949             continue;
7950           }
7951
7952           // If any of the operands is non-constant and if they are
7953           // non-integer and non-pointer, don't even try to analyze them
7954           // with scev techniques.
7955           if (!isSCEVable(Op->getType()))
7956             return V;
7957
7958           const SCEV *OrigV = getSCEV(Op);
7959           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7960           MadeImprovement |= OrigV != OpV;
7961
7962           Constant *C = BuildConstantFromSCEV(OpV);
7963           if (!C) return V;
7964           if (C->getType() != Op->getType())
7965             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7966                                                               Op->getType(),
7967                                                               false),
7968                                       C, Op->getType());
7969           Operands.push_back(C);
7970         }
7971
7972         // Check to see if getSCEVAtScope actually made an improvement.
7973         if (MadeImprovement) {
7974           Constant *C = nullptr;
7975           const DataLayout &DL = getDataLayout();
7976           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7977             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7978                                                 Operands[1], DL, &TLI);
7979           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7980             if (!LI->isVolatile())
7981               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7982           } else
7983             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7984           if (!C) return V;
7985           return getSCEV(C);
7986         }
7987       }
7988     }
7989
7990     // This is some other type of SCEVUnknown, just return it.
7991     return V;
7992   }
7993
7994   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7995     // Avoid performing the look-up in the common case where the specified
7996     // expression has no loop-variant portions.
7997     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7998       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7999       if (OpAtScope != Comm->getOperand(i)) {
8000         // Okay, at least one of these operands is loop variant but might be
8001         // foldable.  Build a new instance of the folded commutative expression.
8002         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8003                                             Comm->op_begin()+i);
8004         NewOps.push_back(OpAtScope);
8005
8006         for (++i; i != e; ++i) {
8007           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8008           NewOps.push_back(OpAtScope);
8009         }
8010         if (isa<SCEVAddExpr>(Comm))
8011           return getAddExpr(NewOps);
8012         if (isa<SCEVMulExpr>(Comm))
8013           return getMulExpr(NewOps);
8014         if (isa<SCEVSMaxExpr>(Comm))
8015           return getSMaxExpr(NewOps);
8016         if (isa<SCEVUMaxExpr>(Comm))
8017           return getUMaxExpr(NewOps);
8018         llvm_unreachable("Unknown commutative SCEV type!");
8019       }
8020     }
8021     // If we got here, all operands are loop invariant.
8022     return Comm;
8023   }
8024
8025   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8026     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8027     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8028     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8029       return Div;   // must be loop invariant
8030     return getUDivExpr(LHS, RHS);
8031   }
8032
8033   // If this is a loop recurrence for a loop that does not contain L, then we
8034   // are dealing with the final value computed by the loop.
8035   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8036     // First, attempt to evaluate each operand.
8037     // Avoid performing the look-up in the common case where the specified
8038     // expression has no loop-variant portions.
8039     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8040       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8041       if (OpAtScope == AddRec->getOperand(i))
8042         continue;
8043
8044       // Okay, at least one of these operands is loop variant but might be
8045       // foldable.  Build a new instance of the folded commutative expression.
8046       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8047                                           AddRec->op_begin()+i);
8048       NewOps.push_back(OpAtScope);
8049       for (++i; i != e; ++i)
8050         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8051
8052       const SCEV *FoldedRec =
8053         getAddRecExpr(NewOps, AddRec->getLoop(),
8054                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8055       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8056       // The addrec may be folded to a nonrecurrence, for example, if the
8057       // induction variable is multiplied by zero after constant folding. Go
8058       // ahead and return the folded value.
8059       if (!AddRec)
8060         return FoldedRec;
8061       break;
8062     }
8063
8064     // If the scope is outside the addrec's loop, evaluate it by using the
8065     // loop exit value of the addrec.
8066     if (!AddRec->getLoop()->contains(L)) {
8067       // To evaluate this recurrence, we need to know how many times the AddRec
8068       // loop iterates.  Compute this now.
8069       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8070       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8071
8072       // Then, evaluate the AddRec.
8073       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8074     }
8075
8076     return AddRec;
8077   }
8078
8079   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8080     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8081     if (Op == Cast->getOperand())
8082       return Cast;  // must be loop invariant
8083     return getZeroExtendExpr(Op, Cast->getType());
8084   }
8085
8086   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8087     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8088     if (Op == Cast->getOperand())
8089       return Cast;  // must be loop invariant
8090     return getSignExtendExpr(Op, Cast->getType());
8091   }
8092
8093   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8094     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8095     if (Op == Cast->getOperand())
8096       return Cast;  // must be loop invariant
8097     return getTruncateExpr(Op, Cast->getType());
8098   }
8099
8100   llvm_unreachable("Unknown SCEV type!");
8101 }
8102
8103 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8104   return getSCEVAtScope(getSCEV(V), L);
8105 }
8106
8107 /// Finds the minimum unsigned root of the following equation:
8108 ///
8109 ///     A * X = B (mod N)
8110 ///
8111 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8112 /// A and B isn't important.
8113 ///
8114 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8115 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8116                                                ScalarEvolution &SE) {
8117   uint32_t BW = A.getBitWidth();
8118   assert(BW == SE.getTypeSizeInBits(B->getType()));
8119   assert(A != 0 && "A must be non-zero.");
8120
8121   // 1. D = gcd(A, N)
8122   //
8123   // The gcd of A and N may have only one prime factor: 2. The number of
8124   // trailing zeros in A is its multiplicity
8125   uint32_t Mult2 = A.countTrailingZeros();
8126   // D = 2^Mult2
8127
8128   // 2. Check if B is divisible by D.
8129   //
8130   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8131   // is not less than multiplicity of this prime factor for D.
8132   if (SE.GetMinTrailingZeros(B) < Mult2)
8133     return SE.getCouldNotCompute();
8134
8135   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8136   // modulo (N / D).
8137   //
8138   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8139   // (N / D) in general. The inverse itself always fits into BW bits, though,
8140   // so we immediately truncate it.
8141   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8142   APInt Mod(BW + 1, 0);
8143   Mod.setBit(BW - Mult2);  // Mod = N / D
8144   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8145
8146   // 4. Compute the minimum unsigned root of the equation:
8147   // I * (B / D) mod (N / D)
8148   // To simplify the computation, we factor out the divide by D:
8149   // (I * B mod N) / D
8150   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8151   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8152 }
8153
8154 /// Find the roots of the quadratic equation for the given quadratic chrec
8155 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8156 /// two SCEVCouldNotCompute objects.
8157 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8158 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8159   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8160   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8161   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8162   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8163
8164   // We currently can only solve this if the coefficients are constants.
8165   if (!LC || !MC || !NC)
8166     return None;
8167
8168   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8169   const APInt &L = LC->getAPInt();
8170   const APInt &M = MC->getAPInt();
8171   const APInt &N = NC->getAPInt();
8172   APInt Two(BitWidth, 2);
8173
8174   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8175
8176   // The A coefficient is N/2
8177   APInt A = N.sdiv(Two);
8178
8179   // The B coefficient is M-N/2
8180   APInt B = M;
8181   B -= A; // A is the same as N/2.
8182
8183   // The C coefficient is L.
8184   const APInt& C = L;
8185
8186   // Compute the B^2-4ac term.
8187   APInt SqrtTerm = B;
8188   SqrtTerm *= B;
8189   SqrtTerm -= 4 * (A * C);
8190
8191   if (SqrtTerm.isNegative()) {
8192     // The loop is provably infinite.
8193     return None;
8194   }
8195
8196   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8197   // integer value or else APInt::sqrt() will assert.
8198   APInt SqrtVal = SqrtTerm.sqrt();
8199
8200   // Compute the two solutions for the quadratic formula.
8201   // The divisions must be performed as signed divisions.
8202   APInt NegB = -std::move(B);
8203   APInt TwoA = std::move(A);
8204   TwoA <<= 1;
8205   if (TwoA.isNullValue())
8206     return None;
8207
8208   LLVMContext &Context = SE.getContext();
8209
8210   ConstantInt *Solution1 =
8211     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8212   ConstantInt *Solution2 =
8213     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8214
8215   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8216                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8217 }
8218
8219 ScalarEvolution::ExitLimit
8220 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8221                               bool AllowPredicates) {
8222
8223   // This is only used for loops with a "x != y" exit test. The exit condition
8224   // is now expressed as a single expression, V = x-y. So the exit test is
8225   // effectively V != 0.  We know and take advantage of the fact that this
8226   // expression only being used in a comparison by zero context.
8227
8228   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8229   // If the value is a constant
8230   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8231     // If the value is already zero, the branch will execute zero times.
8232     if (C->getValue()->isZero()) return C;
8233     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8234   }
8235
8236   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8237   if (!AddRec && AllowPredicates)
8238     // Try to make this an AddRec using runtime tests, in the first X
8239     // iterations of this loop, where X is the SCEV expression found by the
8240     // algorithm below.
8241     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8242
8243   if (!AddRec || AddRec->getLoop() != L)
8244     return getCouldNotCompute();
8245
8246   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8247   // the quadratic equation to solve it.
8248   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8249     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8250       const SCEVConstant *R1 = Roots->first;
8251       const SCEVConstant *R2 = Roots->second;
8252       // Pick the smallest positive root value.
8253       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8254               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8255         if (!CB->getZExtValue())
8256           std::swap(R1, R2); // R1 is the minimum root now.
8257
8258         // We can only use this value if the chrec ends up with an exact zero
8259         // value at this index.  When solving for "X*X != 5", for example, we
8260         // should not accept a root of 2.
8261         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8262         if (Val->isZero())
8263           // We found a quadratic root!
8264           return ExitLimit(R1, R1, false, Predicates);
8265       }
8266     }
8267     return getCouldNotCompute();
8268   }
8269
8270   // Otherwise we can only handle this if it is affine.
8271   if (!AddRec->isAffine())
8272     return getCouldNotCompute();
8273
8274   // If this is an affine expression, the execution count of this branch is
8275   // the minimum unsigned root of the following equation:
8276   //
8277   //     Start + Step*N = 0 (mod 2^BW)
8278   //
8279   // equivalent to:
8280   //
8281   //             Step*N = -Start (mod 2^BW)
8282   //
8283   // where BW is the common bit width of Start and Step.
8284
8285   // Get the initial value for the loop.
8286   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8287   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8288
8289   // For now we handle only constant steps.
8290   //
8291   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8292   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8293   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8294   // We have not yet seen any such cases.
8295   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8296   if (!StepC || StepC->getValue()->isZero())
8297     return getCouldNotCompute();
8298
8299   // For positive steps (counting up until unsigned overflow):
8300   //   N = -Start/Step (as unsigned)
8301   // For negative steps (counting down to zero):
8302   //   N = Start/-Step
8303   // First compute the unsigned distance from zero in the direction of Step.
8304   bool CountDown = StepC->getAPInt().isNegative();
8305   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8306
8307   // Handle unitary steps, which cannot wraparound.
8308   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8309   //   N = Distance (as unsigned)
8310   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8311     APInt MaxBECount = getUnsignedRangeMax(Distance);
8312
8313     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8314     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8315     // case, and see if we can improve the bound.
8316     //
8317     // Explicitly handling this here is necessary because getUnsignedRange
8318     // isn't context-sensitive; it doesn't know that we only care about the
8319     // range inside the loop.
8320     const SCEV *Zero = getZero(Distance->getType());
8321     const SCEV *One = getOne(Distance->getType());
8322     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8323     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8324       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8325       // as "unsigned_max(Distance + 1) - 1".
8326       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8327       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8328     }
8329     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8330   }
8331
8332   // If the condition controls loop exit (the loop exits only if the expression
8333   // is true) and the addition is no-wrap we can use unsigned divide to
8334   // compute the backedge count.  In this case, the step may not divide the
8335   // distance, but we don't care because if the condition is "missed" the loop
8336   // will have undefined behavior due to wrapping.
8337   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8338       loopHasNoAbnormalExits(AddRec->getLoop())) {
8339     const SCEV *Exact =
8340         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8341     const SCEV *Max =
8342         Exact == getCouldNotCompute()
8343             ? Exact
8344             : getConstant(getUnsignedRangeMax(Exact));
8345     return ExitLimit(Exact, Max, false, Predicates);
8346   }
8347
8348   // Solve the general equation.
8349   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8350                                                getNegativeSCEV(Start), *this);
8351   const SCEV *M = E == getCouldNotCompute()
8352                       ? E
8353                       : getConstant(getUnsignedRangeMax(E));
8354   return ExitLimit(E, M, false, Predicates);
8355 }
8356
8357 ScalarEvolution::ExitLimit
8358 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8359   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8360   // handle them yet except for the trivial case.  This could be expanded in the
8361   // future as needed.
8362
8363   // If the value is a constant, check to see if it is known to be non-zero
8364   // already.  If so, the backedge will execute zero times.
8365   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8366     if (!C->getValue()->isZero())
8367       return getZero(C->getType());
8368     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8369   }
8370
8371   // We could implement others, but I really doubt anyone writes loops like
8372   // this, and if they did, they would already be constant folded.
8373   return getCouldNotCompute();
8374 }
8375
8376 std::pair<BasicBlock *, BasicBlock *>
8377 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8378   // If the block has a unique predecessor, then there is no path from the
8379   // predecessor to the block that does not go through the direct edge
8380   // from the predecessor to the block.
8381   if (BasicBlock *Pred = BB->getSinglePredecessor())
8382     return {Pred, BB};
8383
8384   // A loop's header is defined to be a block that dominates the loop.
8385   // If the header has a unique predecessor outside the loop, it must be
8386   // a block that has exactly one successor that can reach the loop.
8387   if (Loop *L = LI.getLoopFor(BB))
8388     return {L->getLoopPredecessor(), L->getHeader()};
8389
8390   return {nullptr, nullptr};
8391 }
8392
8393 /// SCEV structural equivalence is usually sufficient for testing whether two
8394 /// expressions are equal, however for the purposes of looking for a condition
8395 /// guarding a loop, it can be useful to be a little more general, since a
8396 /// front-end may have replicated the controlling expression.
8397 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8398   // Quick check to see if they are the same SCEV.
8399   if (A == B) return true;
8400
8401   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8402     // Not all instructions that are "identical" compute the same value.  For
8403     // instance, two distinct alloca instructions allocating the same type are
8404     // identical and do not read memory; but compute distinct values.
8405     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8406   };
8407
8408   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8409   // two different instructions with the same value. Check for this case.
8410   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8411     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8412       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8413         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8414           if (ComputesEqualValues(AI, BI))
8415             return true;
8416
8417   // Otherwise assume they may have a different value.
8418   return false;
8419 }
8420
8421 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8422                                            const SCEV *&LHS, const SCEV *&RHS,
8423                                            unsigned Depth) {
8424   bool Changed = false;
8425
8426   // If we hit the max recursion limit bail out.
8427   if (Depth >= 3)
8428     return false;
8429
8430   // Canonicalize a constant to the right side.
8431   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8432     // Check for both operands constant.
8433     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8434       if (ConstantExpr::getICmp(Pred,
8435                                 LHSC->getValue(),
8436                                 RHSC->getValue())->isNullValue())
8437         goto trivially_false;
8438       else
8439         goto trivially_true;
8440     }
8441     // Otherwise swap the operands to put the constant on the right.
8442     std::swap(LHS, RHS);
8443     Pred = ICmpInst::getSwappedPredicate(Pred);
8444     Changed = true;
8445   }
8446
8447   // If we're comparing an addrec with a value which is loop-invariant in the
8448   // addrec's loop, put the addrec on the left. Also make a dominance check,
8449   // as both operands could be addrecs loop-invariant in each other's loop.
8450   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8451     const Loop *L = AR->getLoop();
8452     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8453       std::swap(LHS, RHS);
8454       Pred = ICmpInst::getSwappedPredicate(Pred);
8455       Changed = true;
8456     }
8457   }
8458
8459   // If there's a constant operand, canonicalize comparisons with boundary
8460   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8461   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8462     const APInt &RA = RC->getAPInt();
8463
8464     bool SimplifiedByConstantRange = false;
8465
8466     if (!ICmpInst::isEquality(Pred)) {
8467       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8468       if (ExactCR.isFullSet())
8469         goto trivially_true;
8470       else if (ExactCR.isEmptySet())
8471         goto trivially_false;
8472
8473       APInt NewRHS;
8474       CmpInst::Predicate NewPred;
8475       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8476           ICmpInst::isEquality(NewPred)) {
8477         // We were able to convert an inequality to an equality.
8478         Pred = NewPred;
8479         RHS = getConstant(NewRHS);
8480         Changed = SimplifiedByConstantRange = true;
8481       }
8482     }
8483
8484     if (!SimplifiedByConstantRange) {
8485       switch (Pred) {
8486       default:
8487         break;
8488       case ICmpInst::ICMP_EQ:
8489       case ICmpInst::ICMP_NE:
8490         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8491         if (!RA)
8492           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8493             if (const SCEVMulExpr *ME =
8494                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8495               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8496                   ME->getOperand(0)->isAllOnesValue()) {
8497                 RHS = AE->getOperand(1);
8498                 LHS = ME->getOperand(1);
8499                 Changed = true;
8500               }
8501         break;
8502
8503
8504         // The "Should have been caught earlier!" messages refer to the fact
8505         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8506         // should have fired on the corresponding cases, and canonicalized the
8507         // check to trivially_true or trivially_false.
8508
8509       case ICmpInst::ICMP_UGE:
8510         assert(!RA.isMinValue() && "Should have been caught earlier!");
8511         Pred = ICmpInst::ICMP_UGT;
8512         RHS = getConstant(RA - 1);
8513         Changed = true;
8514         break;
8515       case ICmpInst::ICMP_ULE:
8516         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8517         Pred = ICmpInst::ICMP_ULT;
8518         RHS = getConstant(RA + 1);
8519         Changed = true;
8520         break;
8521       case ICmpInst::ICMP_SGE:
8522         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8523         Pred = ICmpInst::ICMP_SGT;
8524         RHS = getConstant(RA - 1);
8525         Changed = true;
8526         break;
8527       case ICmpInst::ICMP_SLE:
8528         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8529         Pred = ICmpInst::ICMP_SLT;
8530         RHS = getConstant(RA + 1);
8531         Changed = true;
8532         break;
8533       }
8534     }
8535   }
8536
8537   // Check for obvious equality.
8538   if (HasSameValue(LHS, RHS)) {
8539     if (ICmpInst::isTrueWhenEqual(Pred))
8540       goto trivially_true;
8541     if (ICmpInst::isFalseWhenEqual(Pred))
8542       goto trivially_false;
8543   }
8544
8545   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8546   // adding or subtracting 1 from one of the operands.
8547   switch (Pred) {
8548   case ICmpInst::ICMP_SLE:
8549     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8550       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8551                        SCEV::FlagNSW);
8552       Pred = ICmpInst::ICMP_SLT;
8553       Changed = true;
8554     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8555       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8556                        SCEV::FlagNSW);
8557       Pred = ICmpInst::ICMP_SLT;
8558       Changed = true;
8559     }
8560     break;
8561   case ICmpInst::ICMP_SGE:
8562     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8563       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8564                        SCEV::FlagNSW);
8565       Pred = ICmpInst::ICMP_SGT;
8566       Changed = true;
8567     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8568       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8569                        SCEV::FlagNSW);
8570       Pred = ICmpInst::ICMP_SGT;
8571       Changed = true;
8572     }
8573     break;
8574   case ICmpInst::ICMP_ULE:
8575     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8576       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8577                        SCEV::FlagNUW);
8578       Pred = ICmpInst::ICMP_ULT;
8579       Changed = true;
8580     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8581       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8582       Pred = ICmpInst::ICMP_ULT;
8583       Changed = true;
8584     }
8585     break;
8586   case ICmpInst::ICMP_UGE:
8587     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8588       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8589       Pred = ICmpInst::ICMP_UGT;
8590       Changed = true;
8591     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8592       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8593                        SCEV::FlagNUW);
8594       Pred = ICmpInst::ICMP_UGT;
8595       Changed = true;
8596     }
8597     break;
8598   default:
8599     break;
8600   }
8601
8602   // TODO: More simplifications are possible here.
8603
8604   // Recursively simplify until we either hit a recursion limit or nothing
8605   // changes.
8606   if (Changed)
8607     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8608
8609   return Changed;
8610
8611 trivially_true:
8612   // Return 0 == 0.
8613   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8614   Pred = ICmpInst::ICMP_EQ;
8615   return true;
8616
8617 trivially_false:
8618   // Return 0 != 0.
8619   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8620   Pred = ICmpInst::ICMP_NE;
8621   return true;
8622 }
8623
8624 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8625   return getSignedRangeMax(S).isNegative();
8626 }
8627
8628 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8629   return getSignedRangeMin(S).isStrictlyPositive();
8630 }
8631
8632 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8633   return !getSignedRangeMin(S).isNegative();
8634 }
8635
8636 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8637   return !getSignedRangeMax(S).isStrictlyPositive();
8638 }
8639
8640 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8641   return isKnownNegative(S) || isKnownPositive(S);
8642 }
8643
8644 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8645                                        const SCEV *LHS, const SCEV *RHS) {
8646   // Canonicalize the inputs first.
8647   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8648
8649   // If LHS or RHS is an addrec, check to see if the condition is true in
8650   // every iteration of the loop.
8651   // If LHS and RHS are both addrec, both conditions must be true in
8652   // every iteration of the loop.
8653   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8654   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8655   bool LeftGuarded = false;
8656   bool RightGuarded = false;
8657   if (LAR) {
8658     const Loop *L = LAR->getLoop();
8659     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
8660         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
8661       if (!RAR) return true;
8662       LeftGuarded = true;
8663     }
8664   }
8665   if (RAR) {
8666     const Loop *L = RAR->getLoop();
8667     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
8668         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
8669       if (!LAR) return true;
8670       RightGuarded = true;
8671     }
8672   }
8673   if (LeftGuarded && RightGuarded)
8674     return true;
8675
8676   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8677     return true;
8678
8679   // Otherwise see what can be done with known constant ranges.
8680   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
8681 }
8682
8683 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8684                                            ICmpInst::Predicate Pred,
8685                                            bool &Increasing) {
8686   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8687
8688 #ifndef NDEBUG
8689   // Verify an invariant: inverting the predicate should turn a monotonically
8690   // increasing change to a monotonically decreasing one, and vice versa.
8691   bool IncreasingSwapped;
8692   bool ResultSwapped = isMonotonicPredicateImpl(
8693       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8694
8695   assert(Result == ResultSwapped && "should be able to analyze both!");
8696   if (ResultSwapped)
8697     assert(Increasing == !IncreasingSwapped &&
8698            "monotonicity should flip as we flip the predicate");
8699 #endif
8700
8701   return Result;
8702 }
8703
8704 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8705                                                ICmpInst::Predicate Pred,
8706                                                bool &Increasing) {
8707
8708   // A zero step value for LHS means the induction variable is essentially a
8709   // loop invariant value. We don't really depend on the predicate actually
8710   // flipping from false to true (for increasing predicates, and the other way
8711   // around for decreasing predicates), all we care about is that *if* the
8712   // predicate changes then it only changes from false to true.
8713   //
8714   // A zero step value in itself is not very useful, but there may be places
8715   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8716   // as general as possible.
8717
8718   switch (Pred) {
8719   default:
8720     return false; // Conservative answer
8721
8722   case ICmpInst::ICMP_UGT:
8723   case ICmpInst::ICMP_UGE:
8724   case ICmpInst::ICMP_ULT:
8725   case ICmpInst::ICMP_ULE:
8726     if (!LHS->hasNoUnsignedWrap())
8727       return false;
8728
8729     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8730     return true;
8731
8732   case ICmpInst::ICMP_SGT:
8733   case ICmpInst::ICMP_SGE:
8734   case ICmpInst::ICMP_SLT:
8735   case ICmpInst::ICMP_SLE: {
8736     if (!LHS->hasNoSignedWrap())
8737       return false;
8738
8739     const SCEV *Step = LHS->getStepRecurrence(*this);
8740
8741     if (isKnownNonNegative(Step)) {
8742       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8743       return true;
8744     }
8745
8746     if (isKnownNonPositive(Step)) {
8747       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8748       return true;
8749     }
8750
8751     return false;
8752   }
8753
8754   }
8755
8756   llvm_unreachable("switch has default clause!");
8757 }
8758
8759 bool ScalarEvolution::isLoopInvariantPredicate(
8760     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8761     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8762     const SCEV *&InvariantRHS) {
8763
8764   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8765   if (!isLoopInvariant(RHS, L)) {
8766     if (!isLoopInvariant(LHS, L))
8767       return false;
8768
8769     std::swap(LHS, RHS);
8770     Pred = ICmpInst::getSwappedPredicate(Pred);
8771   }
8772
8773   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8774   if (!ArLHS || ArLHS->getLoop() != L)
8775     return false;
8776
8777   bool Increasing;
8778   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8779     return false;
8780
8781   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8782   // true as the loop iterates, and the backedge is control dependent on
8783   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8784   //
8785   //   * if the predicate was false in the first iteration then the predicate
8786   //     is never evaluated again, since the loop exits without taking the
8787   //     backedge.
8788   //   * if the predicate was true in the first iteration then it will
8789   //     continue to be true for all future iterations since it is
8790   //     monotonically increasing.
8791   //
8792   // For both the above possibilities, we can replace the loop varying
8793   // predicate with its value on the first iteration of the loop (which is
8794   // loop invariant).
8795   //
8796   // A similar reasoning applies for a monotonically decreasing predicate, by
8797   // replacing true with false and false with true in the above two bullets.
8798
8799   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8800
8801   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8802     return false;
8803
8804   InvariantPred = Pred;
8805   InvariantLHS = ArLHS->getStart();
8806   InvariantRHS = RHS;
8807   return true;
8808 }
8809
8810 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8811     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8812   if (HasSameValue(LHS, RHS))
8813     return ICmpInst::isTrueWhenEqual(Pred);
8814
8815   // This code is split out from isKnownPredicate because it is called from
8816   // within isLoopEntryGuardedByCond.
8817
8818   auto CheckRanges =
8819       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8820     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8821         .contains(RangeLHS);
8822   };
8823
8824   // The check at the top of the function catches the case where the values are
8825   // known to be equal.
8826   if (Pred == CmpInst::ICMP_EQ)
8827     return false;
8828
8829   if (Pred == CmpInst::ICMP_NE)
8830     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8831            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8832            isKnownNonZero(getMinusSCEV(LHS, RHS));
8833
8834   if (CmpInst::isSigned(Pred))
8835     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8836
8837   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8838 }
8839
8840 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8841                                                     const SCEV *LHS,
8842                                                     const SCEV *RHS) {
8843   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8844   // Return Y via OutY.
8845   auto MatchBinaryAddToConst =
8846       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8847              SCEV::NoWrapFlags ExpectedFlags) {
8848     const SCEV *NonConstOp, *ConstOp;
8849     SCEV::NoWrapFlags FlagsPresent;
8850
8851     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8852         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8853       return false;
8854
8855     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8856     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8857   };
8858
8859   APInt C;
8860
8861   switch (Pred) {
8862   default:
8863     break;
8864
8865   case ICmpInst::ICMP_SGE:
8866     std::swap(LHS, RHS);
8867     LLVM_FALLTHROUGH;
8868   case ICmpInst::ICMP_SLE:
8869     // X s<= (X + C)<nsw> if C >= 0
8870     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8871       return true;
8872
8873     // (X + C)<nsw> s<= X if C <= 0
8874     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8875         !C.isStrictlyPositive())
8876       return true;
8877     break;
8878
8879   case ICmpInst::ICMP_SGT:
8880     std::swap(LHS, RHS);
8881     LLVM_FALLTHROUGH;
8882   case ICmpInst::ICMP_SLT:
8883     // X s< (X + C)<nsw> if C > 0
8884     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8885         C.isStrictlyPositive())
8886       return true;
8887
8888     // (X + C)<nsw> s< X if C < 0
8889     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8890       return true;
8891     break;
8892   }
8893
8894   return false;
8895 }
8896
8897 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8898                                                    const SCEV *LHS,
8899                                                    const SCEV *RHS) {
8900   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8901     return false;
8902
8903   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8904   // the stack can result in exponential time complexity.
8905   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8906
8907   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8908   //
8909   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8910   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8911   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8912   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8913   // use isKnownPredicate later if needed.
8914   return isKnownNonNegative(RHS) &&
8915          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8916          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8917 }
8918
8919 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8920                                         ICmpInst::Predicate Pred,
8921                                         const SCEV *LHS, const SCEV *RHS) {
8922   // No need to even try if we know the module has no guards.
8923   if (!HasGuards)
8924     return false;
8925
8926   return any_of(*BB, [&](Instruction &I) {
8927     using namespace llvm::PatternMatch;
8928
8929     Value *Condition;
8930     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8931                          m_Value(Condition))) &&
8932            isImpliedCond(Pred, LHS, RHS, Condition, false);
8933   });
8934 }
8935
8936 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8937 /// protected by a conditional between LHS and RHS.  This is used to
8938 /// to eliminate casts.
8939 bool
8940 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8941                                              ICmpInst::Predicate Pred,
8942                                              const SCEV *LHS, const SCEV *RHS) {
8943   // Interpret a null as meaning no loop, where there is obviously no guard
8944   // (interprocedural conditions notwithstanding).
8945   if (!L) return true;
8946
8947   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8948     return true;
8949
8950   BasicBlock *Latch = L->getLoopLatch();
8951   if (!Latch)
8952     return false;
8953
8954   BranchInst *LoopContinuePredicate =
8955     dyn_cast<BranchInst>(Latch->getTerminator());
8956   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8957       isImpliedCond(Pred, LHS, RHS,
8958                     LoopContinuePredicate->getCondition(),
8959                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8960     return true;
8961
8962   // We don't want more than one activation of the following loops on the stack
8963   // -- that can lead to O(n!) time complexity.
8964   if (WalkingBEDominatingConds)
8965     return false;
8966
8967   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8968
8969   // See if we can exploit a trip count to prove the predicate.
8970   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8971   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8972   if (LatchBECount != getCouldNotCompute()) {
8973     // We know that Latch branches back to the loop header exactly
8974     // LatchBECount times.  This means the backdege condition at Latch is
8975     // equivalent to  "{0,+,1} u< LatchBECount".
8976     Type *Ty = LatchBECount->getType();
8977     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8978     const SCEV *LoopCounter =
8979       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8980     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8981                       LatchBECount))
8982       return true;
8983   }
8984
8985   // Check conditions due to any @llvm.assume intrinsics.
8986   for (auto &AssumeVH : AC.assumptions()) {
8987     if (!AssumeVH)
8988       continue;
8989     auto *CI = cast<CallInst>(AssumeVH);
8990     if (!DT.dominates(CI, Latch->getTerminator()))
8991       continue;
8992
8993     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8994       return true;
8995   }
8996
8997   // If the loop is not reachable from the entry block, we risk running into an
8998   // infinite loop as we walk up into the dom tree.  These loops do not matter
8999   // anyway, so we just return a conservative answer when we see them.
9000   if (!DT.isReachableFromEntry(L->getHeader()))
9001     return false;
9002
9003   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9004     return true;
9005
9006   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9007        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9008     assert(DTN && "should reach the loop header before reaching the root!");
9009
9010     BasicBlock *BB = DTN->getBlock();
9011     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9012       return true;
9013
9014     BasicBlock *PBB = BB->getSinglePredecessor();
9015     if (!PBB)
9016       continue;
9017
9018     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9019     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9020       continue;
9021
9022     Value *Condition = ContinuePredicate->getCondition();
9023
9024     // If we have an edge `E` within the loop body that dominates the only
9025     // latch, the condition guarding `E` also guards the backedge.  This
9026     // reasoning works only for loops with a single latch.
9027
9028     BasicBlockEdge DominatingEdge(PBB, BB);
9029     if (DominatingEdge.isSingleEdge()) {
9030       // We're constructively (and conservatively) enumerating edges within the
9031       // loop body that dominate the latch.  The dominator tree better agree
9032       // with us on this:
9033       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9034
9035       if (isImpliedCond(Pred, LHS, RHS, Condition,
9036                         BB != ContinuePredicate->getSuccessor(0)))
9037         return true;
9038     }
9039   }
9040
9041   return false;
9042 }
9043
9044 bool
9045 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9046                                           ICmpInst::Predicate Pred,
9047                                           const SCEV *LHS, const SCEV *RHS) {
9048   // Interpret a null as meaning no loop, where there is obviously no guard
9049   // (interprocedural conditions notwithstanding).
9050   if (!L) return false;
9051
9052   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
9053     return true;
9054
9055   // Starting at the loop predecessor, climb up the predecessor chain, as long
9056   // as there are predecessors that can be found that have unique successors
9057   // leading to the original header.
9058   for (std::pair<BasicBlock *, BasicBlock *>
9059          Pair(L->getLoopPredecessor(), L->getHeader());
9060        Pair.first;
9061        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9062
9063     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
9064       return true;
9065
9066     BranchInst *LoopEntryPredicate =
9067       dyn_cast<BranchInst>(Pair.first->getTerminator());
9068     if (!LoopEntryPredicate ||
9069         LoopEntryPredicate->isUnconditional())
9070       continue;
9071
9072     if (isImpliedCond(Pred, LHS, RHS,
9073                       LoopEntryPredicate->getCondition(),
9074                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
9075       return true;
9076   }
9077
9078   // Check conditions due to any @llvm.assume intrinsics.
9079   for (auto &AssumeVH : AC.assumptions()) {
9080     if (!AssumeVH)
9081       continue;
9082     auto *CI = cast<CallInst>(AssumeVH);
9083     if (!DT.dominates(CI, L->getHeader()))
9084       continue;
9085
9086     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9087       return true;
9088   }
9089
9090   return false;
9091 }
9092
9093 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9094                                     const SCEV *LHS, const SCEV *RHS,
9095                                     Value *FoundCondValue,
9096                                     bool Inverse) {
9097   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9098     return false;
9099
9100   auto ClearOnExit =
9101       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9102
9103   // Recursively handle And and Or conditions.
9104   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9105     if (BO->getOpcode() == Instruction::And) {
9106       if (!Inverse)
9107         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9108                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9109     } else if (BO->getOpcode() == Instruction::Or) {
9110       if (Inverse)
9111         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9112                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9113     }
9114   }
9115
9116   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9117   if (!ICI) return false;
9118
9119   // Now that we found a conditional branch that dominates the loop or controls
9120   // the loop latch. Check to see if it is the comparison we are looking for.
9121   ICmpInst::Predicate FoundPred;
9122   if (Inverse)
9123     FoundPred = ICI->getInversePredicate();
9124   else
9125     FoundPred = ICI->getPredicate();
9126
9127   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9128   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9129
9130   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9131 }
9132
9133 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9134                                     const SCEV *RHS,
9135                                     ICmpInst::Predicate FoundPred,
9136                                     const SCEV *FoundLHS,
9137                                     const SCEV *FoundRHS) {
9138   // Balance the types.
9139   if (getTypeSizeInBits(LHS->getType()) <
9140       getTypeSizeInBits(FoundLHS->getType())) {
9141     if (CmpInst::isSigned(Pred)) {
9142       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9143       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9144     } else {
9145       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9146       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9147     }
9148   } else if (getTypeSizeInBits(LHS->getType()) >
9149       getTypeSizeInBits(FoundLHS->getType())) {
9150     if (CmpInst::isSigned(FoundPred)) {
9151       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9152       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9153     } else {
9154       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9155       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9156     }
9157   }
9158
9159   // Canonicalize the query to match the way instcombine will have
9160   // canonicalized the comparison.
9161   if (SimplifyICmpOperands(Pred, LHS, RHS))
9162     if (LHS == RHS)
9163       return CmpInst::isTrueWhenEqual(Pred);
9164   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9165     if (FoundLHS == FoundRHS)
9166       return CmpInst::isFalseWhenEqual(FoundPred);
9167
9168   // Check to see if we can make the LHS or RHS match.
9169   if (LHS == FoundRHS || RHS == FoundLHS) {
9170     if (isa<SCEVConstant>(RHS)) {
9171       std::swap(FoundLHS, FoundRHS);
9172       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9173     } else {
9174       std::swap(LHS, RHS);
9175       Pred = ICmpInst::getSwappedPredicate(Pred);
9176     }
9177   }
9178
9179   // Check whether the found predicate is the same as the desired predicate.
9180   if (FoundPred == Pred)
9181     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9182
9183   // Check whether swapping the found predicate makes it the same as the
9184   // desired predicate.
9185   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9186     if (isa<SCEVConstant>(RHS))
9187       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9188     else
9189       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9190                                    RHS, LHS, FoundLHS, FoundRHS);
9191   }
9192
9193   // Unsigned comparison is the same as signed comparison when both the operands
9194   // are non-negative.
9195   if (CmpInst::isUnsigned(FoundPred) &&
9196       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9197       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9198     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9199
9200   // Check if we can make progress by sharpening ranges.
9201   if (FoundPred == ICmpInst::ICMP_NE &&
9202       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9203
9204     const SCEVConstant *C = nullptr;
9205     const SCEV *V = nullptr;
9206
9207     if (isa<SCEVConstant>(FoundLHS)) {
9208       C = cast<SCEVConstant>(FoundLHS);
9209       V = FoundRHS;
9210     } else {
9211       C = cast<SCEVConstant>(FoundRHS);
9212       V = FoundLHS;
9213     }
9214
9215     // The guarding predicate tells us that C != V. If the known range
9216     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9217     // range we consider has to correspond to same signedness as the
9218     // predicate we're interested in folding.
9219
9220     APInt Min = ICmpInst::isSigned(Pred) ?
9221         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9222
9223     if (Min == C->getAPInt()) {
9224       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9225       // This is true even if (Min + 1) wraps around -- in case of
9226       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9227
9228       APInt SharperMin = Min + 1;
9229
9230       switch (Pred) {
9231         case ICmpInst::ICMP_SGE:
9232         case ICmpInst::ICMP_UGE:
9233           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9234           // RHS, we're done.
9235           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9236                                     getConstant(SharperMin)))
9237             return true;
9238           LLVM_FALLTHROUGH;
9239
9240         case ICmpInst::ICMP_SGT:
9241         case ICmpInst::ICMP_UGT:
9242           // We know from the range information that (V `Pred` Min ||
9243           // V == Min).  We know from the guarding condition that !(V
9244           // == Min).  This gives us
9245           //
9246           //       V `Pred` Min || V == Min && !(V == Min)
9247           //   =>  V `Pred` Min
9248           //
9249           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9250
9251           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9252             return true;
9253           LLVM_FALLTHROUGH;
9254
9255         default:
9256           // No change
9257           break;
9258       }
9259     }
9260   }
9261
9262   // Check whether the actual condition is beyond sufficient.
9263   if (FoundPred == ICmpInst::ICMP_EQ)
9264     if (ICmpInst::isTrueWhenEqual(Pred))
9265       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9266         return true;
9267   if (Pred == ICmpInst::ICMP_NE)
9268     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9269       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9270         return true;
9271
9272   // Otherwise assume the worst.
9273   return false;
9274 }
9275
9276 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9277                                      const SCEV *&L, const SCEV *&R,
9278                                      SCEV::NoWrapFlags &Flags) {
9279   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9280   if (!AE || AE->getNumOperands() != 2)
9281     return false;
9282
9283   L = AE->getOperand(0);
9284   R = AE->getOperand(1);
9285   Flags = AE->getNoWrapFlags();
9286   return true;
9287 }
9288
9289 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9290                                                            const SCEV *Less) {
9291   // We avoid subtracting expressions here because this function is usually
9292   // fairly deep in the call stack (i.e. is called many times).
9293
9294   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9295     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9296     const auto *MAR = cast<SCEVAddRecExpr>(More);
9297
9298     if (LAR->getLoop() != MAR->getLoop())
9299       return None;
9300
9301     // We look at affine expressions only; not for correctness but to keep
9302     // getStepRecurrence cheap.
9303     if (!LAR->isAffine() || !MAR->isAffine())
9304       return None;
9305
9306     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9307       return None;
9308
9309     Less = LAR->getStart();
9310     More = MAR->getStart();
9311
9312     // fall through
9313   }
9314
9315   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9316     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9317     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9318     return M - L;
9319   }
9320
9321   const SCEV *L, *R;
9322   SCEV::NoWrapFlags Flags;
9323   if (splitBinaryAdd(Less, L, R, Flags))
9324     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9325       if (R == More)
9326         return -(LC->getAPInt());
9327
9328   if (splitBinaryAdd(More, L, R, Flags))
9329     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9330       if (R == Less)
9331         return LC->getAPInt();
9332
9333   return None;
9334 }
9335
9336 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9337     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9338     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9339   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9340     return false;
9341
9342   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9343   if (!AddRecLHS)
9344     return false;
9345
9346   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9347   if (!AddRecFoundLHS)
9348     return false;
9349
9350   // We'd like to let SCEV reason about control dependencies, so we constrain
9351   // both the inequalities to be about add recurrences on the same loop.  This
9352   // way we can use isLoopEntryGuardedByCond later.
9353
9354   const Loop *L = AddRecFoundLHS->getLoop();
9355   if (L != AddRecLHS->getLoop())
9356     return false;
9357
9358   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9359   //
9360   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9361   //                                                                  ... (2)
9362   //
9363   // Informal proof for (2), assuming (1) [*]:
9364   //
9365   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9366   //
9367   // Then
9368   //
9369   //       FoundLHS s< FoundRHS s< INT_MIN - C
9370   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9371   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9372   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9373   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9374   // <=>  FoundLHS + C s< FoundRHS + C
9375   //
9376   // [*]: (1) can be proved by ruling out overflow.
9377   //
9378   // [**]: This can be proved by analyzing all the four possibilities:
9379   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9380   //    (A s>= 0, B s>= 0).
9381   //
9382   // Note:
9383   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9384   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9385   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9386   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9387   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9388   // C)".
9389
9390   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9391   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9392   if (!LDiff || !RDiff || *LDiff != *RDiff)
9393     return false;
9394
9395   if (LDiff->isMinValue())
9396     return true;
9397
9398   APInt FoundRHSLimit;
9399
9400   if (Pred == CmpInst::ICMP_ULT) {
9401     FoundRHSLimit = -(*RDiff);
9402   } else {
9403     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9404     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9405   }
9406
9407   // Try to prove (1) or (2), as needed.
9408   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9409                                   getConstant(FoundRHSLimit));
9410 }
9411
9412 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9413                                             const SCEV *LHS, const SCEV *RHS,
9414                                             const SCEV *FoundLHS,
9415                                             const SCEV *FoundRHS) {
9416   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9417     return true;
9418
9419   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9420     return true;
9421
9422   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9423                                      FoundLHS, FoundRHS) ||
9424          // ~x < ~y --> x > y
9425          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9426                                      getNotSCEV(FoundRHS),
9427                                      getNotSCEV(FoundLHS));
9428 }
9429
9430 /// If Expr computes ~A, return A else return nullptr
9431 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9432   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9433   if (!Add || Add->getNumOperands() != 2 ||
9434       !Add->getOperand(0)->isAllOnesValue())
9435     return nullptr;
9436
9437   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9438   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9439       !AddRHS->getOperand(0)->isAllOnesValue())
9440     return nullptr;
9441
9442   return AddRHS->getOperand(1);
9443 }
9444
9445 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9446 template<typename MaxExprType>
9447 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9448                               const SCEV *Candidate) {
9449   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9450   if (!MaxExpr) return false;
9451
9452   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9453 }
9454
9455 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9456 template<typename MaxExprType>
9457 static bool IsMinConsistingOf(ScalarEvolution &SE,
9458                               const SCEV *MaybeMinExpr,
9459                               const SCEV *Candidate) {
9460   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9461   if (!MaybeMaxExpr)
9462     return false;
9463
9464   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9465 }
9466
9467 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9468                                            ICmpInst::Predicate Pred,
9469                                            const SCEV *LHS, const SCEV *RHS) {
9470   // If both sides are affine addrecs for the same loop, with equal
9471   // steps, and we know the recurrences don't wrap, then we only
9472   // need to check the predicate on the starting values.
9473
9474   if (!ICmpInst::isRelational(Pred))
9475     return false;
9476
9477   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9478   if (!LAR)
9479     return false;
9480   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9481   if (!RAR)
9482     return false;
9483   if (LAR->getLoop() != RAR->getLoop())
9484     return false;
9485   if (!LAR->isAffine() || !RAR->isAffine())
9486     return false;
9487
9488   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9489     return false;
9490
9491   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9492                          SCEV::FlagNSW : SCEV::FlagNUW;
9493   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9494     return false;
9495
9496   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9497 }
9498
9499 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9500 /// expression?
9501 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9502                                         ICmpInst::Predicate Pred,
9503                                         const SCEV *LHS, const SCEV *RHS) {
9504   switch (Pred) {
9505   default:
9506     return false;
9507
9508   case ICmpInst::ICMP_SGE:
9509     std::swap(LHS, RHS);
9510     LLVM_FALLTHROUGH;
9511   case ICmpInst::ICMP_SLE:
9512     return
9513       // min(A, ...) <= A
9514       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9515       // A <= max(A, ...)
9516       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9517
9518   case ICmpInst::ICMP_UGE:
9519     std::swap(LHS, RHS);
9520     LLVM_FALLTHROUGH;
9521   case ICmpInst::ICMP_ULE:
9522     return
9523       // min(A, ...) <= A
9524       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9525       // A <= max(A, ...)
9526       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9527   }
9528
9529   llvm_unreachable("covered switch fell through?!");
9530 }
9531
9532 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9533                                              const SCEV *LHS, const SCEV *RHS,
9534                                              const SCEV *FoundLHS,
9535                                              const SCEV *FoundRHS,
9536                                              unsigned Depth) {
9537   assert(getTypeSizeInBits(LHS->getType()) ==
9538              getTypeSizeInBits(RHS->getType()) &&
9539          "LHS and RHS have different sizes?");
9540   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9541              getTypeSizeInBits(FoundRHS->getType()) &&
9542          "FoundLHS and FoundRHS have different sizes?");
9543   // We want to avoid hurting the compile time with analysis of too big trees.
9544   if (Depth > MaxSCEVOperationsImplicationDepth)
9545     return false;
9546   // We only want to work with ICMP_SGT comparison so far.
9547   // TODO: Extend to ICMP_UGT?
9548   if (Pred == ICmpInst::ICMP_SLT) {
9549     Pred = ICmpInst::ICMP_SGT;
9550     std::swap(LHS, RHS);
9551     std::swap(FoundLHS, FoundRHS);
9552   }
9553   if (Pred != ICmpInst::ICMP_SGT)
9554     return false;
9555
9556   auto GetOpFromSExt = [&](const SCEV *S) {
9557     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9558       return Ext->getOperand();
9559     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9560     // the constant in some cases.
9561     return S;
9562   };
9563
9564   // Acquire values from extensions.
9565   auto *OrigFoundLHS = FoundLHS;
9566   LHS = GetOpFromSExt(LHS);
9567   FoundLHS = GetOpFromSExt(FoundLHS);
9568
9569   // Is the SGT predicate can be proved trivially or using the found context.
9570   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9571     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9572            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9573                                   FoundRHS, Depth + 1);
9574   };
9575
9576   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9577     // We want to avoid creation of any new non-constant SCEV. Since we are
9578     // going to compare the operands to RHS, we should be certain that we don't
9579     // need any size extensions for this. So let's decline all cases when the
9580     // sizes of types of LHS and RHS do not match.
9581     // TODO: Maybe try to get RHS from sext to catch more cases?
9582     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9583       return false;
9584
9585     // Should not overflow.
9586     if (!LHSAddExpr->hasNoSignedWrap())
9587       return false;
9588
9589     auto *LL = LHSAddExpr->getOperand(0);
9590     auto *LR = LHSAddExpr->getOperand(1);
9591     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9592
9593     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9594     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9595       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9596     };
9597     // Try to prove the following rule:
9598     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9599     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9600     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9601       return true;
9602   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9603     Value *LL, *LR;
9604     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9605
9606     using namespace llvm::PatternMatch;
9607
9608     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9609       // Rules for division.
9610       // We are going to perform some comparisons with Denominator and its
9611       // derivative expressions. In general case, creating a SCEV for it may
9612       // lead to a complex analysis of the entire graph, and in particular it
9613       // can request trip count recalculation for the same loop. This would
9614       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9615       // this, we only want to create SCEVs that are constants in this section.
9616       // So we bail if Denominator is not a constant.
9617       if (!isa<ConstantInt>(LR))
9618         return false;
9619
9620       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9621
9622       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9623       // then a SCEV for the numerator already exists and matches with FoundLHS.
9624       auto *Numerator = getExistingSCEV(LL);
9625       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9626         return false;
9627
9628       // Make sure that the numerator matches with FoundLHS and the denominator
9629       // is positive.
9630       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9631         return false;
9632
9633       auto *DTy = Denominator->getType();
9634       auto *FRHSTy = FoundRHS->getType();
9635       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9636         // One of types is a pointer and another one is not. We cannot extend
9637         // them properly to a wider type, so let us just reject this case.
9638         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9639         // to avoid this check.
9640         return false;
9641
9642       // Given that:
9643       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9644       auto *WTy = getWiderType(DTy, FRHSTy);
9645       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9646       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9647
9648       // Try to prove the following rule:
9649       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9650       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9651       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9652       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9653       if (isKnownNonPositive(RHS) &&
9654           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9655         return true;
9656
9657       // Try to prove the following rule:
9658       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9659       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9660       // If we divide it by Denominator > 2, then:
9661       // 1. If FoundLHS is negative, then the result is 0.
9662       // 2. If FoundLHS is non-negative, then the result is non-negative.
9663       // Anyways, the result is non-negative.
9664       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9665       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9666       if (isKnownNegative(RHS) &&
9667           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9668         return true;
9669     }
9670   }
9671
9672   return false;
9673 }
9674
9675 bool
9676 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
9677                                            const SCEV *LHS, const SCEV *RHS) {
9678   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9679          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9680          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9681          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9682 }
9683
9684 bool
9685 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9686                                              const SCEV *LHS, const SCEV *RHS,
9687                                              const SCEV *FoundLHS,
9688                                              const SCEV *FoundRHS) {
9689   switch (Pred) {
9690   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9691   case ICmpInst::ICMP_EQ:
9692   case ICmpInst::ICMP_NE:
9693     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9694       return true;
9695     break;
9696   case ICmpInst::ICMP_SLT:
9697   case ICmpInst::ICMP_SLE:
9698     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9699         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9700       return true;
9701     break;
9702   case ICmpInst::ICMP_SGT:
9703   case ICmpInst::ICMP_SGE:
9704     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9705         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9706       return true;
9707     break;
9708   case ICmpInst::ICMP_ULT:
9709   case ICmpInst::ICMP_ULE:
9710     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9711         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9712       return true;
9713     break;
9714   case ICmpInst::ICMP_UGT:
9715   case ICmpInst::ICMP_UGE:
9716     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9717         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9718       return true;
9719     break;
9720   }
9721
9722   // Maybe it can be proved via operations?
9723   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9724     return true;
9725
9726   return false;
9727 }
9728
9729 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9730                                                      const SCEV *LHS,
9731                                                      const SCEV *RHS,
9732                                                      const SCEV *FoundLHS,
9733                                                      const SCEV *FoundRHS) {
9734   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9735     // The restriction on `FoundRHS` be lifted easily -- it exists only to
9736     // reduce the compile time impact of this optimization.
9737     return false;
9738
9739   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
9740   if (!Addend)
9741     return false;
9742
9743   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9744
9745   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9746   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9747   ConstantRange FoundLHSRange =
9748       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9749
9750   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9751   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
9752
9753   // We can also compute the range of values for `LHS` that satisfy the
9754   // consequent, "`LHS` `Pred` `RHS`":
9755   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9756   ConstantRange SatisfyingLHSRange =
9757       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9758
9759   // The antecedent implies the consequent if every value of `LHS` that
9760   // satisfies the antecedent also satisfies the consequent.
9761   return SatisfyingLHSRange.contains(LHSRange);
9762 }
9763
9764 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9765                                          bool IsSigned, bool NoWrap) {
9766   assert(isKnownPositive(Stride) && "Positive stride expected!");
9767
9768   if (NoWrap) return false;
9769
9770   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9771   const SCEV *One = getOne(Stride->getType());
9772
9773   if (IsSigned) {
9774     APInt MaxRHS = getSignedRangeMax(RHS);
9775     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9776     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9777
9778     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9779     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9780   }
9781
9782   APInt MaxRHS = getUnsignedRangeMax(RHS);
9783   APInt MaxValue = APInt::getMaxValue(BitWidth);
9784   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9785
9786   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9787   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9788 }
9789
9790 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9791                                          bool IsSigned, bool NoWrap) {
9792   if (NoWrap) return false;
9793
9794   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9795   const SCEV *One = getOne(Stride->getType());
9796
9797   if (IsSigned) {
9798     APInt MinRHS = getSignedRangeMin(RHS);
9799     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9800     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9801
9802     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9803     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9804   }
9805
9806   APInt MinRHS = getUnsignedRangeMin(RHS);
9807   APInt MinValue = APInt::getMinValue(BitWidth);
9808   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9809
9810   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9811   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9812 }
9813
9814 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9815                                             bool Equality) {
9816   const SCEV *One = getOne(Step->getType());
9817   Delta = Equality ? getAddExpr(Delta, Step)
9818                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9819   return getUDivExpr(Delta, Step);
9820 }
9821
9822 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
9823                                                     const SCEV *Stride,
9824                                                     const SCEV *End,
9825                                                     unsigned BitWidth,
9826                                                     bool IsSigned) {
9827
9828   assert(!isKnownNonPositive(Stride) &&
9829          "Stride is expected strictly positive!");
9830   // Calculate the maximum backedge count based on the range of values
9831   // permitted by Start, End, and Stride.
9832   const SCEV *MaxBECount;
9833   APInt MinStart =
9834       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
9835
9836   APInt StrideForMaxBECount =
9837       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
9838
9839   // We already know that the stride is positive, so we paper over conservatism
9840   // in our range computation by forcing StrideForMaxBECount to be at least one.
9841   // In theory this is unnecessary, but we expect MaxBECount to be a
9842   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
9843   // is nothing to constant fold it to).
9844   APInt One(BitWidth, 1, IsSigned);
9845   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
9846
9847   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
9848                             : APInt::getMaxValue(BitWidth);
9849   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
9850
9851   // Although End can be a MAX expression we estimate MaxEnd considering only
9852   // the case End = RHS of the loop termination condition. This is safe because
9853   // in the other case (End - Start) is zero, leading to a zero maximum backedge
9854   // taken count.
9855   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
9856                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
9857
9858   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
9859                               getConstant(StrideForMaxBECount) /* Step */,
9860                               false /* Equality */);
9861
9862   return MaxBECount;
9863 }
9864
9865 ScalarEvolution::ExitLimit
9866 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9867                                   const Loop *L, bool IsSigned,
9868                                   bool ControlsExit, bool AllowPredicates) {
9869   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9870
9871   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9872   bool PredicatedIV = false;
9873
9874   if (!IV && AllowPredicates) {
9875     // Try to make this an AddRec using runtime tests, in the first X
9876     // iterations of this loop, where X is the SCEV expression found by the
9877     // algorithm below.
9878     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9879     PredicatedIV = true;
9880   }
9881
9882   // Avoid weird loops
9883   if (!IV || IV->getLoop() != L || !IV->isAffine())
9884     return getCouldNotCompute();
9885
9886   bool NoWrap = ControlsExit &&
9887                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9888
9889   const SCEV *Stride = IV->getStepRecurrence(*this);
9890
9891   bool PositiveStride = isKnownPositive(Stride);
9892
9893   // Avoid negative or zero stride values.
9894   if (!PositiveStride) {
9895     // We can compute the correct backedge taken count for loops with unknown
9896     // strides if we can prove that the loop is not an infinite loop with side
9897     // effects. Here's the loop structure we are trying to handle -
9898     //
9899     // i = start
9900     // do {
9901     //   A[i] = i;
9902     //   i += s;
9903     // } while (i < end);
9904     //
9905     // The backedge taken count for such loops is evaluated as -
9906     // (max(end, start + stride) - start - 1) /u stride
9907     //
9908     // The additional preconditions that we need to check to prove correctness
9909     // of the above formula is as follows -
9910     //
9911     // a) IV is either nuw or nsw depending upon signedness (indicated by the
9912     //    NoWrap flag).
9913     // b) loop is single exit with no side effects.
9914     //
9915     //
9916     // Precondition a) implies that if the stride is negative, this is a single
9917     // trip loop. The backedge taken count formula reduces to zero in this case.
9918     //
9919     // Precondition b) implies that the unknown stride cannot be zero otherwise
9920     // we have UB.
9921     //
9922     // The positive stride case is the same as isKnownPositive(Stride) returning
9923     // true (original behavior of the function).
9924     //
9925     // We want to make sure that the stride is truly unknown as there are edge
9926     // cases where ScalarEvolution propagates no wrap flags to the
9927     // post-increment/decrement IV even though the increment/decrement operation
9928     // itself is wrapping. The computed backedge taken count may be wrong in
9929     // such cases. This is prevented by checking that the stride is not known to
9930     // be either positive or non-positive. For example, no wrap flags are
9931     // propagated to the post-increment IV of this loop with a trip count of 2 -
9932     //
9933     // unsigned char i;
9934     // for(i=127; i<128; i+=129)
9935     //   A[i] = i;
9936     //
9937     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9938         !loopHasNoSideEffects(L))
9939       return getCouldNotCompute();
9940   } else if (!Stride->isOne() &&
9941              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9942     // Avoid proven overflow cases: this will ensure that the backedge taken
9943     // count will not generate any unsigned overflow. Relaxed no-overflow
9944     // conditions exploit NoWrapFlags, allowing to optimize in presence of
9945     // undefined behaviors like the case of C language.
9946     return getCouldNotCompute();
9947
9948   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9949                                       : ICmpInst::ICMP_ULT;
9950   const SCEV *Start = IV->getStart();
9951   const SCEV *End = RHS;
9952   // When the RHS is not invariant, we do not know the end bound of the loop and
9953   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
9954   // calculate the MaxBECount, given the start, stride and max value for the end
9955   // bound of the loop (RHS), and the fact that IV does not overflow (which is
9956   // checked above).
9957   if (!isLoopInvariant(RHS, L)) {
9958     const SCEV *MaxBECount = computeMaxBECountForLT(
9959         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
9960     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
9961                      false /*MaxOrZero*/, Predicates);
9962   }
9963   // If the backedge is taken at least once, then it will be taken
9964   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9965   // is the LHS value of the less-than comparison the first time it is evaluated
9966   // and End is the RHS.
9967   const SCEV *BECountIfBackedgeTaken =
9968     computeBECount(getMinusSCEV(End, Start), Stride, false);
9969   // If the loop entry is guarded by the result of the backedge test of the
9970   // first loop iteration, then we know the backedge will be taken at least
9971   // once and so the backedge taken count is as above. If not then we use the
9972   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9973   // as if the backedge is taken at least once max(End,Start) is End and so the
9974   // result is as above, and if not max(End,Start) is Start so we get a backedge
9975   // count of zero.
9976   const SCEV *BECount;
9977   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9978     BECount = BECountIfBackedgeTaken;
9979   else {
9980     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9981     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9982   }
9983
9984   const SCEV *MaxBECount;
9985   bool MaxOrZero = false;
9986   if (isa<SCEVConstant>(BECount))
9987     MaxBECount = BECount;
9988   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9989     // If we know exactly how many times the backedge will be taken if it's
9990     // taken at least once, then the backedge count will either be that or
9991     // zero.
9992     MaxBECount = BECountIfBackedgeTaken;
9993     MaxOrZero = true;
9994   } else {
9995     MaxBECount = computeMaxBECountForLT(
9996         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
9997   }
9998
9999   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10000       !isa<SCEVCouldNotCompute>(BECount))
10001     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10002
10003   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10004 }
10005
10006 ScalarEvolution::ExitLimit
10007 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10008                                      const Loop *L, bool IsSigned,
10009                                      bool ControlsExit, bool AllowPredicates) {
10010   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10011   // We handle only IV > Invariant
10012   if (!isLoopInvariant(RHS, L))
10013     return getCouldNotCompute();
10014
10015   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10016   if (!IV && AllowPredicates)
10017     // Try to make this an AddRec using runtime tests, in the first X
10018     // iterations of this loop, where X is the SCEV expression found by the
10019     // algorithm below.
10020     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10021
10022   // Avoid weird loops
10023   if (!IV || IV->getLoop() != L || !IV->isAffine())
10024     return getCouldNotCompute();
10025
10026   bool NoWrap = ControlsExit &&
10027                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10028
10029   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10030
10031   // Avoid negative or zero stride values
10032   if (!isKnownPositive(Stride))
10033     return getCouldNotCompute();
10034
10035   // Avoid proven overflow cases: this will ensure that the backedge taken count
10036   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10037   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10038   // behaviors like the case of C language.
10039   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10040     return getCouldNotCompute();
10041
10042   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10043                                       : ICmpInst::ICMP_UGT;
10044
10045   const SCEV *Start = IV->getStart();
10046   const SCEV *End = RHS;
10047   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10048     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10049
10050   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10051
10052   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10053                             : getUnsignedRangeMax(Start);
10054
10055   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10056                              : getUnsignedRangeMin(Stride);
10057
10058   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10059   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10060                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10061
10062   // Although End can be a MIN expression we estimate MinEnd considering only
10063   // the case End = RHS. This is safe because in the other case (Start - End)
10064   // is zero, leading to a zero maximum backedge taken count.
10065   APInt MinEnd =
10066     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10067              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10068
10069
10070   const SCEV *MaxBECount = getCouldNotCompute();
10071   if (isa<SCEVConstant>(BECount))
10072     MaxBECount = BECount;
10073   else
10074     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10075                                 getConstant(MinStride), false);
10076
10077   if (isa<SCEVCouldNotCompute>(MaxBECount))
10078     MaxBECount = BECount;
10079
10080   return ExitLimit(BECount, MaxBECount, false, Predicates);
10081 }
10082
10083 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10084                                                     ScalarEvolution &SE) const {
10085   if (Range.isFullSet())  // Infinite loop.
10086     return SE.getCouldNotCompute();
10087
10088   // If the start is a non-zero constant, shift the range to simplify things.
10089   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10090     if (!SC->getValue()->isZero()) {
10091       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10092       Operands[0] = SE.getZero(SC->getType());
10093       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10094                                              getNoWrapFlags(FlagNW));
10095       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10096         return ShiftedAddRec->getNumIterationsInRange(
10097             Range.subtract(SC->getAPInt()), SE);
10098       // This is strange and shouldn't happen.
10099       return SE.getCouldNotCompute();
10100     }
10101
10102   // The only time we can solve this is when we have all constant indices.
10103   // Otherwise, we cannot determine the overflow conditions.
10104   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10105     return SE.getCouldNotCompute();
10106
10107   // Okay at this point we know that all elements of the chrec are constants and
10108   // that the start element is zero.
10109
10110   // First check to see if the range contains zero.  If not, the first
10111   // iteration exits.
10112   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10113   if (!Range.contains(APInt(BitWidth, 0)))
10114     return SE.getZero(getType());
10115
10116   if (isAffine()) {
10117     // If this is an affine expression then we have this situation:
10118     //   Solve {0,+,A} in Range  ===  Ax in Range
10119
10120     // We know that zero is in the range.  If A is positive then we know that
10121     // the upper value of the range must be the first possible exit value.
10122     // If A is negative then the lower of the range is the last possible loop
10123     // value.  Also note that we already checked for a full range.
10124     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10125     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10126
10127     // The exit value should be (End+A)/A.
10128     APInt ExitVal = (End + A).udiv(A);
10129     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10130
10131     // Evaluate at the exit value.  If we really did fall out of the valid
10132     // range, then we computed our trip count, otherwise wrap around or other
10133     // things must have happened.
10134     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10135     if (Range.contains(Val->getValue()))
10136       return SE.getCouldNotCompute();  // Something strange happened
10137
10138     // Ensure that the previous value is in the range.  This is a sanity check.
10139     assert(Range.contains(
10140            EvaluateConstantChrecAtConstant(this,
10141            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10142            "Linear scev computation is off in a bad way!");
10143     return SE.getConstant(ExitValue);
10144   } else if (isQuadratic()) {
10145     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10146     // quadratic equation to solve it.  To do this, we must frame our problem in
10147     // terms of figuring out when zero is crossed, instead of when
10148     // Range.getUpper() is crossed.
10149     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10150     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10151     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10152
10153     // Next, solve the constructed addrec
10154     if (auto Roots =
10155             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10156       const SCEVConstant *R1 = Roots->first;
10157       const SCEVConstant *R2 = Roots->second;
10158       // Pick the smallest positive root value.
10159       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10160               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10161         if (!CB->getZExtValue())
10162           std::swap(R1, R2); // R1 is the minimum root now.
10163
10164         // Make sure the root is not off by one.  The returned iteration should
10165         // not be in the range, but the previous one should be.  When solving
10166         // for "X*X < 5", for example, we should not return a root of 2.
10167         ConstantInt *R1Val =
10168             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10169         if (Range.contains(R1Val->getValue())) {
10170           // The next iteration must be out of the range...
10171           ConstantInt *NextVal =
10172               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10173
10174           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10175           if (!Range.contains(R1Val->getValue()))
10176             return SE.getConstant(NextVal);
10177           return SE.getCouldNotCompute(); // Something strange happened
10178         }
10179
10180         // If R1 was not in the range, then it is a good return value.  Make
10181         // sure that R1-1 WAS in the range though, just in case.
10182         ConstantInt *NextVal =
10183             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10184         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10185         if (Range.contains(R1Val->getValue()))
10186           return R1;
10187         return SE.getCouldNotCompute(); // Something strange happened
10188       }
10189     }
10190   }
10191
10192   return SE.getCouldNotCompute();
10193 }
10194
10195 // Return true when S contains at least an undef value.
10196 static inline bool containsUndefs(const SCEV *S) {
10197   return SCEVExprContains(S, [](const SCEV *S) {
10198     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10199       return isa<UndefValue>(SU->getValue());
10200     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10201       return isa<UndefValue>(SC->getValue());
10202     return false;
10203   });
10204 }
10205
10206 namespace {
10207
10208 // Collect all steps of SCEV expressions.
10209 struct SCEVCollectStrides {
10210   ScalarEvolution &SE;
10211   SmallVectorImpl<const SCEV *> &Strides;
10212
10213   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10214       : SE(SE), Strides(S) {}
10215
10216   bool follow(const SCEV *S) {
10217     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10218       Strides.push_back(AR->getStepRecurrence(SE));
10219     return true;
10220   }
10221
10222   bool isDone() const { return false; }
10223 };
10224
10225 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10226 struct SCEVCollectTerms {
10227   SmallVectorImpl<const SCEV *> &Terms;
10228
10229   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10230
10231   bool follow(const SCEV *S) {
10232     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10233         isa<SCEVSignExtendExpr>(S)) {
10234       if (!containsUndefs(S))
10235         Terms.push_back(S);
10236
10237       // Stop recursion: once we collected a term, do not walk its operands.
10238       return false;
10239     }
10240
10241     // Keep looking.
10242     return true;
10243   }
10244
10245   bool isDone() const { return false; }
10246 };
10247
10248 // Check if a SCEV contains an AddRecExpr.
10249 struct SCEVHasAddRec {
10250   bool &ContainsAddRec;
10251
10252   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10253     ContainsAddRec = false;
10254   }
10255
10256   bool follow(const SCEV *S) {
10257     if (isa<SCEVAddRecExpr>(S)) {
10258       ContainsAddRec = true;
10259
10260       // Stop recursion: once we collected a term, do not walk its operands.
10261       return false;
10262     }
10263
10264     // Keep looking.
10265     return true;
10266   }
10267
10268   bool isDone() const { return false; }
10269 };
10270
10271 // Find factors that are multiplied with an expression that (possibly as a
10272 // subexpression) contains an AddRecExpr. In the expression:
10273 //
10274 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10275 //
10276 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10277 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10278 // parameters as they form a product with an induction variable.
10279 //
10280 // This collector expects all array size parameters to be in the same MulExpr.
10281 // It might be necessary to later add support for collecting parameters that are
10282 // spread over different nested MulExpr.
10283 struct SCEVCollectAddRecMultiplies {
10284   SmallVectorImpl<const SCEV *> &Terms;
10285   ScalarEvolution &SE;
10286
10287   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10288       : Terms(T), SE(SE) {}
10289
10290   bool follow(const SCEV *S) {
10291     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10292       bool HasAddRec = false;
10293       SmallVector<const SCEV *, 0> Operands;
10294       for (auto Op : Mul->operands()) {
10295         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10296         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10297           Operands.push_back(Op);
10298         } else if (Unknown) {
10299           HasAddRec = true;
10300         } else {
10301           bool ContainsAddRec;
10302           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10303           visitAll(Op, ContiansAddRec);
10304           HasAddRec |= ContainsAddRec;
10305         }
10306       }
10307       if (Operands.size() == 0)
10308         return true;
10309
10310       if (!HasAddRec)
10311         return false;
10312
10313       Terms.push_back(SE.getMulExpr(Operands));
10314       // Stop recursion: once we collected a term, do not walk its operands.
10315       return false;
10316     }
10317
10318     // Keep looking.
10319     return true;
10320   }
10321
10322   bool isDone() const { return false; }
10323 };
10324
10325 } // end anonymous namespace
10326
10327 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10328 /// two places:
10329 ///   1) The strides of AddRec expressions.
10330 ///   2) Unknowns that are multiplied with AddRec expressions.
10331 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10332     SmallVectorImpl<const SCEV *> &Terms) {
10333   SmallVector<const SCEV *, 4> Strides;
10334   SCEVCollectStrides StrideCollector(*this, Strides);
10335   visitAll(Expr, StrideCollector);
10336
10337   DEBUG({
10338       dbgs() << "Strides:\n";
10339       for (const SCEV *S : Strides)
10340         dbgs() << *S << "\n";
10341     });
10342
10343   for (const SCEV *S : Strides) {
10344     SCEVCollectTerms TermCollector(Terms);
10345     visitAll(S, TermCollector);
10346   }
10347
10348   DEBUG({
10349       dbgs() << "Terms:\n";
10350       for (const SCEV *T : Terms)
10351         dbgs() << *T << "\n";
10352     });
10353
10354   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10355   visitAll(Expr, MulCollector);
10356 }
10357
10358 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10359                                    SmallVectorImpl<const SCEV *> &Terms,
10360                                    SmallVectorImpl<const SCEV *> &Sizes) {
10361   int Last = Terms.size() - 1;
10362   const SCEV *Step = Terms[Last];
10363
10364   // End of recursion.
10365   if (Last == 0) {
10366     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10367       SmallVector<const SCEV *, 2> Qs;
10368       for (const SCEV *Op : M->operands())
10369         if (!isa<SCEVConstant>(Op))
10370           Qs.push_back(Op);
10371
10372       Step = SE.getMulExpr(Qs);
10373     }
10374
10375     Sizes.push_back(Step);
10376     return true;
10377   }
10378
10379   for (const SCEV *&Term : Terms) {
10380     // Normalize the terms before the next call to findArrayDimensionsRec.
10381     const SCEV *Q, *R;
10382     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10383
10384     // Bail out when GCD does not evenly divide one of the terms.
10385     if (!R->isZero())
10386       return false;
10387
10388     Term = Q;
10389   }
10390
10391   // Remove all SCEVConstants.
10392   Terms.erase(
10393       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10394       Terms.end());
10395
10396   if (Terms.size() > 0)
10397     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10398       return false;
10399
10400   Sizes.push_back(Step);
10401   return true;
10402 }
10403
10404 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10405 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10406   for (const SCEV *T : Terms)
10407     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10408       return true;
10409   return false;
10410 }
10411
10412 // Return the number of product terms in S.
10413 static inline int numberOfTerms(const SCEV *S) {
10414   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10415     return Expr->getNumOperands();
10416   return 1;
10417 }
10418
10419 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10420   if (isa<SCEVConstant>(T))
10421     return nullptr;
10422
10423   if (isa<SCEVUnknown>(T))
10424     return T;
10425
10426   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10427     SmallVector<const SCEV *, 2> Factors;
10428     for (const SCEV *Op : M->operands())
10429       if (!isa<SCEVConstant>(Op))
10430         Factors.push_back(Op);
10431
10432     return SE.getMulExpr(Factors);
10433   }
10434
10435   return T;
10436 }
10437
10438 /// Return the size of an element read or written by Inst.
10439 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10440   Type *Ty;
10441   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10442     Ty = Store->getValueOperand()->getType();
10443   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10444     Ty = Load->getType();
10445   else
10446     return nullptr;
10447
10448   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10449   return getSizeOfExpr(ETy, Ty);
10450 }
10451
10452 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10453                                           SmallVectorImpl<const SCEV *> &Sizes,
10454                                           const SCEV *ElementSize) {
10455   if (Terms.size() < 1 || !ElementSize)
10456     return;
10457
10458   // Early return when Terms do not contain parameters: we do not delinearize
10459   // non parametric SCEVs.
10460   if (!containsParameters(Terms))
10461     return;
10462
10463   DEBUG({
10464       dbgs() << "Terms:\n";
10465       for (const SCEV *T : Terms)
10466         dbgs() << *T << "\n";
10467     });
10468
10469   // Remove duplicates.
10470   array_pod_sort(Terms.begin(), Terms.end());
10471   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10472
10473   // Put larger terms first.
10474   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10475     return numberOfTerms(LHS) > numberOfTerms(RHS);
10476   });
10477
10478   // Try to divide all terms by the element size. If term is not divisible by
10479   // element size, proceed with the original term.
10480   for (const SCEV *&Term : Terms) {
10481     const SCEV *Q, *R;
10482     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10483     if (!Q->isZero())
10484       Term = Q;
10485   }
10486
10487   SmallVector<const SCEV *, 4> NewTerms;
10488
10489   // Remove constant factors.
10490   for (const SCEV *T : Terms)
10491     if (const SCEV *NewT = removeConstantFactors(*this, T))
10492       NewTerms.push_back(NewT);
10493
10494   DEBUG({
10495       dbgs() << "Terms after sorting:\n";
10496       for (const SCEV *T : NewTerms)
10497         dbgs() << *T << "\n";
10498     });
10499
10500   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10501     Sizes.clear();
10502     return;
10503   }
10504
10505   // The last element to be pushed into Sizes is the size of an element.
10506   Sizes.push_back(ElementSize);
10507
10508   DEBUG({
10509       dbgs() << "Sizes:\n";
10510       for (const SCEV *S : Sizes)
10511         dbgs() << *S << "\n";
10512     });
10513 }
10514
10515 void ScalarEvolution::computeAccessFunctions(
10516     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10517     SmallVectorImpl<const SCEV *> &Sizes) {
10518   // Early exit in case this SCEV is not an affine multivariate function.
10519   if (Sizes.empty())
10520     return;
10521
10522   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10523     if (!AR->isAffine())
10524       return;
10525
10526   const SCEV *Res = Expr;
10527   int Last = Sizes.size() - 1;
10528   for (int i = Last; i >= 0; i--) {
10529     const SCEV *Q, *R;
10530     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10531
10532     DEBUG({
10533         dbgs() << "Res: " << *Res << "\n";
10534         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10535         dbgs() << "Res divided by Sizes[i]:\n";
10536         dbgs() << "Quotient: " << *Q << "\n";
10537         dbgs() << "Remainder: " << *R << "\n";
10538       });
10539
10540     Res = Q;
10541
10542     // Do not record the last subscript corresponding to the size of elements in
10543     // the array.
10544     if (i == Last) {
10545
10546       // Bail out if the remainder is too complex.
10547       if (isa<SCEVAddRecExpr>(R)) {
10548         Subscripts.clear();
10549         Sizes.clear();
10550         return;
10551       }
10552
10553       continue;
10554     }
10555
10556     // Record the access function for the current subscript.
10557     Subscripts.push_back(R);
10558   }
10559
10560   // Also push in last position the remainder of the last division: it will be
10561   // the access function of the innermost dimension.
10562   Subscripts.push_back(Res);
10563
10564   std::reverse(Subscripts.begin(), Subscripts.end());
10565
10566   DEBUG({
10567       dbgs() << "Subscripts:\n";
10568       for (const SCEV *S : Subscripts)
10569         dbgs() << *S << "\n";
10570     });
10571 }
10572
10573 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10574 /// sizes of an array access. Returns the remainder of the delinearization that
10575 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10576 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10577 /// expressions in the stride and base of a SCEV corresponding to the
10578 /// computation of a GCD (greatest common divisor) of base and stride.  When
10579 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10580 ///
10581 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10582 ///
10583 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10584 ///
10585 ///    for (long i = 0; i < n; i++)
10586 ///      for (long j = 0; j < m; j++)
10587 ///        for (long k = 0; k < o; k++)
10588 ///          A[i][j][k] = 1.0;
10589 ///  }
10590 ///
10591 /// the delinearization input is the following AddRec SCEV:
10592 ///
10593 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10594 ///
10595 /// From this SCEV, we are able to say that the base offset of the access is %A
10596 /// because it appears as an offset that does not divide any of the strides in
10597 /// the loops:
10598 ///
10599 ///  CHECK: Base offset: %A
10600 ///
10601 /// and then SCEV->delinearize determines the size of some of the dimensions of
10602 /// the array as these are the multiples by which the strides are happening:
10603 ///
10604 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10605 ///
10606 /// Note that the outermost dimension remains of UnknownSize because there are
10607 /// no strides that would help identifying the size of the last dimension: when
10608 /// the array has been statically allocated, one could compute the size of that
10609 /// dimension by dividing the overall size of the array by the size of the known
10610 /// dimensions: %m * %o * 8.
10611 ///
10612 /// Finally delinearize provides the access functions for the array reference
10613 /// that does correspond to A[i][j][k] of the above C testcase:
10614 ///
10615 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10616 ///
10617 /// The testcases are checking the output of a function pass:
10618 /// DelinearizationPass that walks through all loads and stores of a function
10619 /// asking for the SCEV of the memory access with respect to all enclosing
10620 /// loops, calling SCEV->delinearize on that and printing the results.
10621 void ScalarEvolution::delinearize(const SCEV *Expr,
10622                                  SmallVectorImpl<const SCEV *> &Subscripts,
10623                                  SmallVectorImpl<const SCEV *> &Sizes,
10624                                  const SCEV *ElementSize) {
10625   // First step: collect parametric terms.
10626   SmallVector<const SCEV *, 4> Terms;
10627   collectParametricTerms(Expr, Terms);
10628
10629   if (Terms.empty())
10630     return;
10631
10632   // Second step: find subscript sizes.
10633   findArrayDimensions(Terms, Sizes, ElementSize);
10634
10635   if (Sizes.empty())
10636     return;
10637
10638   // Third step: compute the access functions for each subscript.
10639   computeAccessFunctions(Expr, Subscripts, Sizes);
10640
10641   if (Subscripts.empty())
10642     return;
10643
10644   DEBUG({
10645       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10646       dbgs() << "ArrayDecl[UnknownSize]";
10647       for (const SCEV *S : Sizes)
10648         dbgs() << "[" << *S << "]";
10649
10650       dbgs() << "\nArrayRef";
10651       for (const SCEV *S : Subscripts)
10652         dbgs() << "[" << *S << "]";
10653       dbgs() << "\n";
10654     });
10655 }
10656
10657 //===----------------------------------------------------------------------===//
10658 //                   SCEVCallbackVH Class Implementation
10659 //===----------------------------------------------------------------------===//
10660
10661 void ScalarEvolution::SCEVCallbackVH::deleted() {
10662   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10663   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10664     SE->ConstantEvolutionLoopExitValue.erase(PN);
10665   SE->eraseValueFromMap(getValPtr());
10666   // this now dangles!
10667 }
10668
10669 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10670   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10671
10672   // Forget all the expressions associated with users of the old value,
10673   // so that future queries will recompute the expressions using the new
10674   // value.
10675   Value *Old = getValPtr();
10676   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10677   SmallPtrSet<User *, 8> Visited;
10678   while (!Worklist.empty()) {
10679     User *U = Worklist.pop_back_val();
10680     // Deleting the Old value will cause this to dangle. Postpone
10681     // that until everything else is done.
10682     if (U == Old)
10683       continue;
10684     if (!Visited.insert(U).second)
10685       continue;
10686     if (PHINode *PN = dyn_cast<PHINode>(U))
10687       SE->ConstantEvolutionLoopExitValue.erase(PN);
10688     SE->eraseValueFromMap(U);
10689     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10690   }
10691   // Delete the Old value.
10692   if (PHINode *PN = dyn_cast<PHINode>(Old))
10693     SE->ConstantEvolutionLoopExitValue.erase(PN);
10694   SE->eraseValueFromMap(Old);
10695   // this now dangles!
10696 }
10697
10698 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10699   : CallbackVH(V), SE(se) {}
10700
10701 //===----------------------------------------------------------------------===//
10702 //                   ScalarEvolution Class Implementation
10703 //===----------------------------------------------------------------------===//
10704
10705 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
10706                                  AssumptionCache &AC, DominatorTree &DT,
10707                                  LoopInfo &LI)
10708     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10709       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
10710       LoopDispositions(64), BlockDispositions(64) {
10711   // To use guards for proving predicates, we need to scan every instruction in
10712   // relevant basic blocks, and not just terminators.  Doing this is a waste of
10713   // time if the IR does not actually contain any calls to
10714   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10715   //
10716   // This pessimizes the case where a pass that preserves ScalarEvolution wants
10717   // to _add_ guards to the module when there weren't any before, and wants
10718   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
10719   // efficient in lieu of being smart in that rather obscure case.
10720
10721   auto *GuardDecl = F.getParent()->getFunction(
10722       Intrinsic::getName(Intrinsic::experimental_guard));
10723   HasGuards = GuardDecl && !GuardDecl->use_empty();
10724 }
10725
10726 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
10727     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10728       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10729       ValueExprMap(std::move(Arg.ValueExprMap)),
10730       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10731       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10732       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10733       PredicatedBackedgeTakenCounts(
10734           std::move(Arg.PredicatedBackedgeTakenCounts)),
10735       ConstantEvolutionLoopExitValue(
10736           std::move(Arg.ConstantEvolutionLoopExitValue)),
10737       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10738       LoopDispositions(std::move(Arg.LoopDispositions)),
10739       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10740       BlockDispositions(std::move(Arg.BlockDispositions)),
10741       UnsignedRanges(std::move(Arg.UnsignedRanges)),
10742       SignedRanges(std::move(Arg.SignedRanges)),
10743       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10744       UniquePreds(std::move(Arg.UniquePreds)),
10745       SCEVAllocator(std::move(Arg.SCEVAllocator)),
10746       LoopUsers(std::move(Arg.LoopUsers)),
10747       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10748       FirstUnknown(Arg.FirstUnknown) {
10749   Arg.FirstUnknown = nullptr;
10750 }
10751
10752 ScalarEvolution::~ScalarEvolution() {
10753   // Iterate through all the SCEVUnknown instances and call their
10754   // destructors, so that they release their references to their values.
10755   for (SCEVUnknown *U = FirstUnknown; U;) {
10756     SCEVUnknown *Tmp = U;
10757     U = U->Next;
10758     Tmp->~SCEVUnknown();
10759   }
10760   FirstUnknown = nullptr;
10761
10762   ExprValueMap.clear();
10763   ValueExprMap.clear();
10764   HasRecMap.clear();
10765
10766   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10767   // that a loop had multiple computable exits.
10768   for (auto &BTCI : BackedgeTakenCounts)
10769     BTCI.second.clear();
10770   for (auto &BTCI : PredicatedBackedgeTakenCounts)
10771     BTCI.second.clear();
10772
10773   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
10774   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
10775   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
10776 }
10777
10778 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
10779   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
10780 }
10781
10782 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10783                           const Loop *L) {
10784   // Print all inner loops first
10785   for (Loop *I : *L)
10786     PrintLoopInfo(OS, SE, I);
10787
10788   OS << "Loop ";
10789   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10790   OS << ": ";
10791
10792   SmallVector<BasicBlock *, 8> ExitBlocks;
10793   L->getExitBlocks(ExitBlocks);
10794   if (ExitBlocks.size() != 1)
10795     OS << "<multiple exits> ";
10796
10797   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10798     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10799   } else {
10800     OS << "Unpredictable backedge-taken count. ";
10801   }
10802
10803   OS << "\n"
10804         "Loop ";
10805   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10806   OS << ": ";
10807
10808   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10809     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10810     if (SE->isBackedgeTakenCountMaxOrZero(L))
10811       OS << ", actual taken count either this or zero.";
10812   } else {
10813     OS << "Unpredictable max backedge-taken count. ";
10814   }
10815
10816   OS << "\n"
10817         "Loop ";
10818   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10819   OS << ": ";
10820
10821   SCEVUnionPredicate Pred;
10822   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10823   if (!isa<SCEVCouldNotCompute>(PBT)) {
10824     OS << "Predicated backedge-taken count is " << *PBT << "\n";
10825     OS << " Predicates:\n";
10826     Pred.print(OS, 4);
10827   } else {
10828     OS << "Unpredictable predicated backedge-taken count. ";
10829   }
10830   OS << "\n";
10831
10832   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10833     OS << "Loop ";
10834     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10835     OS << ": ";
10836     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10837   }
10838 }
10839
10840 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10841   switch (LD) {
10842   case ScalarEvolution::LoopVariant:
10843     return "Variant";
10844   case ScalarEvolution::LoopInvariant:
10845     return "Invariant";
10846   case ScalarEvolution::LoopComputable:
10847     return "Computable";
10848   }
10849   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10850 }
10851
10852 void ScalarEvolution::print(raw_ostream &OS) const {
10853   // ScalarEvolution's implementation of the print method is to print
10854   // out SCEV values of all instructions that are interesting. Doing
10855   // this potentially causes it to create new SCEV objects though,
10856   // which technically conflicts with the const qualifier. This isn't
10857   // observable from outside the class though, so casting away the
10858   // const isn't dangerous.
10859   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10860
10861   OS << "Classifying expressions for: ";
10862   F.printAsOperand(OS, /*PrintType=*/false);
10863   OS << "\n";
10864   for (Instruction &I : instructions(F))
10865     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10866       OS << I << '\n';
10867       OS << "  -->  ";
10868       const SCEV *SV = SE.getSCEV(&I);
10869       SV->print(OS);
10870       if (!isa<SCEVCouldNotCompute>(SV)) {
10871         OS << " U: ";
10872         SE.getUnsignedRange(SV).print(OS);
10873         OS << " S: ";
10874         SE.getSignedRange(SV).print(OS);
10875       }
10876
10877       const Loop *L = LI.getLoopFor(I.getParent());
10878
10879       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10880       if (AtUse != SV) {
10881         OS << "  -->  ";
10882         AtUse->print(OS);
10883         if (!isa<SCEVCouldNotCompute>(AtUse)) {
10884           OS << " U: ";
10885           SE.getUnsignedRange(AtUse).print(OS);
10886           OS << " S: ";
10887           SE.getSignedRange(AtUse).print(OS);
10888         }
10889       }
10890
10891       if (L) {
10892         OS << "\t\t" "Exits: ";
10893         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10894         if (!SE.isLoopInvariant(ExitValue, L)) {
10895           OS << "<<Unknown>>";
10896         } else {
10897           OS << *ExitValue;
10898         }
10899
10900         bool First = true;
10901         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10902           if (First) {
10903             OS << "\t\t" "LoopDispositions: { ";
10904             First = false;
10905           } else {
10906             OS << ", ";
10907           }
10908
10909           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10910           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10911         }
10912
10913         for (auto *InnerL : depth_first(L)) {
10914           if (InnerL == L)
10915             continue;
10916           if (First) {
10917             OS << "\t\t" "LoopDispositions: { ";
10918             First = false;
10919           } else {
10920             OS << ", ";
10921           }
10922
10923           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10924           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10925         }
10926
10927         OS << " }";
10928       }
10929
10930       OS << "\n";
10931     }
10932
10933   OS << "Determining loop execution counts for: ";
10934   F.printAsOperand(OS, /*PrintType=*/false);
10935   OS << "\n";
10936   for (Loop *I : LI)
10937     PrintLoopInfo(OS, &SE, I);
10938 }
10939
10940 ScalarEvolution::LoopDisposition
10941 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10942   auto &Values = LoopDispositions[S];
10943   for (auto &V : Values) {
10944     if (V.getPointer() == L)
10945       return V.getInt();
10946   }
10947   Values.emplace_back(L, LoopVariant);
10948   LoopDisposition D = computeLoopDisposition(S, L);
10949   auto &Values2 = LoopDispositions[S];
10950   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10951     if (V.getPointer() == L) {
10952       V.setInt(D);
10953       break;
10954     }
10955   }
10956   return D;
10957 }
10958
10959 ScalarEvolution::LoopDisposition
10960 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10961   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10962   case scConstant:
10963     return LoopInvariant;
10964   case scTruncate:
10965   case scZeroExtend:
10966   case scSignExtend:
10967     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10968   case scAddRecExpr: {
10969     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10970
10971     // If L is the addrec's loop, it's computable.
10972     if (AR->getLoop() == L)
10973       return LoopComputable;
10974
10975     // Add recurrences are never invariant in the function-body (null loop).
10976     if (!L)
10977       return LoopVariant;
10978
10979     // Everything that is not defined at loop entry is variant.
10980     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
10981       return LoopVariant;
10982     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
10983            " dominate the contained loop's header?");
10984
10985     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10986     if (AR->getLoop()->contains(L))
10987       return LoopInvariant;
10988
10989     // This recurrence is variant w.r.t. L if any of its operands
10990     // are variant.
10991     for (auto *Op : AR->operands())
10992       if (!isLoopInvariant(Op, L))
10993         return LoopVariant;
10994
10995     // Otherwise it's loop-invariant.
10996     return LoopInvariant;
10997   }
10998   case scAddExpr:
10999   case scMulExpr:
11000   case scUMaxExpr:
11001   case scSMaxExpr: {
11002     bool HasVarying = false;
11003     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11004       LoopDisposition D = getLoopDisposition(Op, L);
11005       if (D == LoopVariant)
11006         return LoopVariant;
11007       if (D == LoopComputable)
11008         HasVarying = true;
11009     }
11010     return HasVarying ? LoopComputable : LoopInvariant;
11011   }
11012   case scUDivExpr: {
11013     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11014     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11015     if (LD == LoopVariant)
11016       return LoopVariant;
11017     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11018     if (RD == LoopVariant)
11019       return LoopVariant;
11020     return (LD == LoopInvariant && RD == LoopInvariant) ?
11021            LoopInvariant : LoopComputable;
11022   }
11023   case scUnknown:
11024     // All non-instruction values are loop invariant.  All instructions are loop
11025     // invariant if they are not contained in the specified loop.
11026     // Instructions are never considered invariant in the function body
11027     // (null loop) because they are defined within the "loop".
11028     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11029       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11030     return LoopInvariant;
11031   case scCouldNotCompute:
11032     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11033   }
11034   llvm_unreachable("Unknown SCEV kind!");
11035 }
11036
11037 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11038   return getLoopDisposition(S, L) == LoopInvariant;
11039 }
11040
11041 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11042   return getLoopDisposition(S, L) == LoopComputable;
11043 }
11044
11045 ScalarEvolution::BlockDisposition
11046 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11047   auto &Values = BlockDispositions[S];
11048   for (auto &V : Values) {
11049     if (V.getPointer() == BB)
11050       return V.getInt();
11051   }
11052   Values.emplace_back(BB, DoesNotDominateBlock);
11053   BlockDisposition D = computeBlockDisposition(S, BB);
11054   auto &Values2 = BlockDispositions[S];
11055   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11056     if (V.getPointer() == BB) {
11057       V.setInt(D);
11058       break;
11059     }
11060   }
11061   return D;
11062 }
11063
11064 ScalarEvolution::BlockDisposition
11065 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11066   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11067   case scConstant:
11068     return ProperlyDominatesBlock;
11069   case scTruncate:
11070   case scZeroExtend:
11071   case scSignExtend:
11072     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11073   case scAddRecExpr: {
11074     // This uses a "dominates" query instead of "properly dominates" query
11075     // to test for proper dominance too, because the instruction which
11076     // produces the addrec's value is a PHI, and a PHI effectively properly
11077     // dominates its entire containing block.
11078     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11079     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11080       return DoesNotDominateBlock;
11081
11082     // Fall through into SCEVNAryExpr handling.
11083     LLVM_FALLTHROUGH;
11084   }
11085   case scAddExpr:
11086   case scMulExpr:
11087   case scUMaxExpr:
11088   case scSMaxExpr: {
11089     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11090     bool Proper = true;
11091     for (const SCEV *NAryOp : NAry->operands()) {
11092       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11093       if (D == DoesNotDominateBlock)
11094         return DoesNotDominateBlock;
11095       if (D == DominatesBlock)
11096         Proper = false;
11097     }
11098     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11099   }
11100   case scUDivExpr: {
11101     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11102     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11103     BlockDisposition LD = getBlockDisposition(LHS, BB);
11104     if (LD == DoesNotDominateBlock)
11105       return DoesNotDominateBlock;
11106     BlockDisposition RD = getBlockDisposition(RHS, BB);
11107     if (RD == DoesNotDominateBlock)
11108       return DoesNotDominateBlock;
11109     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11110       ProperlyDominatesBlock : DominatesBlock;
11111   }
11112   case scUnknown:
11113     if (Instruction *I =
11114           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11115       if (I->getParent() == BB)
11116         return DominatesBlock;
11117       if (DT.properlyDominates(I->getParent(), BB))
11118         return ProperlyDominatesBlock;
11119       return DoesNotDominateBlock;
11120     }
11121     return ProperlyDominatesBlock;
11122   case scCouldNotCompute:
11123     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11124   }
11125   llvm_unreachable("Unknown SCEV kind!");
11126 }
11127
11128 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11129   return getBlockDisposition(S, BB) >= DominatesBlock;
11130 }
11131
11132 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11133   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11134 }
11135
11136 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11137   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11138 }
11139
11140 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11141   auto IsS = [&](const SCEV *X) { return S == X; };
11142   auto ContainsS = [&](const SCEV *X) {
11143     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11144   };
11145   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11146 }
11147
11148 void
11149 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11150   ValuesAtScopes.erase(S);
11151   LoopDispositions.erase(S);
11152   BlockDispositions.erase(S);
11153   UnsignedRanges.erase(S);
11154   SignedRanges.erase(S);
11155   ExprValueMap.erase(S);
11156   HasRecMap.erase(S);
11157   MinTrailingZerosCache.erase(S);
11158
11159   for (auto I = PredicatedSCEVRewrites.begin();
11160        I != PredicatedSCEVRewrites.end();) {
11161     std::pair<const SCEV *, const Loop *> Entry = I->first;
11162     if (Entry.first == S)
11163       PredicatedSCEVRewrites.erase(I++);
11164     else
11165       ++I;
11166   }
11167
11168   auto RemoveSCEVFromBackedgeMap =
11169       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11170         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11171           BackedgeTakenInfo &BEInfo = I->second;
11172           if (BEInfo.hasOperand(S, this)) {
11173             BEInfo.clear();
11174             Map.erase(I++);
11175           } else
11176             ++I;
11177         }
11178       };
11179
11180   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11181   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11182 }
11183
11184 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11185   struct FindUsedLoops {
11186     SmallPtrSet<const Loop *, 8> LoopsUsed;
11187     bool follow(const SCEV *S) {
11188       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11189         LoopsUsed.insert(AR->getLoop());
11190       return true;
11191     }
11192
11193     bool isDone() const { return false; }
11194   };
11195
11196   FindUsedLoops F;
11197   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11198
11199   for (auto *L : F.LoopsUsed)
11200     LoopUsers[L].push_back(S);
11201 }
11202
11203 void ScalarEvolution::verify() const {
11204   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11205   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11206
11207   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11208
11209   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11210   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11211     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11212
11213     const SCEV *visitConstant(const SCEVConstant *Constant) {
11214       return SE.getConstant(Constant->getAPInt());
11215     }
11216
11217     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11218       return SE.getUnknown(Expr->getValue());
11219     }
11220
11221     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11222       return SE.getCouldNotCompute();
11223     }
11224   };
11225
11226   SCEVMapper SCM(SE2);
11227
11228   while (!LoopStack.empty()) {
11229     auto *L = LoopStack.pop_back_val();
11230     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11231
11232     auto *CurBECount = SCM.visit(
11233         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11234     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11235
11236     if (CurBECount == SE2.getCouldNotCompute() ||
11237         NewBECount == SE2.getCouldNotCompute()) {
11238       // NB! This situation is legal, but is very suspicious -- whatever pass
11239       // change the loop to make a trip count go from could not compute to
11240       // computable or vice-versa *should have* invalidated SCEV.  However, we
11241       // choose not to assert here (for now) since we don't want false
11242       // positives.
11243       continue;
11244     }
11245
11246     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11247       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11248       // not propagate undef aggressively).  This means we can (and do) fail
11249       // verification in cases where a transform makes the trip count of a loop
11250       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11251       // both cases the loop iterates "undef" times, but SCEV thinks we
11252       // increased the trip count of the loop by 1 incorrectly.
11253       continue;
11254     }
11255
11256     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11257         SE.getTypeSizeInBits(NewBECount->getType()))
11258       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11259     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11260              SE.getTypeSizeInBits(NewBECount->getType()))
11261       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11262
11263     auto *ConstantDelta =
11264         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11265
11266     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11267       dbgs() << "Trip Count Changed!\n";
11268       dbgs() << "Old: " << *CurBECount << "\n";
11269       dbgs() << "New: " << *NewBECount << "\n";
11270       dbgs() << "Delta: " << *ConstantDelta << "\n";
11271       std::abort();
11272     }
11273   }
11274 }
11275
11276 bool ScalarEvolution::invalidate(
11277     Function &F, const PreservedAnalyses &PA,
11278     FunctionAnalysisManager::Invalidator &Inv) {
11279   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11280   // of its dependencies is invalidated.
11281   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11282   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11283          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11284          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11285          Inv.invalidate<LoopAnalysis>(F, PA);
11286 }
11287
11288 AnalysisKey ScalarEvolutionAnalysis::Key;
11289
11290 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11291                                              FunctionAnalysisManager &AM) {
11292   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11293                          AM.getResult<AssumptionAnalysis>(F),
11294                          AM.getResult<DominatorTreeAnalysis>(F),
11295                          AM.getResult<LoopAnalysis>(F));
11296 }
11297
11298 PreservedAnalyses
11299 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11300   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11301   return PreservedAnalyses::all();
11302 }
11303
11304 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11305                       "Scalar Evolution Analysis", false, true)
11306 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11307 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11308 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11309 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11310 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11311                     "Scalar Evolution Analysis", false, true)
11312
11313 char ScalarEvolutionWrapperPass::ID = 0;
11314
11315 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11316   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11317 }
11318
11319 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11320   SE.reset(new ScalarEvolution(
11321       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11322       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11323       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11324       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11325   return false;
11326 }
11327
11328 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11329
11330 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11331   SE->print(OS);
11332 }
11333
11334 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11335   if (!VerifySCEV)
11336     return;
11337
11338   SE->verify();
11339 }
11340
11341 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11342   AU.setPreservesAll();
11343   AU.addRequiredTransitive<AssumptionCacheTracker>();
11344   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11345   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11346   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11347 }
11348
11349 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11350                                                         const SCEV *RHS) {
11351   FoldingSetNodeID ID;
11352   assert(LHS->getType() == RHS->getType() &&
11353          "Type mismatch between LHS and RHS");
11354   // Unique this node based on the arguments
11355   ID.AddInteger(SCEVPredicate::P_Equal);
11356   ID.AddPointer(LHS);
11357   ID.AddPointer(RHS);
11358   void *IP = nullptr;
11359   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11360     return S;
11361   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11362       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11363   UniquePreds.InsertNode(Eq, IP);
11364   return Eq;
11365 }
11366
11367 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11368     const SCEVAddRecExpr *AR,
11369     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11370   FoldingSetNodeID ID;
11371   // Unique this node based on the arguments
11372   ID.AddInteger(SCEVPredicate::P_Wrap);
11373   ID.AddPointer(AR);
11374   ID.AddInteger(AddedFlags);
11375   void *IP = nullptr;
11376   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11377     return S;
11378   auto *OF = new (SCEVAllocator)
11379       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11380   UniquePreds.InsertNode(OF, IP);
11381   return OF;
11382 }
11383
11384 namespace {
11385
11386 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11387 public:
11388
11389   /// Rewrites \p S in the context of a loop L and the SCEV predication
11390   /// infrastructure.
11391   ///
11392   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11393   /// equivalences present in \p Pred.
11394   ///
11395   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11396   /// \p NewPreds such that the result will be an AddRecExpr.
11397   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11398                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11399                              SCEVUnionPredicate *Pred) {
11400     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11401     return Rewriter.visit(S);
11402   }
11403
11404   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11405     if (Pred) {
11406       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11407       for (auto *Pred : ExprPreds)
11408         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11409           if (IPred->getLHS() == Expr)
11410             return IPred->getRHS();
11411     }
11412     return convertToAddRecWithPreds(Expr);
11413   }
11414
11415   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11416     const SCEV *Operand = visit(Expr->getOperand());
11417     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11418     if (AR && AR->getLoop() == L && AR->isAffine()) {
11419       // This couldn't be folded because the operand didn't have the nuw
11420       // flag. Add the nusw flag as an assumption that we could make.
11421       const SCEV *Step = AR->getStepRecurrence(SE);
11422       Type *Ty = Expr->getType();
11423       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11424         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11425                                 SE.getSignExtendExpr(Step, Ty), L,
11426                                 AR->getNoWrapFlags());
11427     }
11428     return SE.getZeroExtendExpr(Operand, Expr->getType());
11429   }
11430
11431   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11432     const SCEV *Operand = visit(Expr->getOperand());
11433     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11434     if (AR && AR->getLoop() == L && AR->isAffine()) {
11435       // This couldn't be folded because the operand didn't have the nsw
11436       // flag. Add the nssw flag as an assumption that we could make.
11437       const SCEV *Step = AR->getStepRecurrence(SE);
11438       Type *Ty = Expr->getType();
11439       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11440         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11441                                 SE.getSignExtendExpr(Step, Ty), L,
11442                                 AR->getNoWrapFlags());
11443     }
11444     return SE.getSignExtendExpr(Operand, Expr->getType());
11445   }
11446
11447 private:
11448   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11449                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11450                         SCEVUnionPredicate *Pred)
11451       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11452
11453   bool addOverflowAssumption(const SCEVPredicate *P) {
11454     if (!NewPreds) {
11455       // Check if we've already made this assumption.
11456       return Pred && Pred->implies(P);
11457     }
11458     NewPreds->insert(P);
11459     return true;
11460   }
11461
11462   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11463                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11464     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11465     return addOverflowAssumption(A);
11466   }
11467
11468   // If \p Expr represents a PHINode, we try to see if it can be represented
11469   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11470   // to add this predicate as a runtime overflow check, we return the AddRec.
11471   // If \p Expr does not meet these conditions (is not a PHI node, or we
11472   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11473   // return \p Expr.
11474   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11475     if (!VersionUnknown)
11476       return Expr;
11477     if (!isa<PHINode>(Expr->getValue()))
11478       return Expr;
11479     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11480     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11481     if (!PredicatedRewrite)
11482       return Expr;
11483     for (auto *P : PredicatedRewrite->second){
11484       if (!addOverflowAssumption(P))
11485         return Expr;
11486     }
11487     return PredicatedRewrite->first;
11488   }
11489
11490   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11491   SCEVUnionPredicate *Pred;
11492   const Loop *L;
11493 };
11494
11495 } // end anonymous namespace
11496
11497 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11498                                                    SCEVUnionPredicate &Preds) {
11499   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11500 }
11501
11502 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11503     const SCEV *S, const Loop *L,
11504     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11505   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11506   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11507   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11508
11509   if (!AddRec)
11510     return nullptr;
11511
11512   // Since the transformation was successful, we can now transfer the SCEV
11513   // predicates.
11514   for (auto *P : TransformPreds)
11515     Preds.insert(P);
11516
11517   return AddRec;
11518 }
11519
11520 /// SCEV predicates
11521 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11522                              SCEVPredicateKind Kind)
11523     : FastID(ID), Kind(Kind) {}
11524
11525 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11526                                        const SCEV *LHS, const SCEV *RHS)
11527     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11528   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11529   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11530 }
11531
11532 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11533   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11534
11535   if (!Op)
11536     return false;
11537
11538   return Op->LHS == LHS && Op->RHS == RHS;
11539 }
11540
11541 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11542
11543 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11544
11545 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11546   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11547 }
11548
11549 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11550                                      const SCEVAddRecExpr *AR,
11551                                      IncrementWrapFlags Flags)
11552     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11553
11554 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11555
11556 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11557   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11558
11559   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11560 }
11561
11562 bool SCEVWrapPredicate::isAlwaysTrue() const {
11563   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11564   IncrementWrapFlags IFlags = Flags;
11565
11566   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11567     IFlags = clearFlags(IFlags, IncrementNSSW);
11568
11569   return IFlags == IncrementAnyWrap;
11570 }
11571
11572 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11573   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11574   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11575     OS << "<nusw>";
11576   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11577     OS << "<nssw>";
11578   OS << "\n";
11579 }
11580
11581 SCEVWrapPredicate::IncrementWrapFlags
11582 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11583                                    ScalarEvolution &SE) {
11584   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11585   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11586
11587   // We can safely transfer the NSW flag as NSSW.
11588   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11589     ImpliedFlags = IncrementNSSW;
11590
11591   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11592     // If the increment is positive, the SCEV NUW flag will also imply the
11593     // WrapPredicate NUSW flag.
11594     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11595       if (Step->getValue()->getValue().isNonNegative())
11596         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11597   }
11598
11599   return ImpliedFlags;
11600 }
11601
11602 /// Union predicates don't get cached so create a dummy set ID for it.
11603 SCEVUnionPredicate::SCEVUnionPredicate()
11604     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11605
11606 bool SCEVUnionPredicate::isAlwaysTrue() const {
11607   return all_of(Preds,
11608                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11609 }
11610
11611 ArrayRef<const SCEVPredicate *>
11612 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11613   auto I = SCEVToPreds.find(Expr);
11614   if (I == SCEVToPreds.end())
11615     return ArrayRef<const SCEVPredicate *>();
11616   return I->second;
11617 }
11618
11619 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11620   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11621     return all_of(Set->Preds,
11622                   [this](const SCEVPredicate *I) { return this->implies(I); });
11623
11624   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11625   if (ScevPredsIt == SCEVToPreds.end())
11626     return false;
11627   auto &SCEVPreds = ScevPredsIt->second;
11628
11629   return any_of(SCEVPreds,
11630                 [N](const SCEVPredicate *I) { return I->implies(N); });
11631 }
11632
11633 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11634
11635 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11636   for (auto Pred : Preds)
11637     Pred->print(OS, Depth);
11638 }
11639
11640 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11641   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11642     for (auto Pred : Set->Preds)
11643       add(Pred);
11644     return;
11645   }
11646
11647   if (implies(N))
11648     return;
11649
11650   const SCEV *Key = N->getExpr();
11651   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11652                 " associated expression!");
11653
11654   SCEVToPreds[Key].push_back(N);
11655   Preds.push_back(N);
11656 }
11657
11658 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11659                                                      Loop &L)
11660     : SE(SE), L(L) {}
11661
11662 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11663   const SCEV *Expr = SE.getSCEV(V);
11664   RewriteEntry &Entry = RewriteMap[Expr];
11665
11666   // If we already have an entry and the version matches, return it.
11667   if (Entry.second && Generation == Entry.first)
11668     return Entry.second;
11669
11670   // We found an entry but it's stale. Rewrite the stale entry
11671   // according to the current predicate.
11672   if (Entry.second)
11673     Expr = Entry.second;
11674
11675   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11676   Entry = {Generation, NewSCEV};
11677
11678   return NewSCEV;
11679 }
11680
11681 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11682   if (!BackedgeCount) {
11683     SCEVUnionPredicate BackedgePred;
11684     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11685     addPredicate(BackedgePred);
11686   }
11687   return BackedgeCount;
11688 }
11689
11690 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
11691   if (Preds.implies(&Pred))
11692     return;
11693   Preds.add(&Pred);
11694   updateGeneration();
11695 }
11696
11697 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
11698   return Preds;
11699 }
11700
11701 void PredicatedScalarEvolution::updateGeneration() {
11702   // If the generation number wrapped recompute everything.
11703   if (++Generation == 0) {
11704     for (auto &II : RewriteMap) {
11705       const SCEV *Rewritten = II.second.second;
11706       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
11707     }
11708   }
11709 }
11710
11711 void PredicatedScalarEvolution::setNoOverflow(
11712     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11713   const SCEV *Expr = getSCEV(V);
11714   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11715
11716   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
11717
11718   // Clear the statically implied flags.
11719   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
11720   addPredicate(*SE.getWrapPredicate(AR, Flags));
11721
11722   auto II = FlagsMap.insert({V, Flags});
11723   if (!II.second)
11724     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
11725 }
11726
11727 bool PredicatedScalarEvolution::hasNoOverflow(
11728     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11729   const SCEV *Expr = getSCEV(V);
11730   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11731
11732   Flags = SCEVWrapPredicate::clearFlags(
11733       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
11734
11735   auto II = FlagsMap.find(V);
11736
11737   if (II != FlagsMap.end())
11738     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
11739
11740   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
11741 }
11742
11743 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
11744   const SCEV *Expr = this->getSCEV(V);
11745   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
11746   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
11747
11748   if (!New)
11749     return nullptr;
11750
11751   for (auto *P : NewPreds)
11752     Preds.add(P);
11753
11754   updateGeneration();
11755   RewriteMap[SE.getSCEV(V)] = {Generation, New};
11756   return New;
11757 }
11758
11759 PredicatedScalarEvolution::PredicatedScalarEvolution(
11760     const PredicatedScalarEvolution &Init)
11761     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11762       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11763   for (const auto &I : Init.FlagsMap)
11764     FlagsMap.insert(I);
11765 }
11766
11767 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11768   // For each block.
11769   for (auto *BB : L.getBlocks())
11770     for (auto &I : *BB) {
11771       if (!SE.isSCEVable(I.getType()))
11772         continue;
11773
11774       auto *Expr = SE.getSCEV(&I);
11775       auto II = RewriteMap.find(Expr);
11776
11777       if (II == RewriteMap.end())
11778         continue;
11779
11780       // Don't print things that are not interesting.
11781       if (II->second.second == Expr)
11782         continue;
11783
11784       OS.indent(Depth) << "[PSE]" << I << ":\n";
11785       OS.indent(Depth + 2) << *Expr << "\n";
11786       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11787     }
11788 }