6c72feb71cdcc4b06f3f1ebf3287812770056905
[oota-llvm.git] / lib / Analysis / ScalarEvolution.cpp
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/Analysis/AssumptionCache.h"
67 #include "llvm/Analysis/ConstantFolding.h"
68 #include "llvm/Analysis/InstructionSimplify.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
71 #include "llvm/Analysis/TargetLibraryInfo.h"
72 #include "llvm/Analysis/ValueTracking.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DerivedTypes.h"
77 #include "llvm/IR/Dominators.h"
78 #include "llvm/IR/GetElementPtrTypeIterator.h"
79 #include "llvm/IR/GlobalAlias.h"
80 #include "llvm/IR/GlobalVariable.h"
81 #include "llvm/IR/InstIterator.h"
82 #include "llvm/IR/Instructions.h"
83 #include "llvm/IR/LLVMContext.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/Support/CommandLine.h"
87 #include "llvm/Support/Debug.h"
88 #include "llvm/Support/ErrorHandling.h"
89 #include "llvm/Support/MathExtras.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Support/SaveAndRestore.h"
92 #include <algorithm>
93 using namespace llvm;
94
95 #define DEBUG_TYPE "scalar-evolution"
96
97 STATISTIC(NumArrayLenItCounts,
98           "Number of trip counts computed with array length");
99 STATISTIC(NumTripCountsComputed,
100           "Number of loops with predictable loop counts");
101 STATISTIC(NumTripCountsNotComputed,
102           "Number of loops without predictable loop counts");
103 STATISTIC(NumBruteForceTripCountsComputed,
104           "Number of loops with trip counts computed by force");
105
106 static cl::opt<unsigned>
107 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
108                         cl::desc("Maximum number of iterations SCEV will "
109                                  "symbolically execute a constant "
110                                  "derived loop"),
111                         cl::init(100));
112
113 // FIXME: Enable this with XDEBUG when the test suite is clean.
114 static cl::opt<bool>
115 VerifySCEV("verify-scev",
116            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
117
118 //===----------------------------------------------------------------------===//
119 //                           SCEV class definitions
120 //===----------------------------------------------------------------------===//
121
122 //===----------------------------------------------------------------------===//
123 // Implementation of the SCEV class.
124 //
125
126 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
127 void SCEV::dump() const {
128   print(dbgs());
129   dbgs() << '\n';
130 }
131 #endif
132
133 void SCEV::print(raw_ostream &OS) const {
134   switch (static_cast<SCEVTypes>(getSCEVType())) {
135   case scConstant:
136     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
137     return;
138   case scTruncate: {
139     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
140     const SCEV *Op = Trunc->getOperand();
141     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
142        << *Trunc->getType() << ")";
143     return;
144   }
145   case scZeroExtend: {
146     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
147     const SCEV *Op = ZExt->getOperand();
148     OS << "(zext " << *Op->getType() << " " << *Op << " to "
149        << *ZExt->getType() << ")";
150     return;
151   }
152   case scSignExtend: {
153     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
154     const SCEV *Op = SExt->getOperand();
155     OS << "(sext " << *Op->getType() << " " << *Op << " to "
156        << *SExt->getType() << ")";
157     return;
158   }
159   case scAddRecExpr: {
160     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
161     OS << "{" << *AR->getOperand(0);
162     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
163       OS << ",+," << *AR->getOperand(i);
164     OS << "}<";
165     if (AR->getNoWrapFlags(FlagNUW))
166       OS << "nuw><";
167     if (AR->getNoWrapFlags(FlagNSW))
168       OS << "nsw><";
169     if (AR->getNoWrapFlags(FlagNW) &&
170         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
171       OS << "nw><";
172     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
173     OS << ">";
174     return;
175   }
176   case scAddExpr:
177   case scMulExpr:
178   case scUMaxExpr:
179   case scSMaxExpr: {
180     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
181     const char *OpStr = nullptr;
182     switch (NAry->getSCEVType()) {
183     case scAddExpr: OpStr = " + "; break;
184     case scMulExpr: OpStr = " * "; break;
185     case scUMaxExpr: OpStr = " umax "; break;
186     case scSMaxExpr: OpStr = " smax "; break;
187     }
188     OS << "(";
189     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
190          I != E; ++I) {
191       OS << **I;
192       if (std::next(I) != E)
193         OS << OpStr;
194     }
195     OS << ")";
196     switch (NAry->getSCEVType()) {
197     case scAddExpr:
198     case scMulExpr:
199       if (NAry->getNoWrapFlags(FlagNUW))
200         OS << "<nuw>";
201       if (NAry->getNoWrapFlags(FlagNSW))
202         OS << "<nsw>";
203     }
204     return;
205   }
206   case scUDivExpr: {
207     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
208     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
209     return;
210   }
211   case scUnknown: {
212     const SCEVUnknown *U = cast<SCEVUnknown>(this);
213     Type *AllocTy;
214     if (U->isSizeOf(AllocTy)) {
215       OS << "sizeof(" << *AllocTy << ")";
216       return;
217     }
218     if (U->isAlignOf(AllocTy)) {
219       OS << "alignof(" << *AllocTy << ")";
220       return;
221     }
222
223     Type *CTy;
224     Constant *FieldNo;
225     if (U->isOffsetOf(CTy, FieldNo)) {
226       OS << "offsetof(" << *CTy << ", ";
227       FieldNo->printAsOperand(OS, false);
228       OS << ")";
229       return;
230     }
231
232     // Otherwise just print it normally.
233     U->getValue()->printAsOperand(OS, false);
234     return;
235   }
236   case scCouldNotCompute:
237     OS << "***COULDNOTCOMPUTE***";
238     return;
239   }
240   llvm_unreachable("Unknown SCEV kind!");
241 }
242
243 Type *SCEV::getType() const {
244   switch (static_cast<SCEVTypes>(getSCEVType())) {
245   case scConstant:
246     return cast<SCEVConstant>(this)->getType();
247   case scTruncate:
248   case scZeroExtend:
249   case scSignExtend:
250     return cast<SCEVCastExpr>(this)->getType();
251   case scAddRecExpr:
252   case scMulExpr:
253   case scUMaxExpr:
254   case scSMaxExpr:
255     return cast<SCEVNAryExpr>(this)->getType();
256   case scAddExpr:
257     return cast<SCEVAddExpr>(this)->getType();
258   case scUDivExpr:
259     return cast<SCEVUDivExpr>(this)->getType();
260   case scUnknown:
261     return cast<SCEVUnknown>(this)->getType();
262   case scCouldNotCompute:
263     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
264   }
265   llvm_unreachable("Unknown SCEV kind!");
266 }
267
268 bool SCEV::isZero() const {
269   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
270     return SC->getValue()->isZero();
271   return false;
272 }
273
274 bool SCEV::isOne() const {
275   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
276     return SC->getValue()->isOne();
277   return false;
278 }
279
280 bool SCEV::isAllOnesValue() const {
281   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
282     return SC->getValue()->isAllOnesValue();
283   return false;
284 }
285
286 /// isNonConstantNegative - Return true if the specified scev is negated, but
287 /// not a constant.
288 bool SCEV::isNonConstantNegative() const {
289   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
290   if (!Mul) return false;
291
292   // If there is a constant factor, it will be first.
293   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
294   if (!SC) return false;
295
296   // Return true if the value is negative, this matches things like (-42 * V).
297   return SC->getValue()->getValue().isNegative();
298 }
299
300 SCEVCouldNotCompute::SCEVCouldNotCompute() :
301   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
302
303 bool SCEVCouldNotCompute::classof(const SCEV *S) {
304   return S->getSCEVType() == scCouldNotCompute;
305 }
306
307 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
308   FoldingSetNodeID ID;
309   ID.AddInteger(scConstant);
310   ID.AddPointer(V);
311   void *IP = nullptr;
312   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
313   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
314   UniqueSCEVs.InsertNode(S, IP);
315   return S;
316 }
317
318 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
319   return getConstant(ConstantInt::get(getContext(), Val));
320 }
321
322 const SCEV *
323 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
324   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
325   return getConstant(ConstantInt::get(ITy, V, isSigned));
326 }
327
328 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
329                            unsigned SCEVTy, const SCEV *op, Type *ty)
330   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
331
332 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
333                                    const SCEV *op, Type *ty)
334   : SCEVCastExpr(ID, scTruncate, op, ty) {
335   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
336          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
337          "Cannot truncate non-integer value!");
338 }
339
340 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
341                                        const SCEV *op, Type *ty)
342   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
343   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
344          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
345          "Cannot zero extend non-integer value!");
346 }
347
348 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
349                                        const SCEV *op, Type *ty)
350   : SCEVCastExpr(ID, scSignExtend, op, ty) {
351   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
352          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
353          "Cannot sign extend non-integer value!");
354 }
355
356 void SCEVUnknown::deleted() {
357   // Clear this SCEVUnknown from various maps.
358   SE->forgetMemoizedResults(this);
359
360   // Remove this SCEVUnknown from the uniquing map.
361   SE->UniqueSCEVs.RemoveNode(this);
362
363   // Release the value.
364   setValPtr(nullptr);
365 }
366
367 void SCEVUnknown::allUsesReplacedWith(Value *New) {
368   // Clear this SCEVUnknown from various maps.
369   SE->forgetMemoizedResults(this);
370
371   // Remove this SCEVUnknown from the uniquing map.
372   SE->UniqueSCEVs.RemoveNode(this);
373
374   // Update this SCEVUnknown to point to the new value. This is needed
375   // because there may still be outstanding SCEVs which still point to
376   // this SCEVUnknown.
377   setValPtr(New);
378 }
379
380 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
381   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
382     if (VCE->getOpcode() == Instruction::PtrToInt)
383       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
384         if (CE->getOpcode() == Instruction::GetElementPtr &&
385             CE->getOperand(0)->isNullValue() &&
386             CE->getNumOperands() == 2)
387           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
388             if (CI->isOne()) {
389               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
390                                  ->getElementType();
391               return true;
392             }
393
394   return false;
395 }
396
397 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
398   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
399     if (VCE->getOpcode() == Instruction::PtrToInt)
400       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
401         if (CE->getOpcode() == Instruction::GetElementPtr &&
402             CE->getOperand(0)->isNullValue()) {
403           Type *Ty =
404             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
405           if (StructType *STy = dyn_cast<StructType>(Ty))
406             if (!STy->isPacked() &&
407                 CE->getNumOperands() == 3 &&
408                 CE->getOperand(1)->isNullValue()) {
409               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
410                 if (CI->isOne() &&
411                     STy->getNumElements() == 2 &&
412                     STy->getElementType(0)->isIntegerTy(1)) {
413                   AllocTy = STy->getElementType(1);
414                   return true;
415                 }
416             }
417         }
418
419   return false;
420 }
421
422 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
423   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
424     if (VCE->getOpcode() == Instruction::PtrToInt)
425       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
426         if (CE->getOpcode() == Instruction::GetElementPtr &&
427             CE->getNumOperands() == 3 &&
428             CE->getOperand(0)->isNullValue() &&
429             CE->getOperand(1)->isNullValue()) {
430           Type *Ty =
431             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
432           // Ignore vector types here so that ScalarEvolutionExpander doesn't
433           // emit getelementptrs that index into vectors.
434           if (Ty->isStructTy() || Ty->isArrayTy()) {
435             CTy = Ty;
436             FieldNo = CE->getOperand(2);
437             return true;
438           }
439         }
440
441   return false;
442 }
443
444 //===----------------------------------------------------------------------===//
445 //                               SCEV Utilities
446 //===----------------------------------------------------------------------===//
447
448 namespace {
449   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450   /// than the complexity of the RHS.  This comparator is used to canonicalize
451   /// expressions.
452   class SCEVComplexityCompare {
453     const LoopInfo *const LI;
454   public:
455     explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
456
457     // Return true or false if LHS is less than, or at least RHS, respectively.
458     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
459       return compare(LHS, RHS) < 0;
460     }
461
462     // Return negative, zero, or positive, if LHS is less than, equal to, or
463     // greater than RHS, respectively. A three-way result allows recursive
464     // comparisons to be more efficient.
465     int compare(const SCEV *LHS, const SCEV *RHS) const {
466       // Fast-path: SCEVs are uniqued so we can do a quick equality check.
467       if (LHS == RHS)
468         return 0;
469
470       // Primarily, sort the SCEVs by their getSCEVType().
471       unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
472       if (LType != RType)
473         return (int)LType - (int)RType;
474
475       // Aside from the getSCEVType() ordering, the particular ordering
476       // isn't very important except that it's beneficial to be consistent,
477       // so that (a + b) and (b + a) don't end up as different expressions.
478       switch (static_cast<SCEVTypes>(LType)) {
479       case scUnknown: {
480         const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
481         const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
482
483         // Sort SCEVUnknown values with some loose heuristics. TODO: This is
484         // not as complete as it could be.
485         const Value *LV = LU->getValue(), *RV = RU->getValue();
486
487         // Order pointer values after integer values. This helps SCEVExpander
488         // form GEPs.
489         bool LIsPointer = LV->getType()->isPointerTy(),
490              RIsPointer = RV->getType()->isPointerTy();
491         if (LIsPointer != RIsPointer)
492           return (int)LIsPointer - (int)RIsPointer;
493
494         // Compare getValueID values.
495         unsigned LID = LV->getValueID(),
496                  RID = RV->getValueID();
497         if (LID != RID)
498           return (int)LID - (int)RID;
499
500         // Sort arguments by their position.
501         if (const Argument *LA = dyn_cast<Argument>(LV)) {
502           const Argument *RA = cast<Argument>(RV);
503           unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
504           return (int)LArgNo - (int)RArgNo;
505         }
506
507         // For instructions, compare their loop depth, and their operand
508         // count.  This is pretty loose.
509         if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
510           const Instruction *RInst = cast<Instruction>(RV);
511
512           // Compare loop depths.
513           const BasicBlock *LParent = LInst->getParent(),
514                            *RParent = RInst->getParent();
515           if (LParent != RParent) {
516             unsigned LDepth = LI->getLoopDepth(LParent),
517                      RDepth = LI->getLoopDepth(RParent);
518             if (LDepth != RDepth)
519               return (int)LDepth - (int)RDepth;
520           }
521
522           // Compare the number of operands.
523           unsigned LNumOps = LInst->getNumOperands(),
524                    RNumOps = RInst->getNumOperands();
525           return (int)LNumOps - (int)RNumOps;
526         }
527
528         return 0;
529       }
530
531       case scConstant: {
532         const SCEVConstant *LC = cast<SCEVConstant>(LHS);
533         const SCEVConstant *RC = cast<SCEVConstant>(RHS);
534
535         // Compare constant values.
536         const APInt &LA = LC->getValue()->getValue();
537         const APInt &RA = RC->getValue()->getValue();
538         unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
539         if (LBitWidth != RBitWidth)
540           return (int)LBitWidth - (int)RBitWidth;
541         return LA.ult(RA) ? -1 : 1;
542       }
543
544       case scAddRecExpr: {
545         const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
546         const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
547
548         // Compare addrec loop depths.
549         const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
550         if (LLoop != RLoop) {
551           unsigned LDepth = LLoop->getLoopDepth(),
552                    RDepth = RLoop->getLoopDepth();
553           if (LDepth != RDepth)
554             return (int)LDepth - (int)RDepth;
555         }
556
557         // Addrec complexity grows with operand count.
558         unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
559         if (LNumOps != RNumOps)
560           return (int)LNumOps - (int)RNumOps;
561
562         // Lexicographically compare.
563         for (unsigned i = 0; i != LNumOps; ++i) {
564           long X = compare(LA->getOperand(i), RA->getOperand(i));
565           if (X != 0)
566             return X;
567         }
568
569         return 0;
570       }
571
572       case scAddExpr:
573       case scMulExpr:
574       case scSMaxExpr:
575       case scUMaxExpr: {
576         const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
577         const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
578
579         // Lexicographically compare n-ary expressions.
580         unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
581         if (LNumOps != RNumOps)
582           return (int)LNumOps - (int)RNumOps;
583
584         for (unsigned i = 0; i != LNumOps; ++i) {
585           if (i >= RNumOps)
586             return 1;
587           long X = compare(LC->getOperand(i), RC->getOperand(i));
588           if (X != 0)
589             return X;
590         }
591         return (int)LNumOps - (int)RNumOps;
592       }
593
594       case scUDivExpr: {
595         const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
596         const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
597
598         // Lexicographically compare udiv expressions.
599         long X = compare(LC->getLHS(), RC->getLHS());
600         if (X != 0)
601           return X;
602         return compare(LC->getRHS(), RC->getRHS());
603       }
604
605       case scTruncate:
606       case scZeroExtend:
607       case scSignExtend: {
608         const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
609         const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
610
611         // Compare cast expressions by operand.
612         return compare(LC->getOperand(), RC->getOperand());
613       }
614
615       case scCouldNotCompute:
616         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
617       }
618       llvm_unreachable("Unknown SCEV kind!");
619     }
620   };
621 }
622
623 /// GroupByComplexity - Given a list of SCEV objects, order them by their
624 /// complexity, and group objects of the same complexity together by value.
625 /// When this routine is finished, we know that any duplicates in the vector are
626 /// consecutive and that complexity is monotonically increasing.
627 ///
628 /// Note that we go take special precautions to ensure that we get deterministic
629 /// results from this routine.  In other words, we don't want the results of
630 /// this to depend on where the addresses of various SCEV objects happened to
631 /// land in memory.
632 ///
633 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
634                               LoopInfo *LI) {
635   if (Ops.size() < 2) return;  // Noop
636   if (Ops.size() == 2) {
637     // This is the common case, which also happens to be trivially simple.
638     // Special case it.
639     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
640     if (SCEVComplexityCompare(LI)(RHS, LHS))
641       std::swap(LHS, RHS);
642     return;
643   }
644
645   // Do the rough sort by complexity.
646   std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
647
648   // Now that we are sorted by complexity, group elements of the same
649   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
650   // be extremely short in practice.  Note that we take this approach because we
651   // do not want to depend on the addresses of the objects we are grouping.
652   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
653     const SCEV *S = Ops[i];
654     unsigned Complexity = S->getSCEVType();
655
656     // If there are any objects of the same complexity and same value as this
657     // one, group them.
658     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
659       if (Ops[j] == S) { // Found a duplicate.
660         // Move it to immediately after i'th element.
661         std::swap(Ops[i+1], Ops[j]);
662         ++i;   // no need to rescan it.
663         if (i == e-2) return;  // Done!
664       }
665     }
666   }
667 }
668
669 namespace {
670 struct FindSCEVSize {
671   int Size;
672   FindSCEVSize() : Size(0) {}
673
674   bool follow(const SCEV *S) {
675     ++Size;
676     // Keep looking at all operands of S.
677     return true;
678   }
679   bool isDone() const {
680     return false;
681   }
682 };
683 }
684
685 // Returns the size of the SCEV S.
686 static inline int sizeOfSCEV(const SCEV *S) {
687   FindSCEVSize F;
688   SCEVTraversal<FindSCEVSize> ST(F);
689   ST.visitAll(S);
690   return F.Size;
691 }
692
693 namespace {
694
695 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
696 public:
697   // Computes the Quotient and Remainder of the division of Numerator by
698   // Denominator.
699   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
700                      const SCEV *Denominator, const SCEV **Quotient,
701                      const SCEV **Remainder) {
702     assert(Numerator && Denominator && "Uninitialized SCEV");
703
704     SCEVDivision D(SE, Numerator, Denominator);
705
706     // Check for the trivial case here to avoid having to check for it in the
707     // rest of the code.
708     if (Numerator == Denominator) {
709       *Quotient = D.One;
710       *Remainder = D.Zero;
711       return;
712     }
713
714     if (Numerator->isZero()) {
715       *Quotient = D.Zero;
716       *Remainder = D.Zero;
717       return;
718     }
719
720     // A simple case when N/1. The quotient is N.
721     if (Denominator->isOne()) {
722       *Quotient = Numerator;
723       *Remainder = D.Zero;
724       return;
725     }
726
727     // Split the Denominator when it is a product.
728     if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
729       const SCEV *Q, *R;
730       *Quotient = Numerator;
731       for (const SCEV *Op : T->operands()) {
732         divide(SE, *Quotient, Op, &Q, &R);
733         *Quotient = Q;
734
735         // Bail out when the Numerator is not divisible by one of the terms of
736         // the Denominator.
737         if (!R->isZero()) {
738           *Quotient = D.Zero;
739           *Remainder = Numerator;
740           return;
741         }
742       }
743       *Remainder = D.Zero;
744       return;
745     }
746
747     D.visit(Numerator);
748     *Quotient = D.Quotient;
749     *Remainder = D.Remainder;
750   }
751
752   // Except in the trivial case described above, we do not know how to divide
753   // Expr by Denominator for the following functions with empty implementation.
754   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
755   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
756   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
757   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
758   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
759   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
760   void visitUnknown(const SCEVUnknown *Numerator) {}
761   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
762
763   void visitConstant(const SCEVConstant *Numerator) {
764     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
765       APInt NumeratorVal = Numerator->getValue()->getValue();
766       APInt DenominatorVal = D->getValue()->getValue();
767       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
768       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
769
770       if (NumeratorBW > DenominatorBW)
771         DenominatorVal = DenominatorVal.sext(NumeratorBW);
772       else if (NumeratorBW < DenominatorBW)
773         NumeratorVal = NumeratorVal.sext(DenominatorBW);
774
775       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
776       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
777       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
778       Quotient = SE.getConstant(QuotientVal);
779       Remainder = SE.getConstant(RemainderVal);
780       return;
781     }
782   }
783
784   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
785     const SCEV *StartQ, *StartR, *StepQ, *StepR;
786     if (!Numerator->isAffine())
787       return cannotDivide(Numerator);
788     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
789     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
790     // Bail out if the types do not match.
791     Type *Ty = Denominator->getType();
792     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
793         Ty != StepQ->getType() || Ty != StepR->getType())
794       return cannotDivide(Numerator);
795     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
796                                 Numerator->getNoWrapFlags());
797     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
798                                  Numerator->getNoWrapFlags());
799   }
800
801   void visitAddExpr(const SCEVAddExpr *Numerator) {
802     SmallVector<const SCEV *, 2> Qs, Rs;
803     Type *Ty = Denominator->getType();
804
805     for (const SCEV *Op : Numerator->operands()) {
806       const SCEV *Q, *R;
807       divide(SE, Op, Denominator, &Q, &R);
808
809       // Bail out if types do not match.
810       if (Ty != Q->getType() || Ty != R->getType())
811         return cannotDivide(Numerator);
812
813       Qs.push_back(Q);
814       Rs.push_back(R);
815     }
816
817     if (Qs.size() == 1) {
818       Quotient = Qs[0];
819       Remainder = Rs[0];
820       return;
821     }
822
823     Quotient = SE.getAddExpr(Qs);
824     Remainder = SE.getAddExpr(Rs);
825   }
826
827   void visitMulExpr(const SCEVMulExpr *Numerator) {
828     SmallVector<const SCEV *, 2> Qs;
829     Type *Ty = Denominator->getType();
830
831     bool FoundDenominatorTerm = false;
832     for (const SCEV *Op : Numerator->operands()) {
833       // Bail out if types do not match.
834       if (Ty != Op->getType())
835         return cannotDivide(Numerator);
836
837       if (FoundDenominatorTerm) {
838         Qs.push_back(Op);
839         continue;
840       }
841
842       // Check whether Denominator divides one of the product operands.
843       const SCEV *Q, *R;
844       divide(SE, Op, Denominator, &Q, &R);
845       if (!R->isZero()) {
846         Qs.push_back(Op);
847         continue;
848       }
849
850       // Bail out if types do not match.
851       if (Ty != Q->getType())
852         return cannotDivide(Numerator);
853
854       FoundDenominatorTerm = true;
855       Qs.push_back(Q);
856     }
857
858     if (FoundDenominatorTerm) {
859       Remainder = Zero;
860       if (Qs.size() == 1)
861         Quotient = Qs[0];
862       else
863         Quotient = SE.getMulExpr(Qs);
864       return;
865     }
866
867     if (!isa<SCEVUnknown>(Denominator))
868       return cannotDivide(Numerator);
869
870     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
871     ValueToValueMap RewriteMap;
872     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
873         cast<SCEVConstant>(Zero)->getValue();
874     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
875
876     if (Remainder->isZero()) {
877       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
878       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
879           cast<SCEVConstant>(One)->getValue();
880       Quotient =
881           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
882       return;
883     }
884
885     // Quotient is (Numerator - Remainder) divided by Denominator.
886     const SCEV *Q, *R;
887     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
888     // This SCEV does not seem to simplify: fail the division here.
889     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
890       return cannotDivide(Numerator);
891     divide(SE, Diff, Denominator, &Q, &R);
892     if (R != Zero)
893       return cannotDivide(Numerator);
894     Quotient = Q;
895   }
896
897 private:
898   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
899                const SCEV *Denominator)
900       : SE(S), Denominator(Denominator) {
901     Zero = SE.getZero(Denominator->getType());
902     One = SE.getOne(Denominator->getType());
903
904     // We generally do not know how to divide Expr by Denominator. We
905     // initialize the division to a "cannot divide" state to simplify the rest
906     // of the code.
907     cannotDivide(Numerator);
908   }
909
910   // Convenience function for giving up on the division. We set the quotient to
911   // be equal to zero and the remainder to be equal to the numerator.
912   void cannotDivide(const SCEV *Numerator) {
913     Quotient = Zero;
914     Remainder = Numerator;
915   }
916
917   ScalarEvolution &SE;
918   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
919 };
920
921 }
922
923 //===----------------------------------------------------------------------===//
924 //                      Simple SCEV method implementations
925 //===----------------------------------------------------------------------===//
926
927 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
928 /// Assume, K > 0.
929 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
930                                        ScalarEvolution &SE,
931                                        Type *ResultTy) {
932   // Handle the simplest case efficiently.
933   if (K == 1)
934     return SE.getTruncateOrZeroExtend(It, ResultTy);
935
936   // We are using the following formula for BC(It, K):
937   //
938   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
939   //
940   // Suppose, W is the bitwidth of the return value.  We must be prepared for
941   // overflow.  Hence, we must assure that the result of our computation is
942   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
943   // safe in modular arithmetic.
944   //
945   // However, this code doesn't use exactly that formula; the formula it uses
946   // is something like the following, where T is the number of factors of 2 in
947   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
948   // exponentiation:
949   //
950   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
951   //
952   // This formula is trivially equivalent to the previous formula.  However,
953   // this formula can be implemented much more efficiently.  The trick is that
954   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
955   // arithmetic.  To do exact division in modular arithmetic, all we have
956   // to do is multiply by the inverse.  Therefore, this step can be done at
957   // width W.
958   //
959   // The next issue is how to safely do the division by 2^T.  The way this
960   // is done is by doing the multiplication step at a width of at least W + T
961   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
962   // when we perform the division by 2^T (which is equivalent to a right shift
963   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
964   // truncated out after the division by 2^T.
965   //
966   // In comparison to just directly using the first formula, this technique
967   // is much more efficient; using the first formula requires W * K bits,
968   // but this formula less than W + K bits. Also, the first formula requires
969   // a division step, whereas this formula only requires multiplies and shifts.
970   //
971   // It doesn't matter whether the subtraction step is done in the calculation
972   // width or the input iteration count's width; if the subtraction overflows,
973   // the result must be zero anyway.  We prefer here to do it in the width of
974   // the induction variable because it helps a lot for certain cases; CodeGen
975   // isn't smart enough to ignore the overflow, which leads to much less
976   // efficient code if the width of the subtraction is wider than the native
977   // register width.
978   //
979   // (It's possible to not widen at all by pulling out factors of 2 before
980   // the multiplication; for example, K=2 can be calculated as
981   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
982   // extra arithmetic, so it's not an obvious win, and it gets
983   // much more complicated for K > 3.)
984
985   // Protection from insane SCEVs; this bound is conservative,
986   // but it probably doesn't matter.
987   if (K > 1000)
988     return SE.getCouldNotCompute();
989
990   unsigned W = SE.getTypeSizeInBits(ResultTy);
991
992   // Calculate K! / 2^T and T; we divide out the factors of two before
993   // multiplying for calculating K! / 2^T to avoid overflow.
994   // Other overflow doesn't matter because we only care about the bottom
995   // W bits of the result.
996   APInt OddFactorial(W, 1);
997   unsigned T = 1;
998   for (unsigned i = 3; i <= K; ++i) {
999     APInt Mult(W, i);
1000     unsigned TwoFactors = Mult.countTrailingZeros();
1001     T += TwoFactors;
1002     Mult = Mult.lshr(TwoFactors);
1003     OddFactorial *= Mult;
1004   }
1005
1006   // We need at least W + T bits for the multiplication step
1007   unsigned CalculationBits = W + T;
1008
1009   // Calculate 2^T, at width T+W.
1010   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1011
1012   // Calculate the multiplicative inverse of K! / 2^T;
1013   // this multiplication factor will perform the exact division by
1014   // K! / 2^T.
1015   APInt Mod = APInt::getSignedMinValue(W+1);
1016   APInt MultiplyFactor = OddFactorial.zext(W+1);
1017   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1018   MultiplyFactor = MultiplyFactor.trunc(W);
1019
1020   // Calculate the product, at width T+W
1021   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1022                                                       CalculationBits);
1023   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1024   for (unsigned i = 1; i != K; ++i) {
1025     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1026     Dividend = SE.getMulExpr(Dividend,
1027                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1028   }
1029
1030   // Divide by 2^T
1031   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1032
1033   // Truncate the result, and divide by K! / 2^T.
1034
1035   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1036                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1037 }
1038
1039 /// evaluateAtIteration - Return the value of this chain of recurrences at
1040 /// the specified iteration number.  We can evaluate this recurrence by
1041 /// multiplying each element in the chain by the binomial coefficient
1042 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
1043 ///
1044 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1045 ///
1046 /// where BC(It, k) stands for binomial coefficient.
1047 ///
1048 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1049                                                 ScalarEvolution &SE) const {
1050   const SCEV *Result = getStart();
1051   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1052     // The computation is correct in the face of overflow provided that the
1053     // multiplication is performed _after_ the evaluation of the binomial
1054     // coefficient.
1055     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1056     if (isa<SCEVCouldNotCompute>(Coeff))
1057       return Coeff;
1058
1059     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1060   }
1061   return Result;
1062 }
1063
1064 //===----------------------------------------------------------------------===//
1065 //                    SCEV Expression folder implementations
1066 //===----------------------------------------------------------------------===//
1067
1068 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1069                                              Type *Ty) {
1070   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1071          "This is not a truncating conversion!");
1072   assert(isSCEVable(Ty) &&
1073          "This is not a conversion to a SCEVable type!");
1074   Ty = getEffectiveSCEVType(Ty);
1075
1076   FoldingSetNodeID ID;
1077   ID.AddInteger(scTruncate);
1078   ID.AddPointer(Op);
1079   ID.AddPointer(Ty);
1080   void *IP = nullptr;
1081   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1082
1083   // Fold if the operand is constant.
1084   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1085     return getConstant(
1086       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1087
1088   // trunc(trunc(x)) --> trunc(x)
1089   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1090     return getTruncateExpr(ST->getOperand(), Ty);
1091
1092   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1093   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1094     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1095
1096   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1097   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1098     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1099
1100   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1101   // eliminate all the truncates, or we replace other casts with truncates.
1102   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1103     SmallVector<const SCEV *, 4> Operands;
1104     bool hasTrunc = false;
1105     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1106       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1107       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1108         hasTrunc = isa<SCEVTruncateExpr>(S);
1109       Operands.push_back(S);
1110     }
1111     if (!hasTrunc)
1112       return getAddExpr(Operands);
1113     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1114   }
1115
1116   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1117   // eliminate all the truncates, or we replace other casts with truncates.
1118   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1119     SmallVector<const SCEV *, 4> Operands;
1120     bool hasTrunc = false;
1121     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1122       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1123       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1124         hasTrunc = isa<SCEVTruncateExpr>(S);
1125       Operands.push_back(S);
1126     }
1127     if (!hasTrunc)
1128       return getMulExpr(Operands);
1129     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1130   }
1131
1132   // If the input value is a chrec scev, truncate the chrec's operands.
1133   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1134     SmallVector<const SCEV *, 4> Operands;
1135     for (const SCEV *Op : AddRec->operands())
1136       Operands.push_back(getTruncateExpr(Op, Ty));
1137     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1138   }
1139
1140   // The cast wasn't folded; create an explicit cast node. We can reuse
1141   // the existing insert position since if we get here, we won't have
1142   // made any changes which would invalidate it.
1143   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1144                                                  Op, Ty);
1145   UniqueSCEVs.InsertNode(S, IP);
1146   return S;
1147 }
1148
1149 // Get the limit of a recurrence such that incrementing by Step cannot cause
1150 // signed overflow as long as the value of the recurrence within the
1151 // loop does not exceed this limit before incrementing.
1152 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1153                                                  ICmpInst::Predicate *Pred,
1154                                                  ScalarEvolution *SE) {
1155   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1156   if (SE->isKnownPositive(Step)) {
1157     *Pred = ICmpInst::ICMP_SLT;
1158     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1159                            SE->getSignedRange(Step).getSignedMax());
1160   }
1161   if (SE->isKnownNegative(Step)) {
1162     *Pred = ICmpInst::ICMP_SGT;
1163     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1164                            SE->getSignedRange(Step).getSignedMin());
1165   }
1166   return nullptr;
1167 }
1168
1169 // Get the limit of a recurrence such that incrementing by Step cannot cause
1170 // unsigned overflow as long as the value of the recurrence within the loop does
1171 // not exceed this limit before incrementing.
1172 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1173                                                    ICmpInst::Predicate *Pred,
1174                                                    ScalarEvolution *SE) {
1175   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1176   *Pred = ICmpInst::ICMP_ULT;
1177
1178   return SE->getConstant(APInt::getMinValue(BitWidth) -
1179                          SE->getUnsignedRange(Step).getUnsignedMax());
1180 }
1181
1182 namespace {
1183
1184 struct ExtendOpTraitsBase {
1185   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1186 };
1187
1188 // Used to make code generic over signed and unsigned overflow.
1189 template <typename ExtendOp> struct ExtendOpTraits {
1190   // Members present:
1191   //
1192   // static const SCEV::NoWrapFlags WrapType;
1193   //
1194   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1195   //
1196   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1197   //                                           ICmpInst::Predicate *Pred,
1198   //                                           ScalarEvolution *SE);
1199 };
1200
1201 template <>
1202 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1203   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1204
1205   static const GetExtendExprTy GetExtendExpr;
1206
1207   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1208                                              ICmpInst::Predicate *Pred,
1209                                              ScalarEvolution *SE) {
1210     return getSignedOverflowLimitForStep(Step, Pred, SE);
1211   }
1212 };
1213
1214 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1215     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1216
1217 template <>
1218 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1219   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1220
1221   static const GetExtendExprTy GetExtendExpr;
1222
1223   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1224                                              ICmpInst::Predicate *Pred,
1225                                              ScalarEvolution *SE) {
1226     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1227   }
1228 };
1229
1230 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1231     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1232 }
1233
1234 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1235 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1236 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1237 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1238 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1239 // expression "Step + sext/zext(PreIncAR)" is congruent with
1240 // "sext/zext(PostIncAR)"
1241 template <typename ExtendOpTy>
1242 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1243                                         ScalarEvolution *SE) {
1244   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1245   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1246
1247   const Loop *L = AR->getLoop();
1248   const SCEV *Start = AR->getStart();
1249   const SCEV *Step = AR->getStepRecurrence(*SE);
1250
1251   // Check for a simple looking step prior to loop entry.
1252   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1253   if (!SA)
1254     return nullptr;
1255
1256   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1257   // subtraction is expensive. For this purpose, perform a quick and dirty
1258   // difference, by checking for Step in the operand list.
1259   SmallVector<const SCEV *, 4> DiffOps;
1260   for (const SCEV *Op : SA->operands())
1261     if (Op != Step)
1262       DiffOps.push_back(Op);
1263
1264   if (DiffOps.size() == SA->getNumOperands())
1265     return nullptr;
1266
1267   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1268   // `Step`:
1269
1270   // 1. NSW/NUW flags on the step increment.
1271   const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
1272   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1273       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1274
1275   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1276   // "S+X does not sign/unsign-overflow".
1277   //
1278
1279   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1280   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1281       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1282     return PreStart;
1283
1284   // 2. Direct overflow check on the step operation's expression.
1285   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1286   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1287   const SCEV *OperandExtendedStart =
1288       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1289                      (SE->*GetExtendExpr)(Step, WideTy));
1290   if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1291     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1292       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1293       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1294       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1295       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1296     }
1297     return PreStart;
1298   }
1299
1300   // 3. Loop precondition.
1301   ICmpInst::Predicate Pred;
1302   const SCEV *OverflowLimit =
1303       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1304
1305   if (OverflowLimit &&
1306       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1307     return PreStart;
1308   }
1309   return nullptr;
1310 }
1311
1312 // Get the normalized zero or sign extended expression for this AddRec's Start.
1313 template <typename ExtendOpTy>
1314 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1315                                         ScalarEvolution *SE) {
1316   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1317
1318   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1319   if (!PreStart)
1320     return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1321
1322   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1323                         (SE->*GetExtendExpr)(PreStart, Ty));
1324 }
1325
1326 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1327 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1328 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1329 //
1330 // Formally:
1331 //
1332 //     {S,+,X} == {S-T,+,X} + T
1333 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1334 //
1335 // If ({S-T,+,X} + T) does not overflow  ... (1)
1336 //
1337 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1338 //
1339 // If {S-T,+,X} does not overflow  ... (2)
1340 //
1341 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1342 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1343 //
1344 // If (S-T)+T does not overflow  ... (3)
1345 //
1346 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1347 //      == {Ext(S),+,Ext(X)} == LHS
1348 //
1349 // Thus, if (1), (2) and (3) are true for some T, then
1350 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1351 //
1352 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1353 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1354 // to check for (1) and (2).
1355 //
1356 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1357 // is `Delta` (defined below).
1358 //
1359 template <typename ExtendOpTy>
1360 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1361                                                 const SCEV *Step,
1362                                                 const Loop *L) {
1363   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1364
1365   // We restrict `Start` to a constant to prevent SCEV from spending too much
1366   // time here.  It is correct (but more expensive) to continue with a
1367   // non-constant `Start` and do a general SCEV subtraction to compute
1368   // `PreStart` below.
1369   //
1370   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1371   if (!StartC)
1372     return false;
1373
1374   APInt StartAI = StartC->getValue()->getValue();
1375
1376   for (unsigned Delta : {-2, -1, 1, 2}) {
1377     const SCEV *PreStart = getConstant(StartAI - Delta);
1378
1379     // Give up if we don't already have the add recurrence we need because
1380     // actually constructing an add recurrence is relatively expensive.
1381     const SCEVAddRecExpr *PreAR = [&]() {
1382       FoldingSetNodeID ID;
1383       ID.AddInteger(scAddRecExpr);
1384       ID.AddPointer(PreStart);
1385       ID.AddPointer(Step);
1386       ID.AddPointer(L);
1387       void *IP = nullptr;
1388       return static_cast<SCEVAddRecExpr *>(
1389           this->UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1390     }();
1391
1392     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1393       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1394       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1395       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1396           DeltaS, &Pred, this);
1397       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1398         return true;
1399     }
1400   }
1401
1402   return false;
1403 }
1404
1405 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1406                                                Type *Ty) {
1407   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1408          "This is not an extending conversion!");
1409   assert(isSCEVable(Ty) &&
1410          "This is not a conversion to a SCEVable type!");
1411   Ty = getEffectiveSCEVType(Ty);
1412
1413   // Fold if the operand is constant.
1414   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1415     return getConstant(
1416       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1417
1418   // zext(zext(x)) --> zext(x)
1419   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1420     return getZeroExtendExpr(SZ->getOperand(), Ty);
1421
1422   // Before doing any expensive analysis, check to see if we've already
1423   // computed a SCEV for this Op and Ty.
1424   FoldingSetNodeID ID;
1425   ID.AddInteger(scZeroExtend);
1426   ID.AddPointer(Op);
1427   ID.AddPointer(Ty);
1428   void *IP = nullptr;
1429   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1430
1431   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1432   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1433     // It's possible the bits taken off by the truncate were all zero bits. If
1434     // so, we should be able to simplify this further.
1435     const SCEV *X = ST->getOperand();
1436     ConstantRange CR = getUnsignedRange(X);
1437     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1438     unsigned NewBits = getTypeSizeInBits(Ty);
1439     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1440             CR.zextOrTrunc(NewBits)))
1441       return getTruncateOrZeroExtend(X, Ty);
1442   }
1443
1444   // If the input value is a chrec scev, and we can prove that the value
1445   // did not overflow the old, smaller, value, we can zero extend all of the
1446   // operands (often constants).  This allows analysis of something like
1447   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1448   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1449     if (AR->isAffine()) {
1450       const SCEV *Start = AR->getStart();
1451       const SCEV *Step = AR->getStepRecurrence(*this);
1452       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1453       const Loop *L = AR->getLoop();
1454
1455       // If we have special knowledge that this addrec won't overflow,
1456       // we don't need to do any further analysis.
1457       if (AR->getNoWrapFlags(SCEV::FlagNUW))
1458         return getAddRecExpr(
1459             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1460             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1461
1462       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1463       // Note that this serves two purposes: It filters out loops that are
1464       // simply not analyzable, and it covers the case where this code is
1465       // being called from within backedge-taken count analysis, such that
1466       // attempting to ask for the backedge-taken count would likely result
1467       // in infinite recursion. In the later case, the analysis code will
1468       // cope with a conservative value, and it will take care to purge
1469       // that value once it has finished.
1470       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1471       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1472         // Manually compute the final value for AR, checking for
1473         // overflow.
1474
1475         // Check whether the backedge-taken count can be losslessly casted to
1476         // the addrec's type. The count is always unsigned.
1477         const SCEV *CastedMaxBECount =
1478           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1479         const SCEV *RecastedMaxBECount =
1480           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1481         if (MaxBECount == RecastedMaxBECount) {
1482           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1483           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1484           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1485           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1486           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1487           const SCEV *WideMaxBECount =
1488             getZeroExtendExpr(CastedMaxBECount, WideTy);
1489           const SCEV *OperandExtendedAdd =
1490             getAddExpr(WideStart,
1491                        getMulExpr(WideMaxBECount,
1492                                   getZeroExtendExpr(Step, WideTy)));
1493           if (ZAdd == OperandExtendedAdd) {
1494             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1495             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1496             // Return the expression with the addrec on the outside.
1497             return getAddRecExpr(
1498                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1499                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1500           }
1501           // Similar to above, only this time treat the step value as signed.
1502           // This covers loops that count down.
1503           OperandExtendedAdd =
1504             getAddExpr(WideStart,
1505                        getMulExpr(WideMaxBECount,
1506                                   getSignExtendExpr(Step, WideTy)));
1507           if (ZAdd == OperandExtendedAdd) {
1508             // Cache knowledge of AR NW, which is propagated to this AddRec.
1509             // Negative step causes unsigned wrap, but it still can't self-wrap.
1510             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1511             // Return the expression with the addrec on the outside.
1512             return getAddRecExpr(
1513                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1514                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1515           }
1516         }
1517
1518         // If the backedge is guarded by a comparison with the pre-inc value
1519         // the addrec is safe. Also, if the entry is guarded by a comparison
1520         // with the start value and the backedge is guarded by a comparison
1521         // with the post-inc value, the addrec is safe.
1522         if (isKnownPositive(Step)) {
1523           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1524                                       getUnsignedRange(Step).getUnsignedMax());
1525           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1526               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1527                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1528                                            AR->getPostIncExpr(*this), N))) {
1529             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1530             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1531             // Return the expression with the addrec on the outside.
1532             return getAddRecExpr(
1533                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1534                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1535           }
1536         } else if (isKnownNegative(Step)) {
1537           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1538                                       getSignedRange(Step).getSignedMin());
1539           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1540               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1541                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1542                                            AR->getPostIncExpr(*this), N))) {
1543             // Cache knowledge of AR NW, which is propagated to this AddRec.
1544             // Negative step causes unsigned wrap, but it still can't self-wrap.
1545             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1546             // Return the expression with the addrec on the outside.
1547             return getAddRecExpr(
1548                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1549                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1550           }
1551         }
1552       }
1553
1554       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1555         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1556         return getAddRecExpr(
1557             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1558             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1559       }
1560     }
1561
1562   // The cast wasn't folded; create an explicit cast node.
1563   // Recompute the insert position, as it may have been invalidated.
1564   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1565   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1566                                                    Op, Ty);
1567   UniqueSCEVs.InsertNode(S, IP);
1568   return S;
1569 }
1570
1571 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1572                                                Type *Ty) {
1573   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1574          "This is not an extending conversion!");
1575   assert(isSCEVable(Ty) &&
1576          "This is not a conversion to a SCEVable type!");
1577   Ty = getEffectiveSCEVType(Ty);
1578
1579   // Fold if the operand is constant.
1580   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1581     return getConstant(
1582       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1583
1584   // sext(sext(x)) --> sext(x)
1585   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1586     return getSignExtendExpr(SS->getOperand(), Ty);
1587
1588   // sext(zext(x)) --> zext(x)
1589   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1590     return getZeroExtendExpr(SZ->getOperand(), Ty);
1591
1592   // Before doing any expensive analysis, check to see if we've already
1593   // computed a SCEV for this Op and Ty.
1594   FoldingSetNodeID ID;
1595   ID.AddInteger(scSignExtend);
1596   ID.AddPointer(Op);
1597   ID.AddPointer(Ty);
1598   void *IP = nullptr;
1599   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1600
1601   // If the input value is provably positive, build a zext instead.
1602   if (isKnownNonNegative(Op))
1603     return getZeroExtendExpr(Op, Ty);
1604
1605   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1606   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1607     // It's possible the bits taken off by the truncate were all sign bits. If
1608     // so, we should be able to simplify this further.
1609     const SCEV *X = ST->getOperand();
1610     ConstantRange CR = getSignedRange(X);
1611     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1612     unsigned NewBits = getTypeSizeInBits(Ty);
1613     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1614             CR.sextOrTrunc(NewBits)))
1615       return getTruncateOrSignExtend(X, Ty);
1616   }
1617
1618   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1619   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1620     if (SA->getNumOperands() == 2) {
1621       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1622       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1623       if (SMul && SC1) {
1624         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1625           const APInt &C1 = SC1->getValue()->getValue();
1626           const APInt &C2 = SC2->getValue()->getValue();
1627           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1628               C2.ugt(C1) && C2.isPowerOf2())
1629             return getAddExpr(getSignExtendExpr(SC1, Ty),
1630                               getSignExtendExpr(SMul, Ty));
1631         }
1632       }
1633     }
1634   }
1635   // If the input value is a chrec scev, and we can prove that the value
1636   // did not overflow the old, smaller, value, we can sign extend all of the
1637   // operands (often constants).  This allows analysis of something like
1638   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1639   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1640     if (AR->isAffine()) {
1641       const SCEV *Start = AR->getStart();
1642       const SCEV *Step = AR->getStepRecurrence(*this);
1643       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1644       const Loop *L = AR->getLoop();
1645
1646       // If we have special knowledge that this addrec won't overflow,
1647       // we don't need to do any further analysis.
1648       if (AR->getNoWrapFlags(SCEV::FlagNSW))
1649         return getAddRecExpr(
1650             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1651             getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1652
1653       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1654       // Note that this serves two purposes: It filters out loops that are
1655       // simply not analyzable, and it covers the case where this code is
1656       // being called from within backedge-taken count analysis, such that
1657       // attempting to ask for the backedge-taken count would likely result
1658       // in infinite recursion. In the later case, the analysis code will
1659       // cope with a conservative value, and it will take care to purge
1660       // that value once it has finished.
1661       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1662       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1663         // Manually compute the final value for AR, checking for
1664         // overflow.
1665
1666         // Check whether the backedge-taken count can be losslessly casted to
1667         // the addrec's type. The count is always unsigned.
1668         const SCEV *CastedMaxBECount =
1669           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1670         const SCEV *RecastedMaxBECount =
1671           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1672         if (MaxBECount == RecastedMaxBECount) {
1673           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1674           // Check whether Start+Step*MaxBECount has no signed overflow.
1675           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1676           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1677           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1678           const SCEV *WideMaxBECount =
1679             getZeroExtendExpr(CastedMaxBECount, WideTy);
1680           const SCEV *OperandExtendedAdd =
1681             getAddExpr(WideStart,
1682                        getMulExpr(WideMaxBECount,
1683                                   getSignExtendExpr(Step, WideTy)));
1684           if (SAdd == OperandExtendedAdd) {
1685             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1686             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1687             // Return the expression with the addrec on the outside.
1688             return getAddRecExpr(
1689                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1690                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1691           }
1692           // Similar to above, only this time treat the step value as unsigned.
1693           // This covers loops that count up with an unsigned step.
1694           OperandExtendedAdd =
1695             getAddExpr(WideStart,
1696                        getMulExpr(WideMaxBECount,
1697                                   getZeroExtendExpr(Step, WideTy)));
1698           if (SAdd == OperandExtendedAdd) {
1699             // If AR wraps around then
1700             //
1701             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1702             // => SAdd != OperandExtendedAdd
1703             //
1704             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1705             // (SAdd == OperandExtendedAdd => AR is NW)
1706
1707             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1708
1709             // Return the expression with the addrec on the outside.
1710             return getAddRecExpr(
1711                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1712                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1713           }
1714         }
1715
1716         // If the backedge is guarded by a comparison with the pre-inc value
1717         // the addrec is safe. Also, if the entry is guarded by a comparison
1718         // with the start value and the backedge is guarded by a comparison
1719         // with the post-inc value, the addrec is safe.
1720         ICmpInst::Predicate Pred;
1721         const SCEV *OverflowLimit =
1722             getSignedOverflowLimitForStep(Step, &Pred, this);
1723         if (OverflowLimit &&
1724             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1725              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1726               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1727                                           OverflowLimit)))) {
1728           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1729           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1730           return getAddRecExpr(
1731               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1732               getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1733         }
1734       }
1735       // If Start and Step are constants, check if we can apply this
1736       // transformation:
1737       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1738       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1739       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1740       if (SC1 && SC2) {
1741         const APInt &C1 = SC1->getValue()->getValue();
1742         const APInt &C2 = SC2->getValue()->getValue();
1743         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1744             C2.isPowerOf2()) {
1745           Start = getSignExtendExpr(Start, Ty);
1746           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1747                                             AR->getNoWrapFlags());
1748           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1749         }
1750       }
1751
1752       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1753         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1754         return getAddRecExpr(
1755             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1756             getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1757       }
1758     }
1759
1760   // The cast wasn't folded; create an explicit cast node.
1761   // Recompute the insert position, as it may have been invalidated.
1762   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1763   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1764                                                    Op, Ty);
1765   UniqueSCEVs.InsertNode(S, IP);
1766   return S;
1767 }
1768
1769 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1770 /// unspecified bits out to the given type.
1771 ///
1772 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1773                                               Type *Ty) {
1774   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1775          "This is not an extending conversion!");
1776   assert(isSCEVable(Ty) &&
1777          "This is not a conversion to a SCEVable type!");
1778   Ty = getEffectiveSCEVType(Ty);
1779
1780   // Sign-extend negative constants.
1781   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1782     if (SC->getValue()->getValue().isNegative())
1783       return getSignExtendExpr(Op, Ty);
1784
1785   // Peel off a truncate cast.
1786   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1787     const SCEV *NewOp = T->getOperand();
1788     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1789       return getAnyExtendExpr(NewOp, Ty);
1790     return getTruncateOrNoop(NewOp, Ty);
1791   }
1792
1793   // Next try a zext cast. If the cast is folded, use it.
1794   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1795   if (!isa<SCEVZeroExtendExpr>(ZExt))
1796     return ZExt;
1797
1798   // Next try a sext cast. If the cast is folded, use it.
1799   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1800   if (!isa<SCEVSignExtendExpr>(SExt))
1801     return SExt;
1802
1803   // Force the cast to be folded into the operands of an addrec.
1804   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1805     SmallVector<const SCEV *, 4> Ops;
1806     for (const SCEV *Op : AR->operands())
1807       Ops.push_back(getAnyExtendExpr(Op, Ty));
1808     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1809   }
1810
1811   // If the expression is obviously signed, use the sext cast value.
1812   if (isa<SCEVSMaxExpr>(Op))
1813     return SExt;
1814
1815   // Absent any other information, use the zext cast value.
1816   return ZExt;
1817 }
1818
1819 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1820 /// a list of operands to be added under the given scale, update the given
1821 /// map. This is a helper function for getAddRecExpr. As an example of
1822 /// what it does, given a sequence of operands that would form an add
1823 /// expression like this:
1824 ///
1825 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1826 ///
1827 /// where A and B are constants, update the map with these values:
1828 ///
1829 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1830 ///
1831 /// and add 13 + A*B*29 to AccumulatedConstant.
1832 /// This will allow getAddRecExpr to produce this:
1833 ///
1834 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1835 ///
1836 /// This form often exposes folding opportunities that are hidden in
1837 /// the original operand list.
1838 ///
1839 /// Return true iff it appears that any interesting folding opportunities
1840 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1841 /// the common case where no interesting opportunities are present, and
1842 /// is also used as a check to avoid infinite recursion.
1843 ///
1844 static bool
1845 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1846                              SmallVectorImpl<const SCEV *> &NewOps,
1847                              APInt &AccumulatedConstant,
1848                              const SCEV *const *Ops, size_t NumOperands,
1849                              const APInt &Scale,
1850                              ScalarEvolution &SE) {
1851   bool Interesting = false;
1852
1853   // Iterate over the add operands. They are sorted, with constants first.
1854   unsigned i = 0;
1855   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1856     ++i;
1857     // Pull a buried constant out to the outside.
1858     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1859       Interesting = true;
1860     AccumulatedConstant += Scale * C->getValue()->getValue();
1861   }
1862
1863   // Next comes everything else. We're especially interested in multiplies
1864   // here, but they're in the middle, so just visit the rest with one loop.
1865   for (; i != NumOperands; ++i) {
1866     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1867     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1868       APInt NewScale =
1869         Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1870       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1871         // A multiplication of a constant with another add; recurse.
1872         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1873         Interesting |=
1874           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1875                                        Add->op_begin(), Add->getNumOperands(),
1876                                        NewScale, SE);
1877       } else {
1878         // A multiplication of a constant with some other value. Update
1879         // the map.
1880         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1881         const SCEV *Key = SE.getMulExpr(MulOps);
1882         auto Pair = M.insert(std::make_pair(Key, NewScale));
1883         if (Pair.second) {
1884           NewOps.push_back(Pair.first->first);
1885         } else {
1886           Pair.first->second += NewScale;
1887           // The map already had an entry for this value, which may indicate
1888           // a folding opportunity.
1889           Interesting = true;
1890         }
1891       }
1892     } else {
1893       // An ordinary operand. Update the map.
1894       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1895         M.insert(std::make_pair(Ops[i], Scale));
1896       if (Pair.second) {
1897         NewOps.push_back(Pair.first->first);
1898       } else {
1899         Pair.first->second += Scale;
1900         // The map already had an entry for this value, which may indicate
1901         // a folding opportunity.
1902         Interesting = true;
1903       }
1904     }
1905   }
1906
1907   return Interesting;
1908 }
1909
1910 namespace {
1911   struct APIntCompare {
1912     bool operator()(const APInt &LHS, const APInt &RHS) const {
1913       return LHS.ult(RHS);
1914     }
1915   };
1916 }
1917
1918 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1919 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
1920 // can't-overflow flags for the operation if possible.
1921 static SCEV::NoWrapFlags
1922 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1923                       const SmallVectorImpl<const SCEV *> &Ops,
1924                       SCEV::NoWrapFlags OldFlags) {
1925   using namespace std::placeholders;
1926
1927   bool CanAnalyze =
1928       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1929   (void)CanAnalyze;
1930   assert(CanAnalyze && "don't call from other places!");
1931
1932   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1933   SCEV::NoWrapFlags SignOrUnsignWrap =
1934       ScalarEvolution::maskFlags(OldFlags, SignOrUnsignMask);
1935
1936   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1937   auto IsKnownNonNegative =
1938     std::bind(std::mem_fn(&ScalarEvolution::isKnownNonNegative), SE, _1);
1939
1940   if (SignOrUnsignWrap == SCEV::FlagNSW &&
1941       std::all_of(Ops.begin(), Ops.end(), IsKnownNonNegative))
1942     return ScalarEvolution::setFlags(OldFlags,
1943                                      (SCEV::NoWrapFlags)SignOrUnsignMask);
1944
1945   return OldFlags;
1946 }
1947
1948 /// getAddExpr - Get a canonical add expression, or something simpler if
1949 /// possible.
1950 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1951                                         SCEV::NoWrapFlags Flags) {
1952   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1953          "only nuw or nsw allowed");
1954   assert(!Ops.empty() && "Cannot get empty add!");
1955   if (Ops.size() == 1) return Ops[0];
1956 #ifndef NDEBUG
1957   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1958   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1959     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1960            "SCEVAddExpr operand types don't match!");
1961 #endif
1962
1963   // Sort by complexity, this groups all similar expression types together.
1964   GroupByComplexity(Ops, &LI);
1965
1966   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
1967
1968   // If there are any constants, fold them together.
1969   unsigned Idx = 0;
1970   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1971     ++Idx;
1972     assert(Idx < Ops.size());
1973     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1974       // We found two constants, fold them together!
1975       Ops[0] = getConstant(LHSC->getValue()->getValue() +
1976                            RHSC->getValue()->getValue());
1977       if (Ops.size() == 2) return Ops[0];
1978       Ops.erase(Ops.begin()+1);  // Erase the folded element
1979       LHSC = cast<SCEVConstant>(Ops[0]);
1980     }
1981
1982     // If we are left with a constant zero being added, strip it off.
1983     if (LHSC->getValue()->isZero()) {
1984       Ops.erase(Ops.begin());
1985       --Idx;
1986     }
1987
1988     if (Ops.size() == 1) return Ops[0];
1989   }
1990
1991   // Okay, check to see if the same value occurs in the operand list more than
1992   // once.  If so, merge them together into an multiply expression.  Since we
1993   // sorted the list, these values are required to be adjacent.
1994   Type *Ty = Ops[0]->getType();
1995   bool FoundMatch = false;
1996   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1997     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
1998       // Scan ahead to count how many equal operands there are.
1999       unsigned Count = 2;
2000       while (i+Count != e && Ops[i+Count] == Ops[i])
2001         ++Count;
2002       // Merge the values into a multiply.
2003       const SCEV *Scale = getConstant(Ty, Count);
2004       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2005       if (Ops.size() == Count)
2006         return Mul;
2007       Ops[i] = Mul;
2008       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2009       --i; e -= Count - 1;
2010       FoundMatch = true;
2011     }
2012   if (FoundMatch)
2013     return getAddExpr(Ops, Flags);
2014
2015   // Check for truncates. If all the operands are truncated from the same
2016   // type, see if factoring out the truncate would permit the result to be
2017   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2018   // if the contents of the resulting outer trunc fold to something simple.
2019   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2020     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2021     Type *DstType = Trunc->getType();
2022     Type *SrcType = Trunc->getOperand()->getType();
2023     SmallVector<const SCEV *, 8> LargeOps;
2024     bool Ok = true;
2025     // Check all the operands to see if they can be represented in the
2026     // source type of the truncate.
2027     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2028       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2029         if (T->getOperand()->getType() != SrcType) {
2030           Ok = false;
2031           break;
2032         }
2033         LargeOps.push_back(T->getOperand());
2034       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2035         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2036       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2037         SmallVector<const SCEV *, 8> LargeMulOps;
2038         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2039           if (const SCEVTruncateExpr *T =
2040                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2041             if (T->getOperand()->getType() != SrcType) {
2042               Ok = false;
2043               break;
2044             }
2045             LargeMulOps.push_back(T->getOperand());
2046           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2047             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2048           } else {
2049             Ok = false;
2050             break;
2051           }
2052         }
2053         if (Ok)
2054           LargeOps.push_back(getMulExpr(LargeMulOps));
2055       } else {
2056         Ok = false;
2057         break;
2058       }
2059     }
2060     if (Ok) {
2061       // Evaluate the expression in the larger type.
2062       const SCEV *Fold = getAddExpr(LargeOps, Flags);
2063       // If it folds to something simple, use it. Otherwise, don't.
2064       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2065         return getTruncateExpr(Fold, DstType);
2066     }
2067   }
2068
2069   // Skip past any other cast SCEVs.
2070   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2071     ++Idx;
2072
2073   // If there are add operands they would be next.
2074   if (Idx < Ops.size()) {
2075     bool DeletedAdd = false;
2076     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2077       // If we have an add, expand the add operands onto the end of the operands
2078       // list.
2079       Ops.erase(Ops.begin()+Idx);
2080       Ops.append(Add->op_begin(), Add->op_end());
2081       DeletedAdd = true;
2082     }
2083
2084     // If we deleted at least one add, we added operands to the end of the list,
2085     // and they are not necessarily sorted.  Recurse to resort and resimplify
2086     // any operands we just acquired.
2087     if (DeletedAdd)
2088       return getAddExpr(Ops);
2089   }
2090
2091   // Skip over the add expression until we get to a multiply.
2092   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2093     ++Idx;
2094
2095   // Check to see if there are any folding opportunities present with
2096   // operands multiplied by constant values.
2097   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2098     uint64_t BitWidth = getTypeSizeInBits(Ty);
2099     DenseMap<const SCEV *, APInt> M;
2100     SmallVector<const SCEV *, 8> NewOps;
2101     APInt AccumulatedConstant(BitWidth, 0);
2102     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2103                                      Ops.data(), Ops.size(),
2104                                      APInt(BitWidth, 1), *this)) {
2105       // Some interesting folding opportunity is present, so its worthwhile to
2106       // re-generate the operands list. Group the operands by constant scale,
2107       // to avoid multiplying by the same constant scale multiple times.
2108       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2109       for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
2110            E = NewOps.end(); I != E; ++I)
2111         MulOpLists[M.find(*I)->second].push_back(*I);
2112       // Re-generate the operands list.
2113       Ops.clear();
2114       if (AccumulatedConstant != 0)
2115         Ops.push_back(getConstant(AccumulatedConstant));
2116       for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
2117            I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
2118         if (I->first != 0)
2119           Ops.push_back(getMulExpr(getConstant(I->first),
2120                                    getAddExpr(I->second)));
2121       if (Ops.empty())
2122         return getZero(Ty);
2123       if (Ops.size() == 1)
2124         return Ops[0];
2125       return getAddExpr(Ops);
2126     }
2127   }
2128
2129   // If we are adding something to a multiply expression, make sure the
2130   // something is not already an operand of the multiply.  If so, merge it into
2131   // the multiply.
2132   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2133     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2134     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2135       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2136       if (isa<SCEVConstant>(MulOpSCEV))
2137         continue;
2138       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2139         if (MulOpSCEV == Ops[AddOp]) {
2140           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2141           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2142           if (Mul->getNumOperands() != 2) {
2143             // If the multiply has more than two operands, we must get the
2144             // Y*Z term.
2145             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2146                                                 Mul->op_begin()+MulOp);
2147             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2148             InnerMul = getMulExpr(MulOps);
2149           }
2150           const SCEV *One = getOne(Ty);
2151           const SCEV *AddOne = getAddExpr(One, InnerMul);
2152           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2153           if (Ops.size() == 2) return OuterMul;
2154           if (AddOp < Idx) {
2155             Ops.erase(Ops.begin()+AddOp);
2156             Ops.erase(Ops.begin()+Idx-1);
2157           } else {
2158             Ops.erase(Ops.begin()+Idx);
2159             Ops.erase(Ops.begin()+AddOp-1);
2160           }
2161           Ops.push_back(OuterMul);
2162           return getAddExpr(Ops);
2163         }
2164
2165       // Check this multiply against other multiplies being added together.
2166       for (unsigned OtherMulIdx = Idx+1;
2167            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2168            ++OtherMulIdx) {
2169         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2170         // If MulOp occurs in OtherMul, we can fold the two multiplies
2171         // together.
2172         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2173              OMulOp != e; ++OMulOp)
2174           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2175             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2176             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2177             if (Mul->getNumOperands() != 2) {
2178               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2179                                                   Mul->op_begin()+MulOp);
2180               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2181               InnerMul1 = getMulExpr(MulOps);
2182             }
2183             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2184             if (OtherMul->getNumOperands() != 2) {
2185               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2186                                                   OtherMul->op_begin()+OMulOp);
2187               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2188               InnerMul2 = getMulExpr(MulOps);
2189             }
2190             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2191             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2192             if (Ops.size() == 2) return OuterMul;
2193             Ops.erase(Ops.begin()+Idx);
2194             Ops.erase(Ops.begin()+OtherMulIdx-1);
2195             Ops.push_back(OuterMul);
2196             return getAddExpr(Ops);
2197           }
2198       }
2199     }
2200   }
2201
2202   // If there are any add recurrences in the operands list, see if any other
2203   // added values are loop invariant.  If so, we can fold them into the
2204   // recurrence.
2205   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2206     ++Idx;
2207
2208   // Scan over all recurrences, trying to fold loop invariants into them.
2209   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2210     // Scan all of the other operands to this add and add them to the vector if
2211     // they are loop invariant w.r.t. the recurrence.
2212     SmallVector<const SCEV *, 8> LIOps;
2213     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2214     const Loop *AddRecLoop = AddRec->getLoop();
2215     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2216       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2217         LIOps.push_back(Ops[i]);
2218         Ops.erase(Ops.begin()+i);
2219         --i; --e;
2220       }
2221
2222     // If we found some loop invariants, fold them into the recurrence.
2223     if (!LIOps.empty()) {
2224       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2225       LIOps.push_back(AddRec->getStart());
2226
2227       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2228                                              AddRec->op_end());
2229       AddRecOps[0] = getAddExpr(LIOps);
2230
2231       // Build the new addrec. Propagate the NUW and NSW flags if both the
2232       // outer add and the inner addrec are guaranteed to have no overflow.
2233       // Always propagate NW.
2234       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2235       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2236
2237       // If all of the other operands were loop invariant, we are done.
2238       if (Ops.size() == 1) return NewRec;
2239
2240       // Otherwise, add the folded AddRec by the non-invariant parts.
2241       for (unsigned i = 0;; ++i)
2242         if (Ops[i] == AddRec) {
2243           Ops[i] = NewRec;
2244           break;
2245         }
2246       return getAddExpr(Ops);
2247     }
2248
2249     // Okay, if there weren't any loop invariants to be folded, check to see if
2250     // there are multiple AddRec's with the same loop induction variable being
2251     // added together.  If so, we can fold them.
2252     for (unsigned OtherIdx = Idx+1;
2253          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2254          ++OtherIdx)
2255       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2256         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2257         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2258                                                AddRec->op_end());
2259         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2260              ++OtherIdx)
2261           if (const SCEVAddRecExpr *OtherAddRec =
2262                 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2263             if (OtherAddRec->getLoop() == AddRecLoop) {
2264               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2265                    i != e; ++i) {
2266                 if (i >= AddRecOps.size()) {
2267                   AddRecOps.append(OtherAddRec->op_begin()+i,
2268                                    OtherAddRec->op_end());
2269                   break;
2270                 }
2271                 AddRecOps[i] = getAddExpr(AddRecOps[i],
2272                                           OtherAddRec->getOperand(i));
2273               }
2274               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2275             }
2276         // Step size has changed, so we cannot guarantee no self-wraparound.
2277         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2278         return getAddExpr(Ops);
2279       }
2280
2281     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2282     // next one.
2283   }
2284
2285   // Okay, it looks like we really DO need an add expr.  Check to see if we
2286   // already have one, otherwise create a new one.
2287   FoldingSetNodeID ID;
2288   ID.AddInteger(scAddExpr);
2289   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2290     ID.AddPointer(Ops[i]);
2291   void *IP = nullptr;
2292   SCEVAddExpr *S =
2293     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2294   if (!S) {
2295     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2296     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2297     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2298                                         O, Ops.size());
2299     UniqueSCEVs.InsertNode(S, IP);
2300   }
2301   S->setNoWrapFlags(Flags);
2302   return S;
2303 }
2304
2305 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2306   uint64_t k = i*j;
2307   if (j > 1 && k / j != i) Overflow = true;
2308   return k;
2309 }
2310
2311 /// Compute the result of "n choose k", the binomial coefficient.  If an
2312 /// intermediate computation overflows, Overflow will be set and the return will
2313 /// be garbage. Overflow is not cleared on absence of overflow.
2314 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2315   // We use the multiplicative formula:
2316   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2317   // At each iteration, we take the n-th term of the numeral and divide by the
2318   // (k-n)th term of the denominator.  This division will always produce an
2319   // integral result, and helps reduce the chance of overflow in the
2320   // intermediate computations. However, we can still overflow even when the
2321   // final result would fit.
2322
2323   if (n == 0 || n == k) return 1;
2324   if (k > n) return 0;
2325
2326   if (k > n/2)
2327     k = n-k;
2328
2329   uint64_t r = 1;
2330   for (uint64_t i = 1; i <= k; ++i) {
2331     r = umul_ov(r, n-(i-1), Overflow);
2332     r /= i;
2333   }
2334   return r;
2335 }
2336
2337 /// Determine if any of the operands in this SCEV are a constant or if
2338 /// any of the add or multiply expressions in this SCEV contain a constant.
2339 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2340   SmallVector<const SCEV *, 4> Ops;
2341   Ops.push_back(StartExpr);
2342   while (!Ops.empty()) {
2343     const SCEV *CurrentExpr = Ops.pop_back_val();
2344     if (isa<SCEVConstant>(*CurrentExpr))
2345       return true;
2346
2347     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2348       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2349       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2350     }
2351   }
2352   return false;
2353 }
2354
2355 /// getMulExpr - Get a canonical multiply expression, or something simpler if
2356 /// possible.
2357 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2358                                         SCEV::NoWrapFlags Flags) {
2359   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2360          "only nuw or nsw allowed");
2361   assert(!Ops.empty() && "Cannot get empty mul!");
2362   if (Ops.size() == 1) return Ops[0];
2363 #ifndef NDEBUG
2364   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2365   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2366     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2367            "SCEVMulExpr operand types don't match!");
2368 #endif
2369
2370   // Sort by complexity, this groups all similar expression types together.
2371   GroupByComplexity(Ops, &LI);
2372
2373   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2374
2375   // If there are any constants, fold them together.
2376   unsigned Idx = 0;
2377   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2378
2379     // C1*(C2+V) -> C1*C2 + C1*V
2380     if (Ops.size() == 2)
2381         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2382           // If any of Add's ops are Adds or Muls with a constant,
2383           // apply this transformation as well.
2384           if (Add->getNumOperands() == 2)
2385             if (containsConstantSomewhere(Add))
2386               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2387                                 getMulExpr(LHSC, Add->getOperand(1)));
2388
2389     ++Idx;
2390     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2391       // We found two constants, fold them together!
2392       ConstantInt *Fold = ConstantInt::get(getContext(),
2393                                            LHSC->getValue()->getValue() *
2394                                            RHSC->getValue()->getValue());
2395       Ops[0] = getConstant(Fold);
2396       Ops.erase(Ops.begin()+1);  // Erase the folded element
2397       if (Ops.size() == 1) return Ops[0];
2398       LHSC = cast<SCEVConstant>(Ops[0]);
2399     }
2400
2401     // If we are left with a constant one being multiplied, strip it off.
2402     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2403       Ops.erase(Ops.begin());
2404       --Idx;
2405     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2406       // If we have a multiply of zero, it will always be zero.
2407       return Ops[0];
2408     } else if (Ops[0]->isAllOnesValue()) {
2409       // If we have a mul by -1 of an add, try distributing the -1 among the
2410       // add operands.
2411       if (Ops.size() == 2) {
2412         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2413           SmallVector<const SCEV *, 4> NewOps;
2414           bool AnyFolded = false;
2415           for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2416                  E = Add->op_end(); I != E; ++I) {
2417             const SCEV *Mul = getMulExpr(Ops[0], *I);
2418             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2419             NewOps.push_back(Mul);
2420           }
2421           if (AnyFolded)
2422             return getAddExpr(NewOps);
2423         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2424           // Negation preserves a recurrence's no self-wrap property.
2425           SmallVector<const SCEV *, 4> Operands;
2426           for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2427                  E = AddRec->op_end(); I != E; ++I) {
2428             Operands.push_back(getMulExpr(Ops[0], *I));
2429           }
2430           return getAddRecExpr(Operands, AddRec->getLoop(),
2431                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2432         }
2433       }
2434     }
2435
2436     if (Ops.size() == 1)
2437       return Ops[0];
2438   }
2439
2440   // Skip over the add expression until we get to a multiply.
2441   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2442     ++Idx;
2443
2444   // If there are mul operands inline them all into this expression.
2445   if (Idx < Ops.size()) {
2446     bool DeletedMul = false;
2447     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2448       // If we have an mul, expand the mul operands onto the end of the operands
2449       // list.
2450       Ops.erase(Ops.begin()+Idx);
2451       Ops.append(Mul->op_begin(), Mul->op_end());
2452       DeletedMul = true;
2453     }
2454
2455     // If we deleted at least one mul, we added operands to the end of the list,
2456     // and they are not necessarily sorted.  Recurse to resort and resimplify
2457     // any operands we just acquired.
2458     if (DeletedMul)
2459       return getMulExpr(Ops);
2460   }
2461
2462   // If there are any add recurrences in the operands list, see if any other
2463   // added values are loop invariant.  If so, we can fold them into the
2464   // recurrence.
2465   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2466     ++Idx;
2467
2468   // Scan over all recurrences, trying to fold loop invariants into them.
2469   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2470     // Scan all of the other operands to this mul and add them to the vector if
2471     // they are loop invariant w.r.t. the recurrence.
2472     SmallVector<const SCEV *, 8> LIOps;
2473     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2474     const Loop *AddRecLoop = AddRec->getLoop();
2475     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2476       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2477         LIOps.push_back(Ops[i]);
2478         Ops.erase(Ops.begin()+i);
2479         --i; --e;
2480       }
2481
2482     // If we found some loop invariants, fold them into the recurrence.
2483     if (!LIOps.empty()) {
2484       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2485       SmallVector<const SCEV *, 4> NewOps;
2486       NewOps.reserve(AddRec->getNumOperands());
2487       const SCEV *Scale = getMulExpr(LIOps);
2488       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2489         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2490
2491       // Build the new addrec. Propagate the NUW and NSW flags if both the
2492       // outer mul and the inner addrec are guaranteed to have no overflow.
2493       //
2494       // No self-wrap cannot be guaranteed after changing the step size, but
2495       // will be inferred if either NUW or NSW is true.
2496       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2497       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2498
2499       // If all of the other operands were loop invariant, we are done.
2500       if (Ops.size() == 1) return NewRec;
2501
2502       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2503       for (unsigned i = 0;; ++i)
2504         if (Ops[i] == AddRec) {
2505           Ops[i] = NewRec;
2506           break;
2507         }
2508       return getMulExpr(Ops);
2509     }
2510
2511     // Okay, if there weren't any loop invariants to be folded, check to see if
2512     // there are multiple AddRec's with the same loop induction variable being
2513     // multiplied together.  If so, we can fold them.
2514
2515     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2516     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2517     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2518     //   ]]],+,...up to x=2n}.
2519     // Note that the arguments to choose() are always integers with values
2520     // known at compile time, never SCEV objects.
2521     //
2522     // The implementation avoids pointless extra computations when the two
2523     // addrec's are of different length (mathematically, it's equivalent to
2524     // an infinite stream of zeros on the right).
2525     bool OpsModified = false;
2526     for (unsigned OtherIdx = Idx+1;
2527          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2528          ++OtherIdx) {
2529       const SCEVAddRecExpr *OtherAddRec =
2530         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2531       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2532         continue;
2533
2534       bool Overflow = false;
2535       Type *Ty = AddRec->getType();
2536       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2537       SmallVector<const SCEV*, 7> AddRecOps;
2538       for (int x = 0, xe = AddRec->getNumOperands() +
2539              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2540         const SCEV *Term = getZero(Ty);
2541         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2542           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2543           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2544                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2545                z < ze && !Overflow; ++z) {
2546             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2547             uint64_t Coeff;
2548             if (LargerThan64Bits)
2549               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2550             else
2551               Coeff = Coeff1*Coeff2;
2552             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2553             const SCEV *Term1 = AddRec->getOperand(y-z);
2554             const SCEV *Term2 = OtherAddRec->getOperand(z);
2555             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2556           }
2557         }
2558         AddRecOps.push_back(Term);
2559       }
2560       if (!Overflow) {
2561         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2562                                               SCEV::FlagAnyWrap);
2563         if (Ops.size() == 2) return NewAddRec;
2564         Ops[Idx] = NewAddRec;
2565         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2566         OpsModified = true;
2567         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2568         if (!AddRec)
2569           break;
2570       }
2571     }
2572     if (OpsModified)
2573       return getMulExpr(Ops);
2574
2575     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2576     // next one.
2577   }
2578
2579   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2580   // already have one, otherwise create a new one.
2581   FoldingSetNodeID ID;
2582   ID.AddInteger(scMulExpr);
2583   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2584     ID.AddPointer(Ops[i]);
2585   void *IP = nullptr;
2586   SCEVMulExpr *S =
2587     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2588   if (!S) {
2589     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2590     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2591     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2592                                         O, Ops.size());
2593     UniqueSCEVs.InsertNode(S, IP);
2594   }
2595   S->setNoWrapFlags(Flags);
2596   return S;
2597 }
2598
2599 /// getUDivExpr - Get a canonical unsigned division expression, or something
2600 /// simpler if possible.
2601 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2602                                          const SCEV *RHS) {
2603   assert(getEffectiveSCEVType(LHS->getType()) ==
2604          getEffectiveSCEVType(RHS->getType()) &&
2605          "SCEVUDivExpr operand types don't match!");
2606
2607   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2608     if (RHSC->getValue()->equalsInt(1))
2609       return LHS;                               // X udiv 1 --> x
2610     // If the denominator is zero, the result of the udiv is undefined. Don't
2611     // try to analyze it, because the resolution chosen here may differ from
2612     // the resolution chosen in other parts of the compiler.
2613     if (!RHSC->getValue()->isZero()) {
2614       // Determine if the division can be folded into the operands of
2615       // its operands.
2616       // TODO: Generalize this to non-constants by using known-bits information.
2617       Type *Ty = LHS->getType();
2618       unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
2619       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2620       // For non-power-of-two values, effectively round the value up to the
2621       // nearest power of two.
2622       if (!RHSC->getValue()->getValue().isPowerOf2())
2623         ++MaxShiftAmt;
2624       IntegerType *ExtTy =
2625         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2626       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2627         if (const SCEVConstant *Step =
2628             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2629           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2630           const APInt &StepInt = Step->getValue()->getValue();
2631           const APInt &DivInt = RHSC->getValue()->getValue();
2632           if (!StepInt.urem(DivInt) &&
2633               getZeroExtendExpr(AR, ExtTy) ==
2634               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2635                             getZeroExtendExpr(Step, ExtTy),
2636                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2637             SmallVector<const SCEV *, 4> Operands;
2638             for (const SCEV *Op : AR->operands())
2639               Operands.push_back(getUDivExpr(Op, RHS));
2640             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2641           }
2642           /// Get a canonical UDivExpr for a recurrence.
2643           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2644           // We can currently only fold X%N if X is constant.
2645           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2646           if (StartC && !DivInt.urem(StepInt) &&
2647               getZeroExtendExpr(AR, ExtTy) ==
2648               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2649                             getZeroExtendExpr(Step, ExtTy),
2650                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2651             const APInt &StartInt = StartC->getValue()->getValue();
2652             const APInt &StartRem = StartInt.urem(StepInt);
2653             if (StartRem != 0)
2654               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2655                                   AR->getLoop(), SCEV::FlagNW);
2656           }
2657         }
2658       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2659       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2660         SmallVector<const SCEV *, 4> Operands;
2661         for (const SCEV *Op : M->operands())
2662           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2663         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2664           // Find an operand that's safely divisible.
2665           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2666             const SCEV *Op = M->getOperand(i);
2667             const SCEV *Div = getUDivExpr(Op, RHSC);
2668             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2669               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2670                                                       M->op_end());
2671               Operands[i] = Div;
2672               return getMulExpr(Operands);
2673             }
2674           }
2675       }
2676       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2677       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2678         SmallVector<const SCEV *, 4> Operands;
2679         for (const SCEV *Op : A->operands())
2680           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2681         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2682           Operands.clear();
2683           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2684             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2685             if (isa<SCEVUDivExpr>(Op) ||
2686                 getMulExpr(Op, RHS) != A->getOperand(i))
2687               break;
2688             Operands.push_back(Op);
2689           }
2690           if (Operands.size() == A->getNumOperands())
2691             return getAddExpr(Operands);
2692         }
2693       }
2694
2695       // Fold if both operands are constant.
2696       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2697         Constant *LHSCV = LHSC->getValue();
2698         Constant *RHSCV = RHSC->getValue();
2699         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2700                                                                    RHSCV)));
2701       }
2702     }
2703   }
2704
2705   FoldingSetNodeID ID;
2706   ID.AddInteger(scUDivExpr);
2707   ID.AddPointer(LHS);
2708   ID.AddPointer(RHS);
2709   void *IP = nullptr;
2710   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2711   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2712                                              LHS, RHS);
2713   UniqueSCEVs.InsertNode(S, IP);
2714   return S;
2715 }
2716
2717 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2718   APInt A = C1->getValue()->getValue().abs();
2719   APInt B = C2->getValue()->getValue().abs();
2720   uint32_t ABW = A.getBitWidth();
2721   uint32_t BBW = B.getBitWidth();
2722
2723   if (ABW > BBW)
2724     B = B.zext(ABW);
2725   else if (ABW < BBW)
2726     A = A.zext(BBW);
2727
2728   return APIntOps::GreatestCommonDivisor(A, B);
2729 }
2730
2731 /// getUDivExactExpr - Get a canonical unsigned division expression, or
2732 /// something simpler if possible. There is no representation for an exact udiv
2733 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2734 /// We can't do this when it's not exact because the udiv may be clearing bits.
2735 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2736                                               const SCEV *RHS) {
2737   // TODO: we could try to find factors in all sorts of things, but for now we
2738   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2739   // end of this file for inspiration.
2740
2741   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2742   if (!Mul)
2743     return getUDivExpr(LHS, RHS);
2744
2745   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2746     // If the mulexpr multiplies by a constant, then that constant must be the
2747     // first element of the mulexpr.
2748     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2749       if (LHSCst == RHSCst) {
2750         SmallVector<const SCEV *, 2> Operands;
2751         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2752         return getMulExpr(Operands);
2753       }
2754
2755       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2756       // that there's a factor provided by one of the other terms. We need to
2757       // check.
2758       APInt Factor = gcd(LHSCst, RHSCst);
2759       if (!Factor.isIntN(1)) {
2760         LHSCst = cast<SCEVConstant>(
2761             getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2762         RHSCst = cast<SCEVConstant>(
2763             getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2764         SmallVector<const SCEV *, 2> Operands;
2765         Operands.push_back(LHSCst);
2766         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2767         LHS = getMulExpr(Operands);
2768         RHS = RHSCst;
2769         Mul = dyn_cast<SCEVMulExpr>(LHS);
2770         if (!Mul)
2771           return getUDivExactExpr(LHS, RHS);
2772       }
2773     }
2774   }
2775
2776   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2777     if (Mul->getOperand(i) == RHS) {
2778       SmallVector<const SCEV *, 2> Operands;
2779       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2780       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2781       return getMulExpr(Operands);
2782     }
2783   }
2784
2785   return getUDivExpr(LHS, RHS);
2786 }
2787
2788 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2789 /// Simplify the expression as much as possible.
2790 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2791                                            const Loop *L,
2792                                            SCEV::NoWrapFlags Flags) {
2793   SmallVector<const SCEV *, 4> Operands;
2794   Operands.push_back(Start);
2795   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2796     if (StepChrec->getLoop() == L) {
2797       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2798       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2799     }
2800
2801   Operands.push_back(Step);
2802   return getAddRecExpr(Operands, L, Flags);
2803 }
2804
2805 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2806 /// Simplify the expression as much as possible.
2807 const SCEV *
2808 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2809                                const Loop *L, SCEV::NoWrapFlags Flags) {
2810   if (Operands.size() == 1) return Operands[0];
2811 #ifndef NDEBUG
2812   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2813   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2814     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2815            "SCEVAddRecExpr operand types don't match!");
2816   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2817     assert(isLoopInvariant(Operands[i], L) &&
2818            "SCEVAddRecExpr operand is not loop-invariant!");
2819 #endif
2820
2821   if (Operands.back()->isZero()) {
2822     Operands.pop_back();
2823     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
2824   }
2825
2826   // It's tempting to want to call getMaxBackedgeTakenCount count here and
2827   // use that information to infer NUW and NSW flags. However, computing a
2828   // BE count requires calling getAddRecExpr, so we may not yet have a
2829   // meaningful BE count at this point (and if we don't, we'd be stuck
2830   // with a SCEVCouldNotCompute as the cached BE count).
2831
2832   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
2833
2834   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2835   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2836     const Loop *NestedLoop = NestedAR->getLoop();
2837     if (L->contains(NestedLoop)
2838             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2839             : (!NestedLoop->contains(L) &&
2840                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
2841       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2842                                                   NestedAR->op_end());
2843       Operands[0] = NestedAR->getStart();
2844       // AddRecs require their operands be loop-invariant with respect to their
2845       // loops. Don't perform this transformation if it would break this
2846       // requirement.
2847       bool AllInvariant = true;
2848       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2849         if (!isLoopInvariant(Operands[i], L)) {
2850           AllInvariant = false;
2851           break;
2852         }
2853       if (AllInvariant) {
2854         // Create a recurrence for the outer loop with the same step size.
2855         //
2856         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2857         // inner recurrence has the same property.
2858         SCEV::NoWrapFlags OuterFlags =
2859           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2860
2861         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2862         AllInvariant = true;
2863         for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2864           if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2865             AllInvariant = false;
2866             break;
2867           }
2868         if (AllInvariant) {
2869           // Ok, both add recurrences are valid after the transformation.
2870           //
2871           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2872           // the outer recurrence has the same property.
2873           SCEV::NoWrapFlags InnerFlags =
2874             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2875           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2876         }
2877       }
2878       // Reset Operands to its original state.
2879       Operands[0] = NestedAR;
2880     }
2881   }
2882
2883   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
2884   // already have one, otherwise create a new one.
2885   FoldingSetNodeID ID;
2886   ID.AddInteger(scAddRecExpr);
2887   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2888     ID.AddPointer(Operands[i]);
2889   ID.AddPointer(L);
2890   void *IP = nullptr;
2891   SCEVAddRecExpr *S =
2892     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2893   if (!S) {
2894     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2895     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2896     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2897                                            O, Operands.size(), L);
2898     UniqueSCEVs.InsertNode(S, IP);
2899   }
2900   S->setNoWrapFlags(Flags);
2901   return S;
2902 }
2903
2904 const SCEV *
2905 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2906                             const SmallVectorImpl<const SCEV *> &IndexExprs,
2907                             bool InBounds) {
2908   // getSCEV(Base)->getType() has the same address space as Base->getType()
2909   // because SCEV::getType() preserves the address space.
2910   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2911   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2912   // instruction to its SCEV, because the Instruction may be guarded by control
2913   // flow and the no-overflow bits may not be valid for the expression in any
2914   // context. This can be fixed similarly to how these flags are handled for
2915   // adds.
2916   SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2917
2918   const SCEV *TotalOffset = getZero(IntPtrTy);
2919   // The address space is unimportant. The first thing we do on CurTy is getting
2920   // its element type.
2921   Type *CurTy = PointerType::getUnqual(PointeeType);
2922   for (const SCEV *IndexExpr : IndexExprs) {
2923     // Compute the (potentially symbolic) offset in bytes for this index.
2924     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2925       // For a struct, add the member offset.
2926       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2927       unsigned FieldNo = Index->getZExtValue();
2928       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2929
2930       // Add the field offset to the running total offset.
2931       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2932
2933       // Update CurTy to the type of the field at Index.
2934       CurTy = STy->getTypeAtIndex(Index);
2935     } else {
2936       // Update CurTy to its element type.
2937       CurTy = cast<SequentialType>(CurTy)->getElementType();
2938       // For an array, add the element offset, explicitly scaled.
2939       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
2940       // Getelementptr indices are signed.
2941       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
2942
2943       // Multiply the index by the element size to compute the element offset.
2944       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
2945
2946       // Add the element offset to the running total offset.
2947       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2948     }
2949   }
2950
2951   // Add the total offset from all the GEP indices to the base.
2952   return getAddExpr(BaseExpr, TotalOffset, Wrap);
2953 }
2954
2955 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2956                                          const SCEV *RHS) {
2957   SmallVector<const SCEV *, 2> Ops;
2958   Ops.push_back(LHS);
2959   Ops.push_back(RHS);
2960   return getSMaxExpr(Ops);
2961 }
2962
2963 const SCEV *
2964 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2965   assert(!Ops.empty() && "Cannot get empty smax!");
2966   if (Ops.size() == 1) return Ops[0];
2967 #ifndef NDEBUG
2968   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2969   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2970     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2971            "SCEVSMaxExpr operand types don't match!");
2972 #endif
2973
2974   // Sort by complexity, this groups all similar expression types together.
2975   GroupByComplexity(Ops, &LI);
2976
2977   // If there are any constants, fold them together.
2978   unsigned Idx = 0;
2979   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2980     ++Idx;
2981     assert(Idx < Ops.size());
2982     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2983       // We found two constants, fold them together!
2984       ConstantInt *Fold = ConstantInt::get(getContext(),
2985                               APIntOps::smax(LHSC->getValue()->getValue(),
2986                                              RHSC->getValue()->getValue()));
2987       Ops[0] = getConstant(Fold);
2988       Ops.erase(Ops.begin()+1);  // Erase the folded element
2989       if (Ops.size() == 1) return Ops[0];
2990       LHSC = cast<SCEVConstant>(Ops[0]);
2991     }
2992
2993     // If we are left with a constant minimum-int, strip it off.
2994     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2995       Ops.erase(Ops.begin());
2996       --Idx;
2997     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2998       // If we have an smax with a constant maximum-int, it will always be
2999       // maximum-int.
3000       return Ops[0];
3001     }
3002
3003     if (Ops.size() == 1) return Ops[0];
3004   }
3005
3006   // Find the first SMax
3007   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3008     ++Idx;
3009
3010   // Check to see if one of the operands is an SMax. If so, expand its operands
3011   // onto our operand list, and recurse to simplify.
3012   if (Idx < Ops.size()) {
3013     bool DeletedSMax = false;
3014     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3015       Ops.erase(Ops.begin()+Idx);
3016       Ops.append(SMax->op_begin(), SMax->op_end());
3017       DeletedSMax = true;
3018     }
3019
3020     if (DeletedSMax)
3021       return getSMaxExpr(Ops);
3022   }
3023
3024   // Okay, check to see if the same value occurs in the operand list twice.  If
3025   // so, delete one.  Since we sorted the list, these values are required to
3026   // be adjacent.
3027   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3028     //  X smax Y smax Y  -->  X smax Y
3029     //  X smax Y         -->  X, if X is always greater than Y
3030     if (Ops[i] == Ops[i+1] ||
3031         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3032       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3033       --i; --e;
3034     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3035       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3036       --i; --e;
3037     }
3038
3039   if (Ops.size() == 1) return Ops[0];
3040
3041   assert(!Ops.empty() && "Reduced smax down to nothing!");
3042
3043   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3044   // already have one, otherwise create a new one.
3045   FoldingSetNodeID ID;
3046   ID.AddInteger(scSMaxExpr);
3047   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3048     ID.AddPointer(Ops[i]);
3049   void *IP = nullptr;
3050   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3051   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3052   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3053   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3054                                              O, Ops.size());
3055   UniqueSCEVs.InsertNode(S, IP);
3056   return S;
3057 }
3058
3059 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3060                                          const SCEV *RHS) {
3061   SmallVector<const SCEV *, 2> Ops;
3062   Ops.push_back(LHS);
3063   Ops.push_back(RHS);
3064   return getUMaxExpr(Ops);
3065 }
3066
3067 const SCEV *
3068 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3069   assert(!Ops.empty() && "Cannot get empty umax!");
3070   if (Ops.size() == 1) return Ops[0];
3071 #ifndef NDEBUG
3072   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3073   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3074     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3075            "SCEVUMaxExpr operand types don't match!");
3076 #endif
3077
3078   // Sort by complexity, this groups all similar expression types together.
3079   GroupByComplexity(Ops, &LI);
3080
3081   // If there are any constants, fold them together.
3082   unsigned Idx = 0;
3083   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3084     ++Idx;
3085     assert(Idx < Ops.size());
3086     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3087       // We found two constants, fold them together!
3088       ConstantInt *Fold = ConstantInt::get(getContext(),
3089                               APIntOps::umax(LHSC->getValue()->getValue(),
3090                                              RHSC->getValue()->getValue()));
3091       Ops[0] = getConstant(Fold);
3092       Ops.erase(Ops.begin()+1);  // Erase the folded element
3093       if (Ops.size() == 1) return Ops[0];
3094       LHSC = cast<SCEVConstant>(Ops[0]);
3095     }
3096
3097     // If we are left with a constant minimum-int, strip it off.
3098     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3099       Ops.erase(Ops.begin());
3100       --Idx;
3101     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3102       // If we have an umax with a constant maximum-int, it will always be
3103       // maximum-int.
3104       return Ops[0];
3105     }
3106
3107     if (Ops.size() == 1) return Ops[0];
3108   }
3109
3110   // Find the first UMax
3111   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3112     ++Idx;
3113
3114   // Check to see if one of the operands is a UMax. If so, expand its operands
3115   // onto our operand list, and recurse to simplify.
3116   if (Idx < Ops.size()) {
3117     bool DeletedUMax = false;
3118     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3119       Ops.erase(Ops.begin()+Idx);
3120       Ops.append(UMax->op_begin(), UMax->op_end());
3121       DeletedUMax = true;
3122     }
3123
3124     if (DeletedUMax)
3125       return getUMaxExpr(Ops);
3126   }
3127
3128   // Okay, check to see if the same value occurs in the operand list twice.  If
3129   // so, delete one.  Since we sorted the list, these values are required to
3130   // be adjacent.
3131   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3132     //  X umax Y umax Y  -->  X umax Y
3133     //  X umax Y         -->  X, if X is always greater than Y
3134     if (Ops[i] == Ops[i+1] ||
3135         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3136       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3137       --i; --e;
3138     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3139       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3140       --i; --e;
3141     }
3142
3143   if (Ops.size() == 1) return Ops[0];
3144
3145   assert(!Ops.empty() && "Reduced umax down to nothing!");
3146
3147   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3148   // already have one, otherwise create a new one.
3149   FoldingSetNodeID ID;
3150   ID.AddInteger(scUMaxExpr);
3151   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3152     ID.AddPointer(Ops[i]);
3153   void *IP = nullptr;
3154   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3155   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3156   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3157   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3158                                              O, Ops.size());
3159   UniqueSCEVs.InsertNode(S, IP);
3160   return S;
3161 }
3162
3163 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3164                                          const SCEV *RHS) {
3165   // ~smax(~x, ~y) == smin(x, y).
3166   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3167 }
3168
3169 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3170                                          const SCEV *RHS) {
3171   // ~umax(~x, ~y) == umin(x, y)
3172   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3173 }
3174
3175 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3176   // We can bypass creating a target-independent
3177   // constant expression and then folding it back into a ConstantInt.
3178   // This is just a compile-time optimization.
3179   return getConstant(IntTy,
3180                      F.getParent()->getDataLayout().getTypeAllocSize(AllocTy));
3181 }
3182
3183 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3184                                              StructType *STy,
3185                                              unsigned FieldNo) {
3186   // We can bypass creating a target-independent
3187   // constant expression and then folding it back into a ConstantInt.
3188   // This is just a compile-time optimization.
3189   return getConstant(
3190       IntTy,
3191       F.getParent()->getDataLayout().getStructLayout(STy)->getElementOffset(
3192           FieldNo));
3193 }
3194
3195 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3196   // Don't attempt to do anything other than create a SCEVUnknown object
3197   // here.  createSCEV only calls getUnknown after checking for all other
3198   // interesting possibilities, and any other code that calls getUnknown
3199   // is doing so in order to hide a value from SCEV canonicalization.
3200
3201   FoldingSetNodeID ID;
3202   ID.AddInteger(scUnknown);
3203   ID.AddPointer(V);
3204   void *IP = nullptr;
3205   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3206     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3207            "Stale SCEVUnknown in uniquing map!");
3208     return S;
3209   }
3210   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3211                                             FirstUnknown);
3212   FirstUnknown = cast<SCEVUnknown>(S);
3213   UniqueSCEVs.InsertNode(S, IP);
3214   return S;
3215 }
3216
3217 //===----------------------------------------------------------------------===//
3218 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3219 //
3220
3221 /// isSCEVable - Test if values of the given type are analyzable within
3222 /// the SCEV framework. This primarily includes integer types, and it
3223 /// can optionally include pointer types if the ScalarEvolution class
3224 /// has access to target-specific information.
3225 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3226   // Integers and pointers are always SCEVable.
3227   return Ty->isIntegerTy() || Ty->isPointerTy();
3228 }
3229
3230 /// getTypeSizeInBits - Return the size in bits of the specified type,
3231 /// for which isSCEVable must return true.
3232 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3233   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3234   return F.getParent()->getDataLayout().getTypeSizeInBits(Ty);
3235 }
3236
3237 /// getEffectiveSCEVType - Return a type with the same bitwidth as
3238 /// the given type and which represents how SCEV will treat the given
3239 /// type, for which isSCEVable must return true. For pointer types,
3240 /// this is the pointer-sized integer type.
3241 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3242   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3243
3244   if (Ty->isIntegerTy()) {
3245     return Ty;
3246   }
3247
3248   // The only other support type is pointer.
3249   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3250   return F.getParent()->getDataLayout().getIntPtrType(Ty);
3251 }
3252
3253 const SCEV *ScalarEvolution::getCouldNotCompute() {
3254   return CouldNotCompute.get();
3255 }
3256
3257 namespace {
3258   // Helper class working with SCEVTraversal to figure out if a SCEV contains
3259   // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3260   // is set iff if find such SCEVUnknown.
3261   //
3262   struct FindInvalidSCEVUnknown {
3263     bool FindOne;
3264     FindInvalidSCEVUnknown() { FindOne = false; }
3265     bool follow(const SCEV *S) {
3266       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3267       case scConstant:
3268         return false;
3269       case scUnknown:
3270         if (!cast<SCEVUnknown>(S)->getValue())
3271           FindOne = true;
3272         return false;
3273       default:
3274         return true;
3275       }
3276     }
3277     bool isDone() const { return FindOne; }
3278   };
3279 }
3280
3281 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3282   FindInvalidSCEVUnknown F;
3283   SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3284   ST.visitAll(S);
3285
3286   return !F.FindOne;
3287 }
3288
3289 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3290 /// expression and create a new one.
3291 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3292   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3293
3294   const SCEV *S = getExistingSCEV(V);
3295   if (S == nullptr) {
3296     S = createSCEV(V);
3297     ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
3298   }
3299   return S;
3300 }
3301
3302 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3303   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3304
3305   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3306   if (I != ValueExprMap.end()) {
3307     const SCEV *S = I->second;
3308     if (checkValidity(S))
3309       return S;
3310     ValueExprMap.erase(I);
3311   }
3312   return nullptr;
3313 }
3314
3315 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3316 ///
3317 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3318                                              SCEV::NoWrapFlags Flags) {
3319   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3320     return getConstant(
3321                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3322
3323   Type *Ty = V->getType();
3324   Ty = getEffectiveSCEVType(Ty);
3325   return getMulExpr(
3326       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3327 }
3328
3329 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3330 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3331   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3332     return getConstant(
3333                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3334
3335   Type *Ty = V->getType();
3336   Ty = getEffectiveSCEVType(Ty);
3337   const SCEV *AllOnes =
3338                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3339   return getMinusSCEV(AllOnes, V);
3340 }
3341
3342 /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
3343 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3344                                           SCEV::NoWrapFlags Flags) {
3345   // Fast path: X - X --> 0.
3346   if (LHS == RHS)
3347     return getZero(LHS->getType());
3348
3349   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3350   // makes it so that we cannot make much use of NUW.
3351   auto AddFlags = SCEV::FlagAnyWrap;
3352   const bool RHSIsNotMinSigned =
3353       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3354   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3355     // Let M be the minimum representable signed value. Then (-1)*RHS
3356     // signed-wraps if and only if RHS is M. That can happen even for
3357     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3358     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3359     // (-1)*RHS, we need to prove that RHS != M.
3360     //
3361     // If LHS is non-negative and we know that LHS - RHS does not
3362     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3363     // either by proving that RHS > M or that LHS >= 0.
3364     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3365       AddFlags = SCEV::FlagNSW;
3366     }
3367   }
3368
3369   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3370   // RHS is NSW and LHS >= 0.
3371   //
3372   // The difficulty here is that the NSW flag may have been proven
3373   // relative to a loop that is to be found in a recurrence in LHS and
3374   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3375   // larger scope than intended.
3376   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3377
3378   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3379 }
3380
3381 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3382 /// input value to the specified type.  If the type must be extended, it is zero
3383 /// extended.
3384 const SCEV *
3385 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3386   Type *SrcTy = V->getType();
3387   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3388          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3389          "Cannot truncate or zero extend with non-integer arguments!");
3390   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3391     return V;  // No conversion
3392   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3393     return getTruncateExpr(V, Ty);
3394   return getZeroExtendExpr(V, Ty);
3395 }
3396
3397 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3398 /// input value to the specified type.  If the type must be extended, it is sign
3399 /// extended.
3400 const SCEV *
3401 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3402                                          Type *Ty) {
3403   Type *SrcTy = V->getType();
3404   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3405          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3406          "Cannot truncate or zero extend with non-integer arguments!");
3407   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3408     return V;  // No conversion
3409   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3410     return getTruncateExpr(V, Ty);
3411   return getSignExtendExpr(V, Ty);
3412 }
3413
3414 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3415 /// input value to the specified type.  If the type must be extended, it is zero
3416 /// extended.  The conversion must not be narrowing.
3417 const SCEV *
3418 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3419   Type *SrcTy = V->getType();
3420   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3421          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3422          "Cannot noop or zero extend with non-integer arguments!");
3423   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3424          "getNoopOrZeroExtend cannot truncate!");
3425   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3426     return V;  // No conversion
3427   return getZeroExtendExpr(V, Ty);
3428 }
3429
3430 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3431 /// input value to the specified type.  If the type must be extended, it is sign
3432 /// extended.  The conversion must not be narrowing.
3433 const SCEV *
3434 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3435   Type *SrcTy = V->getType();
3436   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3437          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3438          "Cannot noop or sign extend with non-integer arguments!");
3439   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3440          "getNoopOrSignExtend cannot truncate!");
3441   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3442     return V;  // No conversion
3443   return getSignExtendExpr(V, Ty);
3444 }
3445
3446 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3447 /// the input value to the specified type. If the type must be extended,
3448 /// it is extended with unspecified bits. The conversion must not be
3449 /// narrowing.
3450 const SCEV *
3451 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3452   Type *SrcTy = V->getType();
3453   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3454          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3455          "Cannot noop or any extend with non-integer arguments!");
3456   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3457          "getNoopOrAnyExtend cannot truncate!");
3458   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3459     return V;  // No conversion
3460   return getAnyExtendExpr(V, Ty);
3461 }
3462
3463 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3464 /// input value to the specified type.  The conversion must not be widening.
3465 const SCEV *
3466 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3467   Type *SrcTy = V->getType();
3468   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3469          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3470          "Cannot truncate or noop with non-integer arguments!");
3471   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3472          "getTruncateOrNoop cannot extend!");
3473   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3474     return V;  // No conversion
3475   return getTruncateExpr(V, Ty);
3476 }
3477
3478 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3479 /// the types using zero-extension, and then perform a umax operation
3480 /// with them.
3481 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3482                                                         const SCEV *RHS) {
3483   const SCEV *PromotedLHS = LHS;
3484   const SCEV *PromotedRHS = RHS;
3485
3486   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3487     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3488   else
3489     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3490
3491   return getUMaxExpr(PromotedLHS, PromotedRHS);
3492 }
3493
3494 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
3495 /// the types using zero-extension, and then perform a umin operation
3496 /// with them.
3497 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3498                                                         const SCEV *RHS) {
3499   const SCEV *PromotedLHS = LHS;
3500   const SCEV *PromotedRHS = RHS;
3501
3502   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3503     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3504   else
3505     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3506
3507   return getUMinExpr(PromotedLHS, PromotedRHS);
3508 }
3509
3510 /// getPointerBase - Transitively follow the chain of pointer-type operands
3511 /// until reaching a SCEV that does not have a single pointer operand. This
3512 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3513 /// but corner cases do exist.
3514 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3515   // A pointer operand may evaluate to a nonpointer expression, such as null.
3516   if (!V->getType()->isPointerTy())
3517     return V;
3518
3519   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3520     return getPointerBase(Cast->getOperand());
3521   }
3522   else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3523     const SCEV *PtrOp = nullptr;
3524     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3525          I != E; ++I) {
3526       if ((*I)->getType()->isPointerTy()) {
3527         // Cannot find the base of an expression with multiple pointer operands.
3528         if (PtrOp)
3529           return V;
3530         PtrOp = *I;
3531       }
3532     }
3533     if (!PtrOp)
3534       return V;
3535     return getPointerBase(PtrOp);
3536   }
3537   return V;
3538 }
3539
3540 /// PushDefUseChildren - Push users of the given Instruction
3541 /// onto the given Worklist.
3542 static void
3543 PushDefUseChildren(Instruction *I,
3544                    SmallVectorImpl<Instruction *> &Worklist) {
3545   // Push the def-use children onto the Worklist stack.
3546   for (User *U : I->users())
3547     Worklist.push_back(cast<Instruction>(U));
3548 }
3549
3550 /// ForgetSymbolicValue - This looks up computed SCEV values for all
3551 /// instructions that depend on the given instruction and removes them from
3552 /// the ValueExprMapType map if they reference SymName. This is used during PHI
3553 /// resolution.
3554 void
3555 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3556   SmallVector<Instruction *, 16> Worklist;
3557   PushDefUseChildren(PN, Worklist);
3558
3559   SmallPtrSet<Instruction *, 8> Visited;
3560   Visited.insert(PN);
3561   while (!Worklist.empty()) {
3562     Instruction *I = Worklist.pop_back_val();
3563     if (!Visited.insert(I).second)
3564       continue;
3565
3566     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3567     if (It != ValueExprMap.end()) {
3568       const SCEV *Old = It->second;
3569
3570       // Short-circuit the def-use traversal if the symbolic name
3571       // ceases to appear in expressions.
3572       if (Old != SymName && !hasOperand(Old, SymName))
3573         continue;
3574
3575       // SCEVUnknown for a PHI either means that it has an unrecognized
3576       // structure, it's a PHI that's in the progress of being computed
3577       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3578       // additional loop trip count information isn't going to change anything.
3579       // In the second case, createNodeForPHI will perform the necessary
3580       // updates on its own when it gets to that point. In the third, we do
3581       // want to forget the SCEVUnknown.
3582       if (!isa<PHINode>(I) ||
3583           !isa<SCEVUnknown>(Old) ||
3584           (I != PN && Old == SymName)) {
3585         forgetMemoizedResults(Old);
3586         ValueExprMap.erase(It);
3587       }
3588     }
3589
3590     PushDefUseChildren(I, Worklist);
3591   }
3592 }
3593
3594 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3595   const Loop *L = LI.getLoopFor(PN->getParent());
3596   if (!L || L->getHeader() != PN->getParent())
3597     return nullptr;
3598
3599   // The loop may have multiple entrances or multiple exits; we can analyze
3600   // this phi as an addrec if it has a unique entry value and a unique
3601   // backedge value.
3602   Value *BEValueV = nullptr, *StartValueV = nullptr;
3603   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3604     Value *V = PN->getIncomingValue(i);
3605     if (L->contains(PN->getIncomingBlock(i))) {
3606       if (!BEValueV) {
3607         BEValueV = V;
3608       } else if (BEValueV != V) {
3609         BEValueV = nullptr;
3610         break;
3611       }
3612     } else if (!StartValueV) {
3613       StartValueV = V;
3614     } else if (StartValueV != V) {
3615       StartValueV = nullptr;
3616       break;
3617     }
3618   }
3619   if (BEValueV && StartValueV) {
3620     // While we are analyzing this PHI node, handle its value symbolically.
3621     const SCEV *SymbolicName = getUnknown(PN);
3622     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3623            "PHI node already processed?");
3624     ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
3625
3626     // Using this symbolic name for the PHI, analyze the value coming around
3627     // the back-edge.
3628     const SCEV *BEValue = getSCEV(BEValueV);
3629
3630     // NOTE: If BEValue is loop invariant, we know that the PHI node just
3631     // has a special value for the first iteration of the loop.
3632
3633     // If the value coming around the backedge is an add with the symbolic
3634     // value we just inserted, then we found a simple induction variable!
3635     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3636       // If there is a single occurrence of the symbolic value, replace it
3637       // with a recurrence.
3638       unsigned FoundIndex = Add->getNumOperands();
3639       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3640         if (Add->getOperand(i) == SymbolicName)
3641           if (FoundIndex == e) {
3642             FoundIndex = i;
3643             break;
3644           }
3645
3646       if (FoundIndex != Add->getNumOperands()) {
3647         // Create an add with everything but the specified operand.
3648         SmallVector<const SCEV *, 8> Ops;
3649         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3650           if (i != FoundIndex)
3651             Ops.push_back(Add->getOperand(i));
3652         const SCEV *Accum = getAddExpr(Ops);
3653
3654         // This is not a valid addrec if the step amount is varying each
3655         // loop iteration, but is not itself an addrec in this loop.
3656         if (isLoopInvariant(Accum, L) ||
3657             (isa<SCEVAddRecExpr>(Accum) &&
3658              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3659           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3660
3661           // If the increment doesn't overflow, then neither the addrec nor
3662           // the post-increment will overflow.
3663           if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3664             if (OBO->getOperand(0) == PN) {
3665               if (OBO->hasNoUnsignedWrap())
3666                 Flags = setFlags(Flags, SCEV::FlagNUW);
3667               if (OBO->hasNoSignedWrap())
3668                 Flags = setFlags(Flags, SCEV::FlagNSW);
3669             }
3670           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3671             // If the increment is an inbounds GEP, then we know the address
3672             // space cannot be wrapped around. We cannot make any guarantee
3673             // about signed or unsigned overflow because pointers are
3674             // unsigned but we may have a negative index from the base
3675             // pointer. We can guarantee that no unsigned wrap occurs if the
3676             // indices form a positive value.
3677             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
3678               Flags = setFlags(Flags, SCEV::FlagNW);
3679
3680               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3681               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3682                 Flags = setFlags(Flags, SCEV::FlagNUW);
3683             }
3684
3685             // We cannot transfer nuw and nsw flags from subtraction
3686             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
3687             // for instance.
3688           }
3689
3690           const SCEV *StartVal = getSCEV(StartValueV);
3691           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3692
3693           // Since the no-wrap flags are on the increment, they apply to the
3694           // post-incremented value as well.
3695           if (isLoopInvariant(Accum, L))
3696             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
3697
3698           // Okay, for the entire analysis of this edge we assumed the PHI
3699           // to be symbolic.  We now need to go back and purge all of the
3700           // entries for the scalars that use the symbolic expression.
3701           ForgetSymbolicName(PN, SymbolicName);
3702           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3703           return PHISCEV;
3704         }
3705       }
3706     } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
3707       // Otherwise, this could be a loop like this:
3708       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
3709       // In this case, j = {1,+,1}  and BEValue is j.
3710       // Because the other in-value of i (0) fits the evolution of BEValue
3711       // i really is an addrec evolution.
3712       if (AddRec->getLoop() == L && AddRec->isAffine()) {
3713         const SCEV *StartVal = getSCEV(StartValueV);
3714
3715         // If StartVal = j.start - j.stride, we can use StartVal as the
3716         // initial step of the addrec evolution.
3717         if (StartVal ==
3718             getMinusSCEV(AddRec->getOperand(0), AddRec->getOperand(1))) {
3719           // FIXME: For constant StartVal, we should be able to infer
3720           // no-wrap flags.
3721           const SCEV *PHISCEV = getAddRecExpr(StartVal, AddRec->getOperand(1),
3722                                               L, SCEV::FlagAnyWrap);
3723
3724           // Okay, for the entire analysis of this edge we assumed the PHI
3725           // to be symbolic.  We now need to go back and purge all of the
3726           // entries for the scalars that use the symbolic expression.
3727           ForgetSymbolicName(PN, SymbolicName);
3728           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3729           return PHISCEV;
3730         }
3731       }
3732     }
3733   }
3734
3735   return nullptr;
3736 }
3737
3738 // Checks if the SCEV S is available at BB.  S is considered available at BB
3739 // if S can be materialized at BB without introducing a fault.
3740 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
3741                                BasicBlock *BB) {
3742   struct CheckAvailable {
3743     bool TraversalDone = false;
3744     bool Available = true;
3745
3746     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
3747     BasicBlock *BB = nullptr;
3748     DominatorTree &DT;
3749
3750     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
3751       : L(L), BB(BB), DT(DT) {}
3752
3753     bool setUnavailable() {
3754       TraversalDone = true;
3755       Available = false;
3756       return false;
3757     }
3758
3759     bool follow(const SCEV *S) {
3760       switch (S->getSCEVType()) {
3761       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
3762       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
3763       // These expressions are available if their operand(s) is/are.
3764       return true;
3765
3766       case scAddRecExpr: {
3767         // We allow add recurrences that are on the loop BB is in, or some
3768         // outer loop.  This guarantees availability because the value of the
3769         // add recurrence at BB is simply the "current" value of the induction
3770         // variable.  We can relax this in the future; for instance an add
3771         // recurrence on a sibling dominating loop is also available at BB.
3772         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
3773         if (L && (ARLoop == L || ARLoop->contains(L)))
3774           return true;
3775
3776         return setUnavailable();
3777       }
3778
3779       case scUnknown: {
3780         // For SCEVUnknown, we check for simple dominance.
3781         const auto *SU = cast<SCEVUnknown>(S);
3782         Value *V = SU->getValue();
3783
3784         if (isa<Argument>(V))
3785           return false;
3786
3787         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
3788           return false;
3789
3790         return setUnavailable();
3791       }
3792
3793       case scUDivExpr:
3794       case scCouldNotCompute:
3795       // We do not try to smart about these at all.
3796       return setUnavailable();
3797       }
3798       llvm_unreachable("switch should be fully covered!");
3799     }
3800
3801     bool isDone() { return TraversalDone; }
3802   };
3803
3804   CheckAvailable CA(L, BB, DT);
3805   SCEVTraversal<CheckAvailable> ST(CA);
3806
3807   ST.visitAll(S);
3808   return CA.Available;
3809 }
3810
3811 // Try to match a control flow sequence that branches out at BI and merges back
3812 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
3813 // match.
3814 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
3815                           Value *&C, Value *&LHS, Value *&RHS) {
3816   C = BI->getCondition();
3817
3818   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
3819   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
3820
3821   if (!LeftEdge.isSingleEdge())
3822     return false;
3823
3824   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
3825
3826   Use &LeftUse = Merge->getOperandUse(0);
3827   Use &RightUse = Merge->getOperandUse(1);
3828
3829   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
3830     LHS = LeftUse;
3831     RHS = RightUse;
3832     return true;
3833   }
3834
3835   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
3836     LHS = RightUse;
3837     RHS = LeftUse;
3838     return true;
3839   }
3840
3841   return false;
3842 }
3843
3844 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
3845   if (PN->getNumIncomingValues() == 2) {
3846     const Loop *L = LI.getLoopFor(PN->getParent());
3847
3848     // Try to match
3849     //
3850     //  br %cond, label %left, label %right
3851     // left:
3852     //  br label %merge
3853     // right:
3854     //  br label %merge
3855     // merge:
3856     //  V = phi [ %x, %left ], [ %y, %right ]
3857     //
3858     // as "select %cond, %x, %y"
3859
3860     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
3861     assert(IDom && "At least the entry block should dominate PN");
3862
3863     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
3864     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
3865
3866     if (BI && BI->isConditional() &&
3867         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
3868         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
3869         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
3870       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
3871   }
3872
3873   return nullptr;
3874 }
3875
3876 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
3877   if (const SCEV *S = createAddRecFromPHI(PN))
3878     return S;
3879
3880   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
3881     return S;
3882
3883   // If the PHI has a single incoming value, follow that value, unless the
3884   // PHI's incoming blocks are in a different loop, in which case doing so
3885   // risks breaking LCSSA form. Instcombine would normally zap these, but
3886   // it doesn't have DominatorTree information, so it may miss cases.
3887   if (Value *V = SimplifyInstruction(PN, F.getParent()->getDataLayout(), &TLI,
3888                                      &DT, &AC))
3889     if (LI.replacementPreservesLCSSAForm(PN, V))
3890       return getSCEV(V);
3891
3892   // If it's not a loop phi, we can't handle it yet.
3893   return getUnknown(PN);
3894 }
3895
3896 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
3897                                                       Value *Cond,
3898                                                       Value *TrueVal,
3899                                                       Value *FalseVal) {
3900   // Handle "constant" branch or select. This can occur for instance when a
3901   // loop pass transforms an inner loop and moves on to process the outer loop.
3902   if (auto *CI = dyn_cast<ConstantInt>(Cond))
3903     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
3904
3905   // Try to match some simple smax or umax patterns.
3906   auto *ICI = dyn_cast<ICmpInst>(Cond);
3907   if (!ICI)
3908     return getUnknown(I);
3909
3910   Value *LHS = ICI->getOperand(0);
3911   Value *RHS = ICI->getOperand(1);
3912
3913   switch (ICI->getPredicate()) {
3914   case ICmpInst::ICMP_SLT:
3915   case ICmpInst::ICMP_SLE:
3916     std::swap(LHS, RHS);
3917   // fall through
3918   case ICmpInst::ICMP_SGT:
3919   case ICmpInst::ICMP_SGE:
3920     // a >s b ? a+x : b+x  ->  smax(a, b)+x
3921     // a >s b ? b+x : a+x  ->  smin(a, b)+x
3922     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
3923       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
3924       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
3925       const SCEV *LA = getSCEV(TrueVal);
3926       const SCEV *RA = getSCEV(FalseVal);
3927       const SCEV *LDiff = getMinusSCEV(LA, LS);
3928       const SCEV *RDiff = getMinusSCEV(RA, RS);
3929       if (LDiff == RDiff)
3930         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3931       LDiff = getMinusSCEV(LA, RS);
3932       RDiff = getMinusSCEV(RA, LS);
3933       if (LDiff == RDiff)
3934         return getAddExpr(getSMinExpr(LS, RS), LDiff);
3935     }
3936     break;
3937   case ICmpInst::ICMP_ULT:
3938   case ICmpInst::ICMP_ULE:
3939     std::swap(LHS, RHS);
3940   // fall through
3941   case ICmpInst::ICMP_UGT:
3942   case ICmpInst::ICMP_UGE:
3943     // a >u b ? a+x : b+x  ->  umax(a, b)+x
3944     // a >u b ? b+x : a+x  ->  umin(a, b)+x
3945     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
3946       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
3947       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
3948       const SCEV *LA = getSCEV(TrueVal);
3949       const SCEV *RA = getSCEV(FalseVal);
3950       const SCEV *LDiff = getMinusSCEV(LA, LS);
3951       const SCEV *RDiff = getMinusSCEV(RA, RS);
3952       if (LDiff == RDiff)
3953         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3954       LDiff = getMinusSCEV(LA, RS);
3955       RDiff = getMinusSCEV(RA, LS);
3956       if (LDiff == RDiff)
3957         return getAddExpr(getUMinExpr(LS, RS), LDiff);
3958     }
3959     break;
3960   case ICmpInst::ICMP_NE:
3961     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
3962     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
3963         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
3964       const SCEV *One = getOne(I->getType());
3965       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
3966       const SCEV *LA = getSCEV(TrueVal);
3967       const SCEV *RA = getSCEV(FalseVal);
3968       const SCEV *LDiff = getMinusSCEV(LA, LS);
3969       const SCEV *RDiff = getMinusSCEV(RA, One);
3970       if (LDiff == RDiff)
3971         return getAddExpr(getUMaxExpr(One, LS), LDiff);
3972     }
3973     break;
3974   case ICmpInst::ICMP_EQ:
3975     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
3976     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
3977         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
3978       const SCEV *One = getOne(I->getType());
3979       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
3980       const SCEV *LA = getSCEV(TrueVal);
3981       const SCEV *RA = getSCEV(FalseVal);
3982       const SCEV *LDiff = getMinusSCEV(LA, One);
3983       const SCEV *RDiff = getMinusSCEV(RA, LS);
3984       if (LDiff == RDiff)
3985         return getAddExpr(getUMaxExpr(One, LS), LDiff);
3986     }
3987     break;
3988   default:
3989     break;
3990   }
3991
3992   return getUnknown(I);
3993 }
3994
3995 /// createNodeForGEP - Expand GEP instructions into add and multiply
3996 /// operations. This allows them to be analyzed by regular SCEV code.
3997 ///
3998 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
3999   Value *Base = GEP->getOperand(0);
4000   // Don't attempt to analyze GEPs over unsized objects.
4001   if (!Base->getType()->getPointerElementType()->isSized())
4002     return getUnknown(GEP);
4003
4004   SmallVector<const SCEV *, 4> IndexExprs;
4005   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4006     IndexExprs.push_back(getSCEV(*Index));
4007   return getGEPExpr(GEP->getSourceElementType(), getSCEV(Base), IndexExprs,
4008                     GEP->isInBounds());
4009 }
4010
4011 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
4012 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
4013 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
4014 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
4015 uint32_t
4016 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4017   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4018     return C->getValue()->getValue().countTrailingZeros();
4019
4020   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4021     return std::min(GetMinTrailingZeros(T->getOperand()),
4022                     (uint32_t)getTypeSizeInBits(T->getType()));
4023
4024   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4025     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4026     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4027              getTypeSizeInBits(E->getType()) : OpRes;
4028   }
4029
4030   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4031     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4032     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4033              getTypeSizeInBits(E->getType()) : OpRes;
4034   }
4035
4036   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4037     // The result is the min of all operands results.
4038     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4039     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4040       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4041     return MinOpRes;
4042   }
4043
4044   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4045     // The result is the sum of all operands results.
4046     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4047     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4048     for (unsigned i = 1, e = M->getNumOperands();
4049          SumOpRes != BitWidth && i != e; ++i)
4050       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
4051                           BitWidth);
4052     return SumOpRes;
4053   }
4054
4055   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4056     // The result is the min of all operands results.
4057     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4058     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4059       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4060     return MinOpRes;
4061   }
4062
4063   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4064     // The result is the min of all operands results.
4065     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4066     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4067       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4068     return MinOpRes;
4069   }
4070
4071   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4072     // The result is the min of all operands results.
4073     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4074     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4075       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4076     return MinOpRes;
4077   }
4078
4079   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4080     // For a SCEVUnknown, ask ValueTracking.
4081     unsigned BitWidth = getTypeSizeInBits(U->getType());
4082     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4083     computeKnownBits(U->getValue(), Zeros, Ones, F.getParent()->getDataLayout(),
4084                      0, &AC, nullptr, &DT);
4085     return Zeros.countTrailingOnes();
4086   }
4087
4088   // SCEVUDivExpr
4089   return 0;
4090 }
4091
4092 /// GetRangeFromMetadata - Helper method to assign a range to V from
4093 /// metadata present in the IR.
4094 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4095   if (Instruction *I = dyn_cast<Instruction>(V)) {
4096     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
4097       ConstantRange TotalRange(
4098           cast<IntegerType>(I->getType())->getBitWidth(), false);
4099
4100       unsigned NumRanges = MD->getNumOperands() / 2;
4101       assert(NumRanges >= 1);
4102
4103       for (unsigned i = 0; i < NumRanges; ++i) {
4104         ConstantInt *Lower =
4105             mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 0));
4106         ConstantInt *Upper =
4107             mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 1));
4108         ConstantRange Range(Lower->getValue(), Upper->getValue());
4109         TotalRange = TotalRange.unionWith(Range);
4110       }
4111
4112       return TotalRange;
4113     }
4114   }
4115
4116   return None;
4117 }
4118
4119 /// getRange - Determine the range for a particular SCEV.  If SignHint is
4120 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4121 /// with a "cleaner" unsigned (resp. signed) representation.
4122 ///
4123 ConstantRange
4124 ScalarEvolution::getRange(const SCEV *S,
4125                           ScalarEvolution::RangeSignHint SignHint) {
4126   DenseMap<const SCEV *, ConstantRange> &Cache =
4127       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4128                                                        : SignedRanges;
4129
4130   // See if we've computed this range already.
4131   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4132   if (I != Cache.end())
4133     return I->second;
4134
4135   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4136     return setRange(C, SignHint, ConstantRange(C->getValue()->getValue()));
4137
4138   unsigned BitWidth = getTypeSizeInBits(S->getType());
4139   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4140
4141   // If the value has known zeros, the maximum value will have those known zeros
4142   // as well.
4143   uint32_t TZ = GetMinTrailingZeros(S);
4144   if (TZ != 0) {
4145     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4146       ConservativeResult =
4147           ConstantRange(APInt::getMinValue(BitWidth),
4148                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4149     else
4150       ConservativeResult = ConstantRange(
4151           APInt::getSignedMinValue(BitWidth),
4152           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4153   }
4154
4155   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4156     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4157     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4158       X = X.add(getRange(Add->getOperand(i), SignHint));
4159     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4160   }
4161
4162   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4163     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4164     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4165       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4166     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4167   }
4168
4169   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4170     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4171     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4172       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4173     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4174   }
4175
4176   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4177     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4178     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4179       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4180     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4181   }
4182
4183   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4184     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4185     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4186     return setRange(UDiv, SignHint,
4187                     ConservativeResult.intersectWith(X.udiv(Y)));
4188   }
4189
4190   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4191     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4192     return setRange(ZExt, SignHint,
4193                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4194   }
4195
4196   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4197     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4198     return setRange(SExt, SignHint,
4199                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4200   }
4201
4202   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4203     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4204     return setRange(Trunc, SignHint,
4205                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4206   }
4207
4208   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4209     // If there's no unsigned wrap, the value will never be less than its
4210     // initial value.
4211     if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
4212       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4213         if (!C->getValue()->isZero())
4214           ConservativeResult =
4215             ConservativeResult.intersectWith(
4216               ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
4217
4218     // If there's no signed wrap, and all the operands have the same sign or
4219     // zero, the value won't ever change sign.
4220     if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
4221       bool AllNonNeg = true;
4222       bool AllNonPos = true;
4223       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4224         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4225         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4226       }
4227       if (AllNonNeg)
4228         ConservativeResult = ConservativeResult.intersectWith(
4229           ConstantRange(APInt(BitWidth, 0),
4230                         APInt::getSignedMinValue(BitWidth)));
4231       else if (AllNonPos)
4232         ConservativeResult = ConservativeResult.intersectWith(
4233           ConstantRange(APInt::getSignedMinValue(BitWidth),
4234                         APInt(BitWidth, 1)));
4235     }
4236
4237     // TODO: non-affine addrec
4238     if (AddRec->isAffine()) {
4239       Type *Ty = AddRec->getType();
4240       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4241       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4242           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4243
4244         // Check for overflow.  This must be done with ConstantRange arithmetic
4245         // because we could be called from within the ScalarEvolution overflow
4246         // checking code.
4247
4248         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
4249         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4250         ConstantRange ZExtMaxBECountRange =
4251             MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4252
4253         const SCEV *Start = AddRec->getStart();
4254         const SCEV *Step = AddRec->getStepRecurrence(*this);
4255         ConstantRange StepSRange = getSignedRange(Step);
4256         ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4257
4258         ConstantRange StartURange = getUnsignedRange(Start);
4259         ConstantRange EndURange =
4260             StartURange.add(MaxBECountRange.multiply(StepSRange));
4261
4262         // Check for unsigned overflow.
4263         ConstantRange ZExtStartURange =
4264             StartURange.zextOrTrunc(BitWidth * 2 + 1);
4265         ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4266         if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4267             ZExtEndURange) {
4268           APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4269                                      EndURange.getUnsignedMin());
4270           APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4271                                      EndURange.getUnsignedMax());
4272           bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4273           if (!IsFullRange)
4274             ConservativeResult =
4275                 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4276         }
4277
4278         ConstantRange StartSRange = getSignedRange(Start);
4279         ConstantRange EndSRange =
4280             StartSRange.add(MaxBECountRange.multiply(StepSRange));
4281
4282         // Check for signed overflow. This must be done with ConstantRange
4283         // arithmetic because we could be called from within the ScalarEvolution
4284         // overflow checking code.
4285         ConstantRange SExtStartSRange =
4286             StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4287         ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4288         if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4289             SExtEndSRange) {
4290           APInt Min = APIntOps::smin(StartSRange.getSignedMin(),
4291                                      EndSRange.getSignedMin());
4292           APInt Max = APIntOps::smax(StartSRange.getSignedMax(),
4293                                      EndSRange.getSignedMax());
4294           bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4295           if (!IsFullRange)
4296             ConservativeResult =
4297                 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4298         }
4299       }
4300     }
4301
4302     return setRange(AddRec, SignHint, ConservativeResult);
4303   }
4304
4305   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4306     // Check if the IR explicitly contains !range metadata.
4307     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4308     if (MDRange.hasValue())
4309       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4310
4311     // Split here to avoid paying the compile-time cost of calling both
4312     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4313     // if needed.
4314     const DataLayout &DL = F.getParent()->getDataLayout();
4315     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4316       // For a SCEVUnknown, ask ValueTracking.
4317       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4318       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4319       if (Ones != ~Zeros + 1)
4320         ConservativeResult =
4321             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4322     } else {
4323       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4324              "generalize as needed!");
4325       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4326       if (NS > 1)
4327         ConservativeResult = ConservativeResult.intersectWith(
4328             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4329                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4330     }
4331
4332     return setRange(U, SignHint, ConservativeResult);
4333   }
4334
4335   return setRange(S, SignHint, ConservativeResult);
4336 }
4337
4338 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
4339   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
4340   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4341
4342   // Return early if there are no flags to propagate to the SCEV.
4343   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4344   if (BinOp->hasNoUnsignedWrap())
4345     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4346   if (BinOp->hasNoSignedWrap())
4347     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4348   if (Flags == SCEV::FlagAnyWrap) {
4349     return SCEV::FlagAnyWrap;
4350   }
4351
4352   // Here we check that BinOp is in the header of the innermost loop
4353   // containing BinOp, since we only deal with instructions in the loop
4354   // header. The actual loop we need to check later will come from an add
4355   // recurrence, but getting that requires computing the SCEV of the operands,
4356   // which can be expensive. This check we can do cheaply to rule out some
4357   // cases early.
4358   Loop *innermostContainingLoop = LI.getLoopFor(BinOp->getParent());
4359   if (innermostContainingLoop == nullptr ||
4360       innermostContainingLoop->getHeader() != BinOp->getParent())
4361     return SCEV::FlagAnyWrap;
4362
4363   // Only proceed if we can prove that BinOp does not yield poison.
4364   if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap;
4365
4366   // At this point we know that if V is executed, then it does not wrap
4367   // according to at least one of NSW or NUW. If V is not executed, then we do
4368   // not know if the calculation that V represents would wrap. Multiple
4369   // instructions can map to the same SCEV. If we apply NSW or NUW from V to
4370   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4371   // derived from other instructions that map to the same SCEV. We cannot make
4372   // that guarantee for cases where V is not executed. So we need to find the
4373   // loop that V is considered in relation to and prove that V is executed for
4374   // every iteration of that loop. That implies that the value that V
4375   // calculates does not wrap anywhere in the loop, so then we can apply the
4376   // flags to the SCEV.
4377   //
4378   // We check isLoopInvariant to disambiguate in case we are adding two
4379   // recurrences from different loops, so that we know which loop to prove
4380   // that V is executed in.
4381   for (int OpIndex = 0; OpIndex < 2; ++OpIndex) {
4382     const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex));
4383     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4384       const int OtherOpIndex = 1 - OpIndex;
4385       const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex));
4386       if (isLoopInvariant(OtherOp, AddRec->getLoop()) &&
4387           isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop()))
4388         return Flags;
4389     }
4390   }
4391   return SCEV::FlagAnyWrap;
4392 }
4393
4394 /// createSCEV - We know that there is no SCEV for the specified value.  Analyze
4395 /// the expression.
4396 ///
4397 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4398   if (!isSCEVable(V->getType()))
4399     return getUnknown(V);
4400
4401   unsigned Opcode = Instruction::UserOp1;
4402   if (Instruction *I = dyn_cast<Instruction>(V)) {
4403     Opcode = I->getOpcode();
4404
4405     // Don't attempt to analyze instructions in blocks that aren't
4406     // reachable. Such instructions don't matter, and they aren't required
4407     // to obey basic rules for definitions dominating uses which this
4408     // analysis depends on.
4409     if (!DT.isReachableFromEntry(I->getParent()))
4410       return getUnknown(V);
4411   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
4412     Opcode = CE->getOpcode();
4413   else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4414     return getConstant(CI);
4415   else if (isa<ConstantPointerNull>(V))
4416     return getZero(V->getType());
4417   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4418     return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
4419   else
4420     return getUnknown(V);
4421
4422   Operator *U = cast<Operator>(V);
4423   switch (Opcode) {
4424   case Instruction::Add: {
4425     // The simple thing to do would be to just call getSCEV on both operands
4426     // and call getAddExpr with the result. However if we're looking at a
4427     // bunch of things all added together, this can be quite inefficient,
4428     // because it leads to N-1 getAddExpr calls for N ultimate operands.
4429     // Instead, gather up all the operands and make a single getAddExpr call.
4430     // LLVM IR canonical form means we need only traverse the left operands.
4431     SmallVector<const SCEV *, 4> AddOps;
4432     for (Value *Op = U;; Op = U->getOperand(0)) {
4433       U = dyn_cast<Operator>(Op);
4434       unsigned Opcode = U ? U->getOpcode() : 0;
4435       if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) {
4436         assert(Op != V && "V should be an add");
4437         AddOps.push_back(getSCEV(Op));
4438         break;
4439       }
4440
4441       if (auto *OpSCEV = getExistingSCEV(U)) {
4442         AddOps.push_back(OpSCEV);
4443         break;
4444       }
4445
4446       // If a NUW or NSW flag can be applied to the SCEV for this
4447       // addition, then compute the SCEV for this addition by itself
4448       // with a separate call to getAddExpr. We need to do that
4449       // instead of pushing the operands of the addition onto AddOps,
4450       // since the flags are only known to apply to this particular
4451       // addition - they may not apply to other additions that can be
4452       // formed with operands from AddOps.
4453       const SCEV *RHS = getSCEV(U->getOperand(1));
4454       SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4455       if (Flags != SCEV::FlagAnyWrap) {
4456         const SCEV *LHS = getSCEV(U->getOperand(0));
4457         if (Opcode == Instruction::Sub)
4458           AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
4459         else
4460           AddOps.push_back(getAddExpr(LHS, RHS, Flags));
4461         break;
4462       }
4463
4464       if (Opcode == Instruction::Sub)
4465         AddOps.push_back(getNegativeSCEV(RHS));
4466       else
4467         AddOps.push_back(RHS);
4468     }
4469     return getAddExpr(AddOps);
4470   }
4471
4472   case Instruction::Mul: {
4473     SmallVector<const SCEV *, 4> MulOps;
4474     for (Value *Op = U;; Op = U->getOperand(0)) {
4475       U = dyn_cast<Operator>(Op);
4476       if (!U || U->getOpcode() != Instruction::Mul) {
4477         assert(Op != V && "V should be a mul");
4478         MulOps.push_back(getSCEV(Op));
4479         break;
4480       }
4481
4482       if (auto *OpSCEV = getExistingSCEV(U)) {
4483         MulOps.push_back(OpSCEV);
4484         break;
4485       }
4486
4487       SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4488       if (Flags != SCEV::FlagAnyWrap) {
4489         MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)),
4490                                     getSCEV(U->getOperand(1)), Flags));
4491         break;
4492       }
4493
4494       MulOps.push_back(getSCEV(U->getOperand(1)));
4495     }
4496     return getMulExpr(MulOps);
4497   }
4498   case Instruction::UDiv:
4499     return getUDivExpr(getSCEV(U->getOperand(0)),
4500                        getSCEV(U->getOperand(1)));
4501   case Instruction::Sub:
4502     return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)),
4503                         getNoWrapFlagsFromUB(U));
4504   case Instruction::And:
4505     // For an expression like x&255 that merely masks off the high bits,
4506     // use zext(trunc(x)) as the SCEV expression.
4507     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4508       if (CI->isNullValue())
4509         return getSCEV(U->getOperand(1));
4510       if (CI->isAllOnesValue())
4511         return getSCEV(U->getOperand(0));
4512       const APInt &A = CI->getValue();
4513
4514       // Instcombine's ShrinkDemandedConstant may strip bits out of
4515       // constants, obscuring what would otherwise be a low-bits mask.
4516       // Use computeKnownBits to compute what ShrinkDemandedConstant
4517       // knew about to reconstruct a low-bits mask value.
4518       unsigned LZ = A.countLeadingZeros();
4519       unsigned TZ = A.countTrailingZeros();
4520       unsigned BitWidth = A.getBitWidth();
4521       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4522       computeKnownBits(U->getOperand(0), KnownZero, KnownOne,
4523                        F.getParent()->getDataLayout(), 0, &AC, nullptr, &DT);
4524
4525       APInt EffectiveMask =
4526           APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4527       if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4528         const SCEV *MulCount = getConstant(
4529             ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4530         return getMulExpr(
4531             getZeroExtendExpr(
4532                 getTruncateExpr(
4533                     getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4534                     IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4535                 U->getType()),
4536             MulCount);
4537       }
4538     }
4539     break;
4540
4541   case Instruction::Or:
4542     // If the RHS of the Or is a constant, we may have something like:
4543     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
4544     // optimizations will transparently handle this case.
4545     //
4546     // In order for this transformation to be safe, the LHS must be of the
4547     // form X*(2^n) and the Or constant must be less than 2^n.
4548     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4549       const SCEV *LHS = getSCEV(U->getOperand(0));
4550       const APInt &CIVal = CI->getValue();
4551       if (GetMinTrailingZeros(LHS) >=
4552           (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4553         // Build a plain add SCEV.
4554         const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4555         // If the LHS of the add was an addrec and it has no-wrap flags,
4556         // transfer the no-wrap flags, since an or won't introduce a wrap.
4557         if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4558           const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
4559           const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4560             OldAR->getNoWrapFlags());
4561         }
4562         return S;
4563       }
4564     }
4565     break;
4566   case Instruction::Xor:
4567     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4568       // If the RHS of the xor is a signbit, then this is just an add.
4569       // Instcombine turns add of signbit into xor as a strength reduction step.
4570       if (CI->getValue().isSignBit())
4571         return getAddExpr(getSCEV(U->getOperand(0)),
4572                           getSCEV(U->getOperand(1)));
4573
4574       // If the RHS of xor is -1, then this is a not operation.
4575       if (CI->isAllOnesValue())
4576         return getNotSCEV(getSCEV(U->getOperand(0)));
4577
4578       // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4579       // This is a variant of the check for xor with -1, and it handles
4580       // the case where instcombine has trimmed non-demanded bits out
4581       // of an xor with -1.
4582       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4583         if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4584           if (BO->getOpcode() == Instruction::And &&
4585               LCI->getValue() == CI->getValue())
4586             if (const SCEVZeroExtendExpr *Z =
4587                   dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
4588               Type *UTy = U->getType();
4589               const SCEV *Z0 = Z->getOperand();
4590               Type *Z0Ty = Z0->getType();
4591               unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4592
4593               // If C is a low-bits mask, the zero extend is serving to
4594               // mask off the high bits. Complement the operand and
4595               // re-apply the zext.
4596               if (APIntOps::isMask(Z0TySize, CI->getValue()))
4597                 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4598
4599               // If C is a single bit, it may be in the sign-bit position
4600               // before the zero-extend. In this case, represent the xor
4601               // using an add, which is equivalent, and re-apply the zext.
4602               APInt Trunc = CI->getValue().trunc(Z0TySize);
4603               if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
4604                   Trunc.isSignBit())
4605                 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4606                                          UTy);
4607             }
4608     }
4609     break;
4610
4611   case Instruction::Shl:
4612     // Turn shift left of a constant amount into a multiply.
4613     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4614       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4615
4616       // If the shift count is not less than the bitwidth, the result of
4617       // the shift is undefined. Don't try to analyze it, because the
4618       // resolution chosen here may differ from the resolution chosen in
4619       // other parts of the compiler.
4620       if (SA->getValue().uge(BitWidth))
4621         break;
4622
4623       // It is currently not resolved how to interpret NSW for left
4624       // shift by BitWidth - 1, so we avoid applying flags in that
4625       // case. Remove this check (or this comment) once the situation
4626       // is resolved. See
4627       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
4628       // and http://reviews.llvm.org/D8890 .
4629       auto Flags = SCEV::FlagAnyWrap;
4630       if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U);
4631
4632       Constant *X = ConstantInt::get(getContext(),
4633         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4634       return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags);
4635     }
4636     break;
4637
4638   case Instruction::LShr:
4639     // Turn logical shift right of a constant into a unsigned divide.
4640     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4641       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4642
4643       // If the shift count is not less than the bitwidth, the result of
4644       // the shift is undefined. Don't try to analyze it, because the
4645       // resolution chosen here may differ from the resolution chosen in
4646       // other parts of the compiler.
4647       if (SA->getValue().uge(BitWidth))
4648         break;
4649
4650       Constant *X = ConstantInt::get(getContext(),
4651         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4652       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4653     }
4654     break;
4655
4656   case Instruction::AShr:
4657     // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4658     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
4659       if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
4660         if (L->getOpcode() == Instruction::Shl &&
4661             L->getOperand(1) == U->getOperand(1)) {
4662           uint64_t BitWidth = getTypeSizeInBits(U->getType());
4663
4664           // If the shift count is not less than the bitwidth, the result of
4665           // the shift is undefined. Don't try to analyze it, because the
4666           // resolution chosen here may differ from the resolution chosen in
4667           // other parts of the compiler.
4668           if (CI->getValue().uge(BitWidth))
4669             break;
4670
4671           uint64_t Amt = BitWidth - CI->getZExtValue();
4672           if (Amt == BitWidth)
4673             return getSCEV(L->getOperand(0));       // shift by zero --> noop
4674           return
4675             getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
4676                                               IntegerType::get(getContext(),
4677                                                                Amt)),
4678                               U->getType());
4679         }
4680     break;
4681
4682   case Instruction::Trunc:
4683     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
4684
4685   case Instruction::ZExt:
4686     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4687
4688   case Instruction::SExt:
4689     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4690
4691   case Instruction::BitCast:
4692     // BitCasts are no-op casts so we just eliminate the cast.
4693     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
4694       return getSCEV(U->getOperand(0));
4695     break;
4696
4697   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4698   // lead to pointer expressions which cannot safely be expanded to GEPs,
4699   // because ScalarEvolution doesn't respect the GEP aliasing rules when
4700   // simplifying integer expressions.
4701
4702   case Instruction::GetElementPtr:
4703     return createNodeForGEP(cast<GEPOperator>(U));
4704
4705   case Instruction::PHI:
4706     return createNodeForPHI(cast<PHINode>(U));
4707
4708   case Instruction::Select:
4709     // U can also be a select constant expr, which let fall through.  Since
4710     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
4711     // constant expressions cannot have instructions as operands, we'd have
4712     // returned getUnknown for a select constant expressions anyway.
4713     if (isa<Instruction>(U))
4714       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
4715                                       U->getOperand(1), U->getOperand(2));
4716
4717   default: // We cannot analyze this expression.
4718     break;
4719   }
4720
4721   return getUnknown(V);
4722 }
4723
4724
4725
4726 //===----------------------------------------------------------------------===//
4727 //                   Iteration Count Computation Code
4728 //
4729
4730 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4731   if (BasicBlock *ExitingBB = L->getExitingBlock())
4732     return getSmallConstantTripCount(L, ExitingBB);
4733
4734   // No trip count information for multiple exits.
4735   return 0;
4736 }
4737
4738 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
4739 /// normal unsigned value. Returns 0 if the trip count is unknown or not
4740 /// constant. Will also return 0 if the maximum trip count is very large (>=
4741 /// 2^32).
4742 ///
4743 /// This "trip count" assumes that control exits via ExitingBlock. More
4744 /// precisely, it is the number of times that control may reach ExitingBlock
4745 /// before taking the branch. For loops with multiple exits, it may not be the
4746 /// number times that the loop header executes because the loop may exit
4747 /// prematurely via another branch.
4748 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4749                                                     BasicBlock *ExitingBlock) {
4750   assert(ExitingBlock && "Must pass a non-null exiting block!");
4751   assert(L->isLoopExiting(ExitingBlock) &&
4752          "Exiting block must actually branch out of the loop!");
4753   const SCEVConstant *ExitCount =
4754       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
4755   if (!ExitCount)
4756     return 0;
4757
4758   ConstantInt *ExitConst = ExitCount->getValue();
4759
4760   // Guard against huge trip counts.
4761   if (ExitConst->getValue().getActiveBits() > 32)
4762     return 0;
4763
4764   // In case of integer overflow, this returns 0, which is correct.
4765   return ((unsigned)ExitConst->getZExtValue()) + 1;
4766 }
4767
4768 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4769   if (BasicBlock *ExitingBB = L->getExitingBlock())
4770     return getSmallConstantTripMultiple(L, ExitingBB);
4771
4772   // No trip multiple information for multiple exits.
4773   return 0;
4774 }
4775
4776 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4777 /// trip count of this loop as a normal unsigned value, if possible. This
4778 /// means that the actual trip count is always a multiple of the returned
4779 /// value (don't forget the trip count could very well be zero as well!).
4780 ///
4781 /// Returns 1 if the trip count is unknown or not guaranteed to be the
4782 /// multiple of a constant (which is also the case if the trip count is simply
4783 /// constant, use getSmallConstantTripCount for that case), Will also return 1
4784 /// if the trip count is very large (>= 2^32).
4785 ///
4786 /// As explained in the comments for getSmallConstantTripCount, this assumes
4787 /// that control exits the loop via ExitingBlock.
4788 unsigned
4789 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4790                                               BasicBlock *ExitingBlock) {
4791   assert(ExitingBlock && "Must pass a non-null exiting block!");
4792   assert(L->isLoopExiting(ExitingBlock) &&
4793          "Exiting block must actually branch out of the loop!");
4794   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
4795   if (ExitCount == getCouldNotCompute())
4796     return 1;
4797
4798   // Get the trip count from the BE count by adding 1.
4799   const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
4800   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4801   // to factor simple cases.
4802   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4803     TCMul = Mul->getOperand(0);
4804
4805   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4806   if (!MulC)
4807     return 1;
4808
4809   ConstantInt *Result = MulC->getValue();
4810
4811   // Guard against huge trip counts (this requires checking
4812   // for zero to handle the case where the trip count == -1 and the
4813   // addition wraps).
4814   if (!Result || Result->getValue().getActiveBits() > 32 ||
4815       Result->getValue().getActiveBits() == 0)
4816     return 1;
4817
4818   return (unsigned)Result->getZExtValue();
4819 }
4820
4821 // getExitCount - Get the expression for the number of loop iterations for which
4822 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
4823 // SCEVCouldNotCompute.
4824 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4825   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
4826 }
4827
4828 /// getBackedgeTakenCount - If the specified loop has a predictable
4829 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4830 /// object. The backedge-taken count is the number of times the loop header
4831 /// will be branched to from within the loop. This is one less than the
4832 /// trip count of the loop, since it doesn't count the first iteration,
4833 /// when the header is branched to from outside the loop.
4834 ///
4835 /// Note that it is not valid to call this method on a loop without a
4836 /// loop-invariant backedge-taken count (see
4837 /// hasLoopInvariantBackedgeTakenCount).
4838 ///
4839 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
4840   return getBackedgeTakenInfo(L).getExact(this);
4841 }
4842
4843 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4844 /// return the least SCEV value that is known never to be less than the
4845 /// actual backedge taken count.
4846 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
4847   return getBackedgeTakenInfo(L).getMax(this);
4848 }
4849
4850 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
4851 /// onto the given Worklist.
4852 static void
4853 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4854   BasicBlock *Header = L->getHeader();
4855
4856   // Push all Loop-header PHIs onto the Worklist stack.
4857   for (BasicBlock::iterator I = Header->begin();
4858        PHINode *PN = dyn_cast<PHINode>(I); ++I)
4859     Worklist.push_back(PN);
4860 }
4861
4862 const ScalarEvolution::BackedgeTakenInfo &
4863 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
4864   // Initially insert an invalid entry for this loop. If the insertion
4865   // succeeds, proceed to actually compute a backedge-taken count and
4866   // update the value. The temporary CouldNotCompute value tells SCEV
4867   // code elsewhere that it shouldn't attempt to request a new
4868   // backedge-taken count, which could result in infinite recursion.
4869   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
4870     BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
4871   if (!Pair.second)
4872     return Pair.first->second;
4873
4874   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
4875   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4876   // must be cleared in this scope.
4877   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
4878
4879   if (Result.getExact(this) != getCouldNotCompute()) {
4880     assert(isLoopInvariant(Result.getExact(this), L) &&
4881            isLoopInvariant(Result.getMax(this), L) &&
4882            "Computed backedge-taken count isn't loop invariant for loop!");
4883     ++NumTripCountsComputed;
4884   }
4885   else if (Result.getMax(this) == getCouldNotCompute() &&
4886            isa<PHINode>(L->getHeader()->begin())) {
4887     // Only count loops that have phi nodes as not being computable.
4888     ++NumTripCountsNotComputed;
4889   }
4890
4891   // Now that we know more about the trip count for this loop, forget any
4892   // existing SCEV values for PHI nodes in this loop since they are only
4893   // conservative estimates made without the benefit of trip count
4894   // information. This is similar to the code in forgetLoop, except that
4895   // it handles SCEVUnknown PHI nodes specially.
4896   if (Result.hasAnyInfo()) {
4897     SmallVector<Instruction *, 16> Worklist;
4898     PushLoopPHIs(L, Worklist);
4899
4900     SmallPtrSet<Instruction *, 8> Visited;
4901     while (!Worklist.empty()) {
4902       Instruction *I = Worklist.pop_back_val();
4903       if (!Visited.insert(I).second)
4904         continue;
4905
4906       ValueExprMapType::iterator It =
4907         ValueExprMap.find_as(static_cast<Value *>(I));
4908       if (It != ValueExprMap.end()) {
4909         const SCEV *Old = It->second;
4910
4911         // SCEVUnknown for a PHI either means that it has an unrecognized
4912         // structure, or it's a PHI that's in the progress of being computed
4913         // by createNodeForPHI.  In the former case, additional loop trip
4914         // count information isn't going to change anything. In the later
4915         // case, createNodeForPHI will perform the necessary updates on its
4916         // own when it gets to that point.
4917         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4918           forgetMemoizedResults(Old);
4919           ValueExprMap.erase(It);
4920         }
4921         if (PHINode *PN = dyn_cast<PHINode>(I))
4922           ConstantEvolutionLoopExitValue.erase(PN);
4923       }
4924
4925       PushDefUseChildren(I, Worklist);
4926     }
4927   }
4928
4929   // Re-lookup the insert position, since the call to
4930   // computeBackedgeTakenCount above could result in a
4931   // recusive call to getBackedgeTakenInfo (on a different
4932   // loop), which would invalidate the iterator computed
4933   // earlier.
4934   return BackedgeTakenCounts.find(L)->second = Result;
4935 }
4936
4937 /// forgetLoop - This method should be called by the client when it has
4938 /// changed a loop in a way that may effect ScalarEvolution's ability to
4939 /// compute a trip count, or if the loop is deleted.
4940 void ScalarEvolution::forgetLoop(const Loop *L) {
4941   // Drop any stored trip count value.
4942   DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4943     BackedgeTakenCounts.find(L);
4944   if (BTCPos != BackedgeTakenCounts.end()) {
4945     BTCPos->second.clear();
4946     BackedgeTakenCounts.erase(BTCPos);
4947   }
4948
4949   // Drop information about expressions based on loop-header PHIs.
4950   SmallVector<Instruction *, 16> Worklist;
4951   PushLoopPHIs(L, Worklist);
4952
4953   SmallPtrSet<Instruction *, 8> Visited;
4954   while (!Worklist.empty()) {
4955     Instruction *I = Worklist.pop_back_val();
4956     if (!Visited.insert(I).second)
4957       continue;
4958
4959     ValueExprMapType::iterator It =
4960       ValueExprMap.find_as(static_cast<Value *>(I));
4961     if (It != ValueExprMap.end()) {
4962       forgetMemoizedResults(It->second);
4963       ValueExprMap.erase(It);
4964       if (PHINode *PN = dyn_cast<PHINode>(I))
4965         ConstantEvolutionLoopExitValue.erase(PN);
4966     }
4967
4968     PushDefUseChildren(I, Worklist);
4969   }
4970
4971   // Forget all contained loops too, to avoid dangling entries in the
4972   // ValuesAtScopes map.
4973   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4974     forgetLoop(*I);
4975 }
4976
4977 /// forgetValue - This method should be called by the client when it has
4978 /// changed a value in a way that may effect its value, or which may
4979 /// disconnect it from a def-use chain linking it to a loop.
4980 void ScalarEvolution::forgetValue(Value *V) {
4981   Instruction *I = dyn_cast<Instruction>(V);
4982   if (!I) return;
4983
4984   // Drop information about expressions based on loop-header PHIs.
4985   SmallVector<Instruction *, 16> Worklist;
4986   Worklist.push_back(I);
4987
4988   SmallPtrSet<Instruction *, 8> Visited;
4989   while (!Worklist.empty()) {
4990     I = Worklist.pop_back_val();
4991     if (!Visited.insert(I).second)
4992       continue;
4993
4994     ValueExprMapType::iterator It =
4995       ValueExprMap.find_as(static_cast<Value *>(I));
4996     if (It != ValueExprMap.end()) {
4997       forgetMemoizedResults(It->second);
4998       ValueExprMap.erase(It);
4999       if (PHINode *PN = dyn_cast<PHINode>(I))
5000         ConstantEvolutionLoopExitValue.erase(PN);
5001     }
5002
5003     PushDefUseChildren(I, Worklist);
5004   }
5005 }
5006
5007 /// getExact - Get the exact loop backedge taken count considering all loop
5008 /// exits. A computable result can only be returned for loops with a single
5009 /// exit.  Returning the minimum taken count among all exits is incorrect
5010 /// because one of the loop's exit limit's may have been skipped. HowFarToZero
5011 /// assumes that the limit of each loop test is never skipped. This is a valid
5012 /// assumption as long as the loop exits via that test. For precise results, it
5013 /// is the caller's responsibility to specify the relevant loop exit using
5014 /// getExact(ExitingBlock, SE).
5015 const SCEV *
5016 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
5017   // If any exits were not computable, the loop is not computable.
5018   if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5019
5020   // We need exactly one computable exit.
5021   if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
5022   assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5023
5024   const SCEV *BECount = nullptr;
5025   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
5026        ENT != nullptr; ENT = ENT->getNextExit()) {
5027
5028     assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5029
5030     if (!BECount)
5031       BECount = ENT->ExactNotTaken;
5032     else if (BECount != ENT->ExactNotTaken)
5033       return SE->getCouldNotCompute();
5034   }
5035   assert(BECount && "Invalid not taken count for loop exit");
5036   return BECount;
5037 }
5038
5039 /// getExact - Get the exact not taken count for this loop exit.
5040 const SCEV *
5041 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5042                                              ScalarEvolution *SE) const {
5043   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
5044        ENT != nullptr; ENT = ENT->getNextExit()) {
5045
5046     if (ENT->ExitingBlock == ExitingBlock)
5047       return ENT->ExactNotTaken;
5048   }
5049   return SE->getCouldNotCompute();
5050 }
5051
5052 /// getMax - Get the max backedge taken count for the loop.
5053 const SCEV *
5054 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5055   return Max ? Max : SE->getCouldNotCompute();
5056 }
5057
5058 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5059                                                     ScalarEvolution *SE) const {
5060   if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5061     return true;
5062
5063   if (!ExitNotTaken.ExitingBlock)
5064     return false;
5065
5066   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
5067        ENT != nullptr; ENT = ENT->getNextExit()) {
5068
5069     if (ENT->ExactNotTaken != SE->getCouldNotCompute()
5070         && SE->hasOperand(ENT->ExactNotTaken, S)) {
5071       return true;
5072     }
5073   }
5074   return false;
5075 }
5076
5077 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5078 /// computable exit into a persistent ExitNotTakenInfo array.
5079 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5080   SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
5081   bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
5082
5083   if (!Complete)
5084     ExitNotTaken.setIncomplete();
5085
5086   unsigned NumExits = ExitCounts.size();
5087   if (NumExits == 0) return;
5088
5089   ExitNotTaken.ExitingBlock = ExitCounts[0].first;
5090   ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
5091   if (NumExits == 1) return;
5092
5093   // Handle the rare case of multiple computable exits.
5094   ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
5095
5096   ExitNotTakenInfo *PrevENT = &ExitNotTaken;
5097   for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
5098     PrevENT->setNextExit(ENT);
5099     ENT->ExitingBlock = ExitCounts[i].first;
5100     ENT->ExactNotTaken = ExitCounts[i].second;
5101   }
5102 }
5103
5104 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
5105 void ScalarEvolution::BackedgeTakenInfo::clear() {
5106   ExitNotTaken.ExitingBlock = nullptr;
5107   ExitNotTaken.ExactNotTaken = nullptr;
5108   delete[] ExitNotTaken.getNextExit();
5109 }
5110
5111 /// computeBackedgeTakenCount - Compute the number of times the backedge
5112 /// of the specified loop will execute.
5113 ScalarEvolution::BackedgeTakenInfo
5114 ScalarEvolution::computeBackedgeTakenCount(const Loop *L) {
5115   SmallVector<BasicBlock *, 8> ExitingBlocks;
5116   L->getExitingBlocks(ExitingBlocks);
5117
5118   SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
5119   bool CouldComputeBECount = true;
5120   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5121   const SCEV *MustExitMaxBECount = nullptr;
5122   const SCEV *MayExitMaxBECount = nullptr;
5123
5124   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5125   // and compute maxBECount.
5126   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5127     BasicBlock *ExitBB = ExitingBlocks[i];
5128     ExitLimit EL = computeExitLimit(L, ExitBB);
5129
5130     // 1. For each exit that can be computed, add an entry to ExitCounts.
5131     // CouldComputeBECount is true only if all exits can be computed.
5132     if (EL.Exact == getCouldNotCompute())
5133       // We couldn't compute an exact value for this exit, so
5134       // we won't be able to compute an exact value for the loop.
5135       CouldComputeBECount = false;
5136     else
5137       ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
5138
5139     // 2. Derive the loop's MaxBECount from each exit's max number of
5140     // non-exiting iterations. Partition the loop exits into two kinds:
5141     // LoopMustExits and LoopMayExits.
5142     //
5143     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5144     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5145     // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5146     // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5147     // considered greater than any computable EL.Max.
5148     if (EL.Max != getCouldNotCompute() && Latch &&
5149         DT.dominates(ExitBB, Latch)) {
5150       if (!MustExitMaxBECount)
5151         MustExitMaxBECount = EL.Max;
5152       else {
5153         MustExitMaxBECount =
5154           getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
5155       }
5156     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5157       if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5158         MayExitMaxBECount = EL.Max;
5159       else {
5160         MayExitMaxBECount =
5161           getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5162       }
5163     }
5164   }
5165   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5166     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5167   return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
5168 }
5169
5170 ScalarEvolution::ExitLimit
5171 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
5172
5173   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5174   // at this block and remember the exit block and whether all other targets
5175   // lead to the loop header.
5176   bool MustExecuteLoopHeader = true;
5177   BasicBlock *Exit = nullptr;
5178   for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
5179        SI != SE; ++SI)
5180     if (!L->contains(*SI)) {
5181       if (Exit) // Multiple exit successors.
5182         return getCouldNotCompute();
5183       Exit = *SI;
5184     } else if (*SI != L->getHeader()) {
5185       MustExecuteLoopHeader = false;
5186     }
5187
5188   // At this point, we know we have a conditional branch that determines whether
5189   // the loop is exited.  However, we don't know if the branch is executed each
5190   // time through the loop.  If not, then the execution count of the branch will
5191   // not be equal to the trip count of the loop.
5192   //
5193   // Currently we check for this by checking to see if the Exit branch goes to
5194   // the loop header.  If so, we know it will always execute the same number of
5195   // times as the loop.  We also handle the case where the exit block *is* the
5196   // loop header.  This is common for un-rotated loops.
5197   //
5198   // If both of those tests fail, walk up the unique predecessor chain to the
5199   // header, stopping if there is an edge that doesn't exit the loop. If the
5200   // header is reached, the execution count of the branch will be equal to the
5201   // trip count of the loop.
5202   //
5203   //  More extensive analysis could be done to handle more cases here.
5204   //
5205   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
5206     // The simple checks failed, try climbing the unique predecessor chain
5207     // up to the header.
5208     bool Ok = false;
5209     for (BasicBlock *BB = ExitingBlock; BB; ) {
5210       BasicBlock *Pred = BB->getUniquePredecessor();
5211       if (!Pred)
5212         return getCouldNotCompute();
5213       TerminatorInst *PredTerm = Pred->getTerminator();
5214       for (const BasicBlock *PredSucc : PredTerm->successors()) {
5215         if (PredSucc == BB)
5216           continue;
5217         // If the predecessor has a successor that isn't BB and isn't
5218         // outside the loop, assume the worst.
5219         if (L->contains(PredSucc))
5220           return getCouldNotCompute();
5221       }
5222       if (Pred == L->getHeader()) {
5223         Ok = true;
5224         break;
5225       }
5226       BB = Pred;
5227     }
5228     if (!Ok)
5229       return getCouldNotCompute();
5230   }
5231
5232   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
5233   TerminatorInst *Term = ExitingBlock->getTerminator();
5234   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5235     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5236     // Proceed to the next level to examine the exit condition expression.
5237     return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
5238                                     BI->getSuccessor(1),
5239                                     /*ControlsExit=*/IsOnlyExit);
5240   }
5241
5242   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
5243     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
5244                                                 /*ControlsExit=*/IsOnlyExit);
5245
5246   return getCouldNotCompute();
5247 }
5248
5249 /// computeExitLimitFromCond - Compute the number of times the
5250 /// backedge of the specified loop will execute if its exit condition
5251 /// were a conditional branch of ExitCond, TBB, and FBB.
5252 ///
5253 /// @param ControlsExit is true if ExitCond directly controls the exit
5254 /// branch. In this case, we can assume that the loop exits only if the
5255 /// condition is true and can infer that failing to meet the condition prior to
5256 /// integer wraparound results in undefined behavior.
5257 ScalarEvolution::ExitLimit
5258 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
5259                                           Value *ExitCond,
5260                                           BasicBlock *TBB,
5261                                           BasicBlock *FBB,
5262                                           bool ControlsExit) {
5263   // Check if the controlling expression for this loop is an And or Or.
5264   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5265     if (BO->getOpcode() == Instruction::And) {
5266       // Recurse on the operands of the and.
5267       bool EitherMayExit = L->contains(TBB);
5268       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5269                                                ControlsExit && !EitherMayExit);
5270       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5271                                                ControlsExit && !EitherMayExit);
5272       const SCEV *BECount = getCouldNotCompute();
5273       const SCEV *MaxBECount = getCouldNotCompute();
5274       if (EitherMayExit) {
5275         // Both conditions must be true for the loop to continue executing.
5276         // Choose the less conservative count.
5277         if (EL0.Exact == getCouldNotCompute() ||
5278             EL1.Exact == getCouldNotCompute())
5279           BECount = getCouldNotCompute();
5280         else
5281           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5282         if (EL0.Max == getCouldNotCompute())
5283           MaxBECount = EL1.Max;
5284         else if (EL1.Max == getCouldNotCompute())
5285           MaxBECount = EL0.Max;
5286         else
5287           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5288       } else {
5289         // Both conditions must be true at the same time for the loop to exit.
5290         // For now, be conservative.
5291         assert(L->contains(FBB) && "Loop block has no successor in loop!");
5292         if (EL0.Max == EL1.Max)
5293           MaxBECount = EL0.Max;
5294         if (EL0.Exact == EL1.Exact)
5295           BECount = EL0.Exact;
5296       }
5297
5298       return ExitLimit(BECount, MaxBECount);
5299     }
5300     if (BO->getOpcode() == Instruction::Or) {
5301       // Recurse on the operands of the or.
5302       bool EitherMayExit = L->contains(FBB);
5303       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5304                                                ControlsExit && !EitherMayExit);
5305       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5306                                                ControlsExit && !EitherMayExit);
5307       const SCEV *BECount = getCouldNotCompute();
5308       const SCEV *MaxBECount = getCouldNotCompute();
5309       if (EitherMayExit) {
5310         // Both conditions must be false for the loop to continue executing.
5311         // Choose the less conservative count.
5312         if (EL0.Exact == getCouldNotCompute() ||
5313             EL1.Exact == getCouldNotCompute())
5314           BECount = getCouldNotCompute();
5315         else
5316           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5317         if (EL0.Max == getCouldNotCompute())
5318           MaxBECount = EL1.Max;
5319         else if (EL1.Max == getCouldNotCompute())
5320           MaxBECount = EL0.Max;
5321         else
5322           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5323       } else {
5324         // Both conditions must be false at the same time for the loop to exit.
5325         // For now, be conservative.
5326         assert(L->contains(TBB) && "Loop block has no successor in loop!");
5327         if (EL0.Max == EL1.Max)
5328           MaxBECount = EL0.Max;
5329         if (EL0.Exact == EL1.Exact)
5330           BECount = EL0.Exact;
5331       }
5332
5333       return ExitLimit(BECount, MaxBECount);
5334     }
5335   }
5336
5337   // With an icmp, it may be feasible to compute an exact backedge-taken count.
5338   // Proceed to the next level to examine the icmp.
5339   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
5340     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5341
5342   // Check for a constant condition. These are normally stripped out by
5343   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5344   // preserve the CFG and is temporarily leaving constant conditions
5345   // in place.
5346   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5347     if (L->contains(FBB) == !CI->getZExtValue())
5348       // The backedge is always taken.
5349       return getCouldNotCompute();
5350     else
5351       // The backedge is never taken.
5352       return getZero(CI->getType());
5353   }
5354
5355   // If it's not an integer or pointer comparison then compute it the hard way.
5356   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5357 }
5358
5359 ScalarEvolution::ExitLimit
5360 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
5361                                           ICmpInst *ExitCond,
5362                                           BasicBlock *TBB,
5363                                           BasicBlock *FBB,
5364                                           bool ControlsExit) {
5365
5366   // If the condition was exit on true, convert the condition to exit on false
5367   ICmpInst::Predicate Cond;
5368   if (!L->contains(FBB))
5369     Cond = ExitCond->getPredicate();
5370   else
5371     Cond = ExitCond->getInversePredicate();
5372
5373   // Handle common loops like: for (X = "string"; *X; ++X)
5374   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5375     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5376       ExitLimit ItCnt =
5377         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5378       if (ItCnt.hasAnyInfo())
5379         return ItCnt;
5380     }
5381
5382   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5383   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
5384
5385   // Try to evaluate any dependencies out of the loop.
5386   LHS = getSCEVAtScope(LHS, L);
5387   RHS = getSCEVAtScope(RHS, L);
5388
5389   // At this point, we would like to compute how many iterations of the
5390   // loop the predicate will return true for these inputs.
5391   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
5392     // If there is a loop-invariant, force it into the RHS.
5393     std::swap(LHS, RHS);
5394     Cond = ICmpInst::getSwappedPredicate(Cond);
5395   }
5396
5397   // Simplify the operands before analyzing them.
5398   (void)SimplifyICmpOperands(Cond, LHS, RHS);
5399
5400   // If we have a comparison of a chrec against a constant, try to use value
5401   // ranges to answer this query.
5402   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5403     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
5404       if (AddRec->getLoop() == L) {
5405         // Form the constant range.
5406         ConstantRange CompRange(
5407             ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
5408
5409         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
5410         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
5411       }
5412
5413   switch (Cond) {
5414   case ICmpInst::ICMP_NE: {                     // while (X != Y)
5415     // Convert to: while (X-Y != 0)
5416     ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5417     if (EL.hasAnyInfo()) return EL;
5418     break;
5419   }
5420   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
5421     // Convert to: while (X-Y == 0)
5422     ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5423     if (EL.hasAnyInfo()) return EL;
5424     break;
5425   }
5426   case ICmpInst::ICMP_SLT:
5427   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
5428     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
5429     ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
5430     if (EL.hasAnyInfo()) return EL;
5431     break;
5432   }
5433   case ICmpInst::ICMP_SGT:
5434   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
5435     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
5436     ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
5437     if (EL.hasAnyInfo()) return EL;
5438     break;
5439   }
5440   default:
5441 #if 0
5442     dbgs() << "computeBackedgeTakenCount ";
5443     if (ExitCond->getOperand(0)->getType()->isUnsigned())
5444       dbgs() << "[unsigned] ";
5445     dbgs() << *LHS << "   "
5446          << Instruction::getOpcodeName(Instruction::ICmp)
5447          << "   " << *RHS << "\n";
5448 #endif
5449     break;
5450   }
5451   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5452 }
5453
5454 ScalarEvolution::ExitLimit
5455 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
5456                                                       SwitchInst *Switch,
5457                                                       BasicBlock *ExitingBlock,
5458                                                       bool ControlsExit) {
5459   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5460
5461   // Give up if the exit is the default dest of a switch.
5462   if (Switch->getDefaultDest() == ExitingBlock)
5463     return getCouldNotCompute();
5464
5465   assert(L->contains(Switch->getDefaultDest()) &&
5466          "Default case must not exit the loop!");
5467   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5468   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5469
5470   // while (X != Y) --> while (X-Y != 0)
5471   ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5472   if (EL.hasAnyInfo())
5473     return EL;
5474
5475   return getCouldNotCompute();
5476 }
5477
5478 static ConstantInt *
5479 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5480                                 ScalarEvolution &SE) {
5481   const SCEV *InVal = SE.getConstant(C);
5482   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
5483   assert(isa<SCEVConstant>(Val) &&
5484          "Evaluation of SCEV at constant didn't fold correctly?");
5485   return cast<SCEVConstant>(Val)->getValue();
5486 }
5487
5488 /// computeLoadConstantCompareExitLimit - Given an exit condition of
5489 /// 'icmp op load X, cst', try to see if we can compute the backedge
5490 /// execution count.
5491 ScalarEvolution::ExitLimit
5492 ScalarEvolution::computeLoadConstantCompareExitLimit(
5493   LoadInst *LI,
5494   Constant *RHS,
5495   const Loop *L,
5496   ICmpInst::Predicate predicate) {
5497
5498   if (LI->isVolatile()) return getCouldNotCompute();
5499
5500   // Check to see if the loaded pointer is a getelementptr of a global.
5501   // TODO: Use SCEV instead of manually grubbing with GEPs.
5502   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
5503   if (!GEP) return getCouldNotCompute();
5504
5505   // Make sure that it is really a constant global we are gepping, with an
5506   // initializer, and make sure the first IDX is really 0.
5507   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
5508   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
5509       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5510       !cast<Constant>(GEP->getOperand(1))->isNullValue())
5511     return getCouldNotCompute();
5512
5513   // Okay, we allow one non-constant index into the GEP instruction.
5514   Value *VarIdx = nullptr;
5515   std::vector<Constant*> Indexes;
5516   unsigned VarIdxNum = 0;
5517   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5518     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5519       Indexes.push_back(CI);
5520     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
5521       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
5522       VarIdx = GEP->getOperand(i);
5523       VarIdxNum = i-2;
5524       Indexes.push_back(nullptr);
5525     }
5526
5527   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5528   if (!VarIdx)
5529     return getCouldNotCompute();
5530
5531   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5532   // Check to see if X is a loop variant variable value now.
5533   const SCEV *Idx = getSCEV(VarIdx);
5534   Idx = getSCEVAtScope(Idx, L);
5535
5536   // We can only recognize very limited forms of loop index expressions, in
5537   // particular, only affine AddRec's like {C1,+,C2}.
5538   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
5539   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
5540       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5541       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
5542     return getCouldNotCompute();
5543
5544   unsigned MaxSteps = MaxBruteForceIterations;
5545   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
5546     ConstantInt *ItCst = ConstantInt::get(
5547                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
5548     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
5549
5550     // Form the GEP offset.
5551     Indexes[VarIdxNum] = Val;
5552
5553     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5554                                                          Indexes);
5555     if (!Result) break;  // Cannot compute!
5556
5557     // Evaluate the condition for this iteration.
5558     Result = ConstantExpr::getICmp(predicate, Result, RHS);
5559     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
5560     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
5561 #if 0
5562       dbgs() << "\n***\n*** Computed loop count " << *ItCst
5563              << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5564              << "***\n";
5565 #endif
5566       ++NumArrayLenItCounts;
5567       return getConstant(ItCst);   // Found terminating iteration!
5568     }
5569   }
5570   return getCouldNotCompute();
5571 }
5572
5573
5574 /// CanConstantFold - Return true if we can constant fold an instruction of the
5575 /// specified type, assuming that all operands were constants.
5576 static bool CanConstantFold(const Instruction *I) {
5577   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
5578       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5579       isa<LoadInst>(I))
5580     return true;
5581
5582   if (const CallInst *CI = dyn_cast<CallInst>(I))
5583     if (const Function *F = CI->getCalledFunction())
5584       return canConstantFoldCallTo(F);
5585   return false;
5586 }
5587
5588 /// Determine whether this instruction can constant evolve within this loop
5589 /// assuming its operands can all constant evolve.
5590 static bool canConstantEvolve(Instruction *I, const Loop *L) {
5591   // An instruction outside of the loop can't be derived from a loop PHI.
5592   if (!L->contains(I)) return false;
5593
5594   if (isa<PHINode>(I)) {
5595     // We don't currently keep track of the control flow needed to evaluate
5596     // PHIs, so we cannot handle PHIs inside of loops.
5597     return L->getHeader() == I->getParent();
5598   }
5599
5600   // If we won't be able to constant fold this expression even if the operands
5601   // are constants, bail early.
5602   return CanConstantFold(I);
5603 }
5604
5605 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5606 /// recursing through each instruction operand until reaching a loop header phi.
5607 static PHINode *
5608 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
5609                                DenseMap<Instruction *, PHINode *> &PHIMap) {
5610
5611   // Otherwise, we can evaluate this instruction if all of its operands are
5612   // constant or derived from a PHI node themselves.
5613   PHINode *PHI = nullptr;
5614   for (Instruction::op_iterator OpI = UseInst->op_begin(),
5615          OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5616
5617     if (isa<Constant>(*OpI)) continue;
5618
5619     Instruction *OpInst = dyn_cast<Instruction>(*OpI);
5620     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
5621
5622     PHINode *P = dyn_cast<PHINode>(OpInst);
5623     if (!P)
5624       // If this operand is already visited, reuse the prior result.
5625       // We may have P != PHI if this is the deepest point at which the
5626       // inconsistent paths meet.
5627       P = PHIMap.lookup(OpInst);
5628     if (!P) {
5629       // Recurse and memoize the results, whether a phi is found or not.
5630       // This recursive call invalidates pointers into PHIMap.
5631       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5632       PHIMap[OpInst] = P;
5633     }
5634     if (!P)
5635       return nullptr;  // Not evolving from PHI
5636     if (PHI && PHI != P)
5637       return nullptr;  // Evolving from multiple different PHIs.
5638     PHI = P;
5639   }
5640   // This is a expression evolving from a constant PHI!
5641   return PHI;
5642 }
5643
5644 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5645 /// in the loop that V is derived from.  We allow arbitrary operations along the
5646 /// way, but the operands of an operation must either be constants or a value
5647 /// derived from a constant PHI.  If this expression does not fit with these
5648 /// constraints, return null.
5649 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
5650   Instruction *I = dyn_cast<Instruction>(V);
5651   if (!I || !canConstantEvolve(I, L)) return nullptr;
5652
5653   if (PHINode *PN = dyn_cast<PHINode>(I)) {
5654     return PN;
5655   }
5656
5657   // Record non-constant instructions contained by the loop.
5658   DenseMap<Instruction *, PHINode *> PHIMap;
5659   return getConstantEvolvingPHIOperands(I, L, PHIMap);
5660 }
5661
5662 /// EvaluateExpression - Given an expression that passes the
5663 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5664 /// in the loop has the value PHIVal.  If we can't fold this expression for some
5665 /// reason, return null.
5666 static Constant *EvaluateExpression(Value *V, const Loop *L,
5667                                     DenseMap<Instruction *, Constant *> &Vals,
5668                                     const DataLayout &DL,
5669                                     const TargetLibraryInfo *TLI) {
5670   // Convenient constant check, but redundant for recursive calls.
5671   if (Constant *C = dyn_cast<Constant>(V)) return C;
5672   Instruction *I = dyn_cast<Instruction>(V);
5673   if (!I) return nullptr;
5674
5675   if (Constant *C = Vals.lookup(I)) return C;
5676
5677   // An instruction inside the loop depends on a value outside the loop that we
5678   // weren't given a mapping for, or a value such as a call inside the loop.
5679   if (!canConstantEvolve(I, L)) return nullptr;
5680
5681   // An unmapped PHI can be due to a branch or another loop inside this loop,
5682   // or due to this not being the initial iteration through a loop where we
5683   // couldn't compute the evolution of this particular PHI last time.
5684   if (isa<PHINode>(I)) return nullptr;
5685
5686   std::vector<Constant*> Operands(I->getNumOperands());
5687
5688   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5689     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5690     if (!Operand) {
5691       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
5692       if (!Operands[i]) return nullptr;
5693       continue;
5694     }
5695     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
5696     Vals[Operand] = C;
5697     if (!C) return nullptr;
5698     Operands[i] = C;
5699   }
5700
5701   if (CmpInst *CI = dyn_cast<CmpInst>(I))
5702     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
5703                                            Operands[1], DL, TLI);
5704   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5705     if (!LI->isVolatile())
5706       return ConstantFoldLoadFromConstPtr(Operands[0], DL);
5707   }
5708   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
5709                                   TLI);
5710 }
5711
5712 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5713 /// in the header of its containing loop, we know the loop executes a
5714 /// constant number of times, and the PHI node is just a recurrence
5715 /// involving constants, fold it.
5716 Constant *
5717 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
5718                                                    const APInt &BEs,
5719                                                    const Loop *L) {
5720   auto I = ConstantEvolutionLoopExitValue.find(PN);
5721   if (I != ConstantEvolutionLoopExitValue.end())
5722     return I->second;
5723
5724   if (BEs.ugt(MaxBruteForceIterations))
5725     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
5726
5727   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5728
5729   DenseMap<Instruction *, Constant *> CurrentIterVals;
5730   BasicBlock *Header = L->getHeader();
5731   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5732
5733   BasicBlock *Latch = L->getLoopLatch();
5734   if (!Latch)
5735     return nullptr;
5736
5737   // Since the loop has one latch, the PHI node must have two entries.  One
5738   // entry must be a constant (coming in from outside of the loop), and the
5739   // second must be derived from the same PHI.
5740
5741   BasicBlock *NonLatch = Latch == PN->getIncomingBlock(0)
5742                              ? PN->getIncomingBlock(1)
5743                              : PN->getIncomingBlock(0);
5744
5745   assert(PN->getNumIncomingValues() == 2 && "Follows from having one latch!");
5746
5747   // Note: not all PHI nodes in the same block have to have their incoming
5748   // values in the same order, so we use the basic block to look up the incoming
5749   // value, not an index.
5750
5751   for (auto &I : *Header) {
5752     PHINode *PHI = dyn_cast<PHINode>(&I);
5753     if (!PHI) break;
5754     auto *StartCST =
5755         dyn_cast<Constant>(PHI->getIncomingValueForBlock(NonLatch));
5756     if (!StartCST) continue;
5757     CurrentIterVals[PHI] = StartCST;
5758   }
5759   if (!CurrentIterVals.count(PN))
5760     return RetVal = nullptr;
5761
5762   Value *BEValue = PN->getIncomingValueForBlock(Latch);
5763
5764   // Execute the loop symbolically to determine the exit value.
5765   if (BEs.getActiveBits() >= 32)
5766     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
5767
5768   unsigned NumIterations = BEs.getZExtValue(); // must be in range
5769   unsigned IterationNum = 0;
5770   const DataLayout &DL = F.getParent()->getDataLayout();
5771   for (; ; ++IterationNum) {
5772     if (IterationNum == NumIterations)
5773       return RetVal = CurrentIterVals[PN];  // Got exit value!
5774
5775     // Compute the value of the PHIs for the next iteration.
5776     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
5777     DenseMap<Instruction *, Constant *> NextIterVals;
5778     Constant *NextPHI =
5779         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
5780     if (!NextPHI)
5781       return nullptr;        // Couldn't evaluate!
5782     NextIterVals[PN] = NextPHI;
5783
5784     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5785
5786     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
5787     // cease to be able to evaluate one of them or if they stop evolving,
5788     // because that doesn't necessarily prevent us from computing PN.
5789     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
5790     for (const auto &I : CurrentIterVals) {
5791       PHINode *PHI = dyn_cast<PHINode>(I.first);
5792       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
5793       PHIsToCompute.emplace_back(PHI, I.second);
5794     }
5795     // We use two distinct loops because EvaluateExpression may invalidate any
5796     // iterators into CurrentIterVals.
5797     for (const auto &I : PHIsToCompute) {
5798       PHINode *PHI = I.first;
5799       Constant *&NextPHI = NextIterVals[PHI];
5800       if (!NextPHI) {   // Not already computed.
5801         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
5802         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
5803       }
5804       if (NextPHI != I.second)
5805         StoppedEvolving = false;
5806     }
5807
5808     // If all entries in CurrentIterVals == NextIterVals then we can stop
5809     // iterating, the loop can't continue to change.
5810     if (StoppedEvolving)
5811       return RetVal = CurrentIterVals[PN];
5812
5813     CurrentIterVals.swap(NextIterVals);
5814   }
5815 }
5816
5817 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
5818                                                           Value *Cond,
5819                                                           bool ExitWhen) {
5820   PHINode *PN = getConstantEvolvingPHI(Cond, L);
5821   if (!PN) return getCouldNotCompute();
5822
5823   // If the loop is canonicalized, the PHI will have exactly two entries.
5824   // That's the only form we support here.
5825   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5826
5827   DenseMap<Instruction *, Constant *> CurrentIterVals;
5828   BasicBlock *Header = L->getHeader();
5829   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5830
5831   BasicBlock *Latch = L->getLoopLatch();
5832   assert(Latch && "Should follow from NumIncomingValues == 2!");
5833
5834   // NonLatch is the preheader, or something equivalent.
5835   BasicBlock *NonLatch = Latch == PN->getIncomingBlock(0)
5836                              ? PN->getIncomingBlock(1)
5837                              : PN->getIncomingBlock(0);
5838
5839   // Note: not all PHI nodes in the same block have to have their incoming
5840   // values in the same order, so we use the basic block to look up the incoming
5841   // value, not an index.
5842
5843   for (auto &I : *Header) {
5844     PHINode *PHI = dyn_cast<PHINode>(&I);
5845     if (!PHI)
5846       break;
5847     auto *StartCST =
5848       dyn_cast<Constant>(PHI->getIncomingValueForBlock(NonLatch));
5849     if (!StartCST) continue;
5850     CurrentIterVals[PHI] = StartCST;
5851   }
5852   if (!CurrentIterVals.count(PN))
5853     return getCouldNotCompute();
5854
5855   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
5856   // the loop symbolically to determine when the condition gets a value of
5857   // "ExitWhen".
5858   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
5859   const DataLayout &DL = F.getParent()->getDataLayout();
5860   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
5861     auto *CondVal = dyn_cast_or_null<ConstantInt>(
5862         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
5863
5864     // Couldn't symbolically evaluate.
5865     if (!CondVal) return getCouldNotCompute();
5866
5867     if (CondVal->getValue() == uint64_t(ExitWhen)) {
5868       ++NumBruteForceTripCountsComputed;
5869       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
5870     }
5871
5872     // Update all the PHI nodes for the next iteration.
5873     DenseMap<Instruction *, Constant *> NextIterVals;
5874
5875     // Create a list of which PHIs we need to compute. We want to do this before
5876     // calling EvaluateExpression on them because that may invalidate iterators
5877     // into CurrentIterVals.
5878     SmallVector<PHINode *, 8> PHIsToCompute;
5879     for (const auto &I : CurrentIterVals) {
5880       PHINode *PHI = dyn_cast<PHINode>(I.first);
5881       if (!PHI || PHI->getParent() != Header) continue;
5882       PHIsToCompute.push_back(PHI);
5883     }
5884     for (PHINode *PHI : PHIsToCompute) {
5885       Constant *&NextPHI = NextIterVals[PHI];
5886       if (NextPHI) continue;    // Already computed!
5887
5888       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
5889       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
5890     }
5891     CurrentIterVals.swap(NextIterVals);
5892   }
5893
5894   // Too many iterations were needed to evaluate.
5895   return getCouldNotCompute();
5896 }
5897
5898 /// getSCEVAtScope - Return a SCEV expression for the specified value
5899 /// at the specified scope in the program.  The L value specifies a loop
5900 /// nest to evaluate the expression at, where null is the top-level or a
5901 /// specified loop is immediately inside of the loop.
5902 ///
5903 /// This method can be used to compute the exit value for a variable defined
5904 /// in a loop by querying what the value will hold in the parent loop.
5905 ///
5906 /// In the case that a relevant loop exit value cannot be computed, the
5907 /// original value V is returned.
5908 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
5909   // Check to see if we've folded this expression at this loop before.
5910   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5911   for (unsigned u = 0; u < Values.size(); u++) {
5912     if (Values[u].first == L)
5913       return Values[u].second ? Values[u].second : V;
5914   }
5915   Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
5916   // Otherwise compute it.
5917   const SCEV *C = computeSCEVAtScope(V, L);
5918   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5919   for (unsigned u = Values2.size(); u > 0; u--) {
5920     if (Values2[u - 1].first == L) {
5921       Values2[u - 1].second = C;
5922       break;
5923     }
5924   }
5925   return C;
5926 }
5927
5928 /// This builds up a Constant using the ConstantExpr interface.  That way, we
5929 /// will return Constants for objects which aren't represented by a
5930 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5931 /// Returns NULL if the SCEV isn't representable as a Constant.
5932 static Constant *BuildConstantFromSCEV(const SCEV *V) {
5933   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
5934     case scCouldNotCompute:
5935     case scAddRecExpr:
5936       break;
5937     case scConstant:
5938       return cast<SCEVConstant>(V)->getValue();
5939     case scUnknown:
5940       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5941     case scSignExtend: {
5942       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5943       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5944         return ConstantExpr::getSExt(CastOp, SS->getType());
5945       break;
5946     }
5947     case scZeroExtend: {
5948       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5949       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5950         return ConstantExpr::getZExt(CastOp, SZ->getType());
5951       break;
5952     }
5953     case scTruncate: {
5954       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5955       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5956         return ConstantExpr::getTrunc(CastOp, ST->getType());
5957       break;
5958     }
5959     case scAddExpr: {
5960       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5961       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
5962         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5963           unsigned AS = PTy->getAddressSpace();
5964           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5965           C = ConstantExpr::getBitCast(C, DestPtrTy);
5966         }
5967         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5968           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
5969           if (!C2) return nullptr;
5970
5971           // First pointer!
5972           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
5973             unsigned AS = C2->getType()->getPointerAddressSpace();
5974             std::swap(C, C2);
5975             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5976             // The offsets have been converted to bytes.  We can add bytes to an
5977             // i8* by GEP with the byte count in the first index.
5978             C = ConstantExpr::getBitCast(C, DestPtrTy);
5979           }
5980
5981           // Don't bother trying to sum two pointers. We probably can't
5982           // statically compute a load that results from it anyway.
5983           if (C2->getType()->isPointerTy())
5984             return nullptr;
5985
5986           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5987             if (PTy->getElementType()->isStructTy())
5988               C2 = ConstantExpr::getIntegerCast(
5989                   C2, Type::getInt32Ty(C->getContext()), true);
5990             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
5991           } else
5992             C = ConstantExpr::getAdd(C, C2);
5993         }
5994         return C;
5995       }
5996       break;
5997     }
5998     case scMulExpr: {
5999       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6000       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6001         // Don't bother with pointers at all.
6002         if (C->getType()->isPointerTy()) return nullptr;
6003         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6004           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6005           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6006           C = ConstantExpr::getMul(C, C2);
6007         }
6008         return C;
6009       }
6010       break;
6011     }
6012     case scUDivExpr: {
6013       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6014       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6015         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6016           if (LHS->getType() == RHS->getType())
6017             return ConstantExpr::getUDiv(LHS, RHS);
6018       break;
6019     }
6020     case scSMaxExpr:
6021     case scUMaxExpr:
6022       break; // TODO: smax, umax.
6023   }
6024   return nullptr;
6025 }
6026
6027 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6028   if (isa<SCEVConstant>(V)) return V;
6029
6030   // If this instruction is evolved from a constant-evolving PHI, compute the
6031   // exit value from the loop without using SCEVs.
6032   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
6033     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
6034       const Loop *LI = this->LI[I->getParent()];
6035       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
6036         if (PHINode *PN = dyn_cast<PHINode>(I))
6037           if (PN->getParent() == LI->getHeader()) {
6038             // Okay, there is no closed form solution for the PHI node.  Check
6039             // to see if the loop that contains it has a known backedge-taken
6040             // count.  If so, we may be able to force computation of the exit
6041             // value.
6042             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
6043             if (const SCEVConstant *BTCC =
6044                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
6045               // Okay, we know how many times the containing loop executes.  If
6046               // this is a constant evolving PHI node, get the final value at
6047               // the specified iteration number.
6048               Constant *RV = getConstantEvolutionLoopExitValue(PN,
6049                                                    BTCC->getValue()->getValue(),
6050                                                                LI);
6051               if (RV) return getSCEV(RV);
6052             }
6053           }
6054
6055       // Okay, this is an expression that we cannot symbolically evaluate
6056       // into a SCEV.  Check to see if it's possible to symbolically evaluate
6057       // the arguments into constants, and if so, try to constant propagate the
6058       // result.  This is particularly useful for computing loop exit values.
6059       if (CanConstantFold(I)) {
6060         SmallVector<Constant *, 4> Operands;
6061         bool MadeImprovement = false;
6062         for (Value *Op : I->operands()) {
6063           if (Constant *C = dyn_cast<Constant>(Op)) {
6064             Operands.push_back(C);
6065             continue;
6066           }
6067
6068           // If any of the operands is non-constant and if they are
6069           // non-integer and non-pointer, don't even try to analyze them
6070           // with scev techniques.
6071           if (!isSCEVable(Op->getType()))
6072             return V;
6073
6074           const SCEV *OrigV = getSCEV(Op);
6075           const SCEV *OpV = getSCEVAtScope(OrigV, L);
6076           MadeImprovement |= OrigV != OpV;
6077
6078           Constant *C = BuildConstantFromSCEV(OpV);
6079           if (!C) return V;
6080           if (C->getType() != Op->getType())
6081             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6082                                                               Op->getType(),
6083                                                               false),
6084                                       C, Op->getType());
6085           Operands.push_back(C);
6086         }
6087
6088         // Check to see if getSCEVAtScope actually made an improvement.
6089         if (MadeImprovement) {
6090           Constant *C = nullptr;
6091           const DataLayout &DL = F.getParent()->getDataLayout();
6092           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
6093             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6094                                                 Operands[1], DL, &TLI);
6095           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6096             if (!LI->isVolatile())
6097               C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
6098           } else
6099             C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands,
6100                                          DL, &TLI);
6101           if (!C) return V;
6102           return getSCEV(C);
6103         }
6104       }
6105     }
6106
6107     // This is some other type of SCEVUnknown, just return it.
6108     return V;
6109   }
6110
6111   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
6112     // Avoid performing the look-up in the common case where the specified
6113     // expression has no loop-variant portions.
6114     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
6115       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6116       if (OpAtScope != Comm->getOperand(i)) {
6117         // Okay, at least one of these operands is loop variant but might be
6118         // foldable.  Build a new instance of the folded commutative expression.
6119         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6120                                             Comm->op_begin()+i);
6121         NewOps.push_back(OpAtScope);
6122
6123         for (++i; i != e; ++i) {
6124           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6125           NewOps.push_back(OpAtScope);
6126         }
6127         if (isa<SCEVAddExpr>(Comm))
6128           return getAddExpr(NewOps);
6129         if (isa<SCEVMulExpr>(Comm))
6130           return getMulExpr(NewOps);
6131         if (isa<SCEVSMaxExpr>(Comm))
6132           return getSMaxExpr(NewOps);
6133         if (isa<SCEVUMaxExpr>(Comm))
6134           return getUMaxExpr(NewOps);
6135         llvm_unreachable("Unknown commutative SCEV type!");
6136       }
6137     }
6138     // If we got here, all operands are loop invariant.
6139     return Comm;
6140   }
6141
6142   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
6143     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6144     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
6145     if (LHS == Div->getLHS() && RHS == Div->getRHS())
6146       return Div;   // must be loop invariant
6147     return getUDivExpr(LHS, RHS);
6148   }
6149
6150   // If this is a loop recurrence for a loop that does not contain L, then we
6151   // are dealing with the final value computed by the loop.
6152   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
6153     // First, attempt to evaluate each operand.
6154     // Avoid performing the look-up in the common case where the specified
6155     // expression has no loop-variant portions.
6156     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6157       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6158       if (OpAtScope == AddRec->getOperand(i))
6159         continue;
6160
6161       // Okay, at least one of these operands is loop variant but might be
6162       // foldable.  Build a new instance of the folded commutative expression.
6163       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6164                                           AddRec->op_begin()+i);
6165       NewOps.push_back(OpAtScope);
6166       for (++i; i != e; ++i)
6167         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6168
6169       const SCEV *FoldedRec =
6170         getAddRecExpr(NewOps, AddRec->getLoop(),
6171                       AddRec->getNoWrapFlags(SCEV::FlagNW));
6172       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
6173       // The addrec may be folded to a nonrecurrence, for example, if the
6174       // induction variable is multiplied by zero after constant folding. Go
6175       // ahead and return the folded value.
6176       if (!AddRec)
6177         return FoldedRec;
6178       break;
6179     }
6180
6181     // If the scope is outside the addrec's loop, evaluate it by using the
6182     // loop exit value of the addrec.
6183     if (!AddRec->getLoop()->contains(L)) {
6184       // To evaluate this recurrence, we need to know how many times the AddRec
6185       // loop iterates.  Compute this now.
6186       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
6187       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
6188
6189       // Then, evaluate the AddRec.
6190       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
6191     }
6192
6193     return AddRec;
6194   }
6195
6196   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
6197     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6198     if (Op == Cast->getOperand())
6199       return Cast;  // must be loop invariant
6200     return getZeroExtendExpr(Op, Cast->getType());
6201   }
6202
6203   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
6204     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6205     if (Op == Cast->getOperand())
6206       return Cast;  // must be loop invariant
6207     return getSignExtendExpr(Op, Cast->getType());
6208   }
6209
6210   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
6211     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6212     if (Op == Cast->getOperand())
6213       return Cast;  // must be loop invariant
6214     return getTruncateExpr(Op, Cast->getType());
6215   }
6216
6217   llvm_unreachable("Unknown SCEV type!");
6218 }
6219
6220 /// getSCEVAtScope - This is a convenience function which does
6221 /// getSCEVAtScope(getSCEV(V), L).
6222 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
6223   return getSCEVAtScope(getSCEV(V), L);
6224 }
6225
6226 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
6227 /// following equation:
6228 ///
6229 ///     A * X = B (mod N)
6230 ///
6231 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6232 /// A and B isn't important.
6233 ///
6234 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
6235 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
6236                                                ScalarEvolution &SE) {
6237   uint32_t BW = A.getBitWidth();
6238   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6239   assert(A != 0 && "A must be non-zero.");
6240
6241   // 1. D = gcd(A, N)
6242   //
6243   // The gcd of A and N may have only one prime factor: 2. The number of
6244   // trailing zeros in A is its multiplicity
6245   uint32_t Mult2 = A.countTrailingZeros();
6246   // D = 2^Mult2
6247
6248   // 2. Check if B is divisible by D.
6249   //
6250   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6251   // is not less than multiplicity of this prime factor for D.
6252   if (B.countTrailingZeros() < Mult2)
6253     return SE.getCouldNotCompute();
6254
6255   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6256   // modulo (N / D).
6257   //
6258   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
6259   // bit width during computations.
6260   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
6261   APInt Mod(BW + 1, 0);
6262   Mod.setBit(BW - Mult2);  // Mod = N / D
6263   APInt I = AD.multiplicativeInverse(Mod);
6264
6265   // 4. Compute the minimum unsigned root of the equation:
6266   // I * (B / D) mod (N / D)
6267   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6268
6269   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6270   // bits.
6271   return SE.getConstant(Result.trunc(BW));
6272 }
6273
6274 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6275 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
6276 /// might be the same) or two SCEVCouldNotCompute objects.
6277 ///
6278 static std::pair<const SCEV *,const SCEV *>
6279 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
6280   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
6281   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6282   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6283   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
6284
6285   // We currently can only solve this if the coefficients are constants.
6286   if (!LC || !MC || !NC) {
6287     const SCEV *CNC = SE.getCouldNotCompute();
6288     return std::make_pair(CNC, CNC);
6289   }
6290
6291   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
6292   const APInt &L = LC->getValue()->getValue();
6293   const APInt &M = MC->getValue()->getValue();
6294   const APInt &N = NC->getValue()->getValue();
6295   APInt Two(BitWidth, 2);
6296   APInt Four(BitWidth, 4);
6297
6298   {
6299     using namespace APIntOps;
6300     const APInt& C = L;
6301     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6302     // The B coefficient is M-N/2
6303     APInt B(M);
6304     B -= sdiv(N,Two);
6305
6306     // The A coefficient is N/2
6307     APInt A(N.sdiv(Two));
6308
6309     // Compute the B^2-4ac term.
6310     APInt SqrtTerm(B);
6311     SqrtTerm *= B;
6312     SqrtTerm -= Four * (A * C);
6313
6314     if (SqrtTerm.isNegative()) {
6315       // The loop is provably infinite.
6316       const SCEV *CNC = SE.getCouldNotCompute();
6317       return std::make_pair(CNC, CNC);
6318     }
6319
6320     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6321     // integer value or else APInt::sqrt() will assert.
6322     APInt SqrtVal(SqrtTerm.sqrt());
6323
6324     // Compute the two solutions for the quadratic formula.
6325     // The divisions must be performed as signed divisions.
6326     APInt NegB(-B);
6327     APInt TwoA(A << 1);
6328     if (TwoA.isMinValue()) {
6329       const SCEV *CNC = SE.getCouldNotCompute();
6330       return std::make_pair(CNC, CNC);
6331     }
6332
6333     LLVMContext &Context = SE.getContext();
6334
6335     ConstantInt *Solution1 =
6336       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
6337     ConstantInt *Solution2 =
6338       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
6339
6340     return std::make_pair(SE.getConstant(Solution1),
6341                           SE.getConstant(Solution2));
6342   } // end APIntOps namespace
6343 }
6344
6345 /// HowFarToZero - Return the number of times a backedge comparing the specified
6346 /// value to zero will execute.  If not computable, return CouldNotCompute.
6347 ///
6348 /// This is only used for loops with a "x != y" exit test. The exit condition is
6349 /// now expressed as a single expression, V = x-y. So the exit test is
6350 /// effectively V != 0.  We know and take advantage of the fact that this
6351 /// expression only being used in a comparison by zero context.
6352 ScalarEvolution::ExitLimit
6353 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
6354   // If the value is a constant
6355   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6356     // If the value is already zero, the branch will execute zero times.
6357     if (C->getValue()->isZero()) return C;
6358     return getCouldNotCompute();  // Otherwise it will loop infinitely.
6359   }
6360
6361   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
6362   if (!AddRec || AddRec->getLoop() != L)
6363     return getCouldNotCompute();
6364
6365   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6366   // the quadratic equation to solve it.
6367   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6368     std::pair<const SCEV *,const SCEV *> Roots =
6369       SolveQuadraticEquation(AddRec, *this);
6370     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6371     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6372     if (R1 && R2) {
6373 #if 0
6374       dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
6375              << "  sol#2: " << *R2 << "\n";
6376 #endif
6377       // Pick the smallest positive root value.
6378       if (ConstantInt *CB =
6379           dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6380                                                       R1->getValue(),
6381                                                       R2->getValue()))) {
6382         if (!CB->getZExtValue())
6383           std::swap(R1, R2);   // R1 is the minimum root now.
6384
6385         // We can only use this value if the chrec ends up with an exact zero
6386         // value at this index.  When solving for "X*X != 5", for example, we
6387         // should not accept a root of 2.
6388         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
6389         if (Val->isZero())
6390           return R1;  // We found a quadratic root!
6391       }
6392     }
6393     return getCouldNotCompute();
6394   }
6395
6396   // Otherwise we can only handle this if it is affine.
6397   if (!AddRec->isAffine())
6398     return getCouldNotCompute();
6399
6400   // If this is an affine expression, the execution count of this branch is
6401   // the minimum unsigned root of the following equation:
6402   //
6403   //     Start + Step*N = 0 (mod 2^BW)
6404   //
6405   // equivalent to:
6406   //
6407   //             Step*N = -Start (mod 2^BW)
6408   //
6409   // where BW is the common bit width of Start and Step.
6410
6411   // Get the initial value for the loop.
6412   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6413   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6414
6415   // For now we handle only constant steps.
6416   //
6417   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6418   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6419   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6420   // We have not yet seen any such cases.
6421   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
6422   if (!StepC || StepC->getValue()->equalsInt(0))
6423     return getCouldNotCompute();
6424
6425   // For positive steps (counting up until unsigned overflow):
6426   //   N = -Start/Step (as unsigned)
6427   // For negative steps (counting down to zero):
6428   //   N = Start/-Step
6429   // First compute the unsigned distance from zero in the direction of Step.
6430   bool CountDown = StepC->getValue()->getValue().isNegative();
6431   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
6432
6433   // Handle unitary steps, which cannot wraparound.
6434   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6435   //   N = Distance (as unsigned)
6436   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6437     ConstantRange CR = getUnsignedRange(Start);
6438     const SCEV *MaxBECount;
6439     if (!CountDown && CR.getUnsignedMin().isMinValue())
6440       // When counting up, the worst starting value is 1, not 0.
6441       MaxBECount = CR.getUnsignedMax().isMinValue()
6442         ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6443         : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6444     else
6445       MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6446                                          : -CR.getUnsignedMin());
6447     return ExitLimit(Distance, MaxBECount);
6448   }
6449
6450   // As a special case, handle the instance where Step is a positive power of
6451   // two. In this case, determining whether Step divides Distance evenly can be
6452   // done by counting and comparing the number of trailing zeros of Step and
6453   // Distance.
6454   if (!CountDown) {
6455     const APInt &StepV = StepC->getValue()->getValue();
6456     // StepV.isPowerOf2() returns true if StepV is an positive power of two.  It
6457     // also returns true if StepV is maximally negative (eg, INT_MIN), but that
6458     // case is not handled as this code is guarded by !CountDown.
6459     if (StepV.isPowerOf2() &&
6460         GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
6461       // Here we've constrained the equation to be of the form
6462       //
6463       //   2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W)  ... (0)
6464       //
6465       // where we're operating on a W bit wide integer domain and k is
6466       // non-negative.  The smallest unsigned solution for X is the trip count.
6467       //
6468       // (0) is equivalent to:
6469       //
6470       //      2^(N + k) * Distance' - 2^N * X = L * 2^W
6471       // <=>  2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
6472       // <=>  2^k * Distance' - X = L * 2^(W - N)
6473       // <=>  2^k * Distance'     = L * 2^(W - N) + X    ... (1)
6474       //
6475       // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
6476       // by 2^(W - N).
6477       //
6478       // <=>  X = 2^k * Distance' URem 2^(W - N)   ... (2)
6479       //
6480       // E.g. say we're solving
6481       //
6482       //   2 * Val = 2 * X  (in i8)   ... (3)
6483       //
6484       // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
6485       //
6486       // Note: It is tempting to solve (3) by setting X = Val, but Val is not
6487       // necessarily the smallest unsigned value of X that satisfies (3).
6488       // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
6489       // is i8 1, not i8 -127
6490
6491       const auto *ModuloResult = getUDivExactExpr(Distance, Step);
6492
6493       // Since SCEV does not have a URem node, we construct one using a truncate
6494       // and a zero extend.
6495
6496       unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
6497       auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
6498       auto *WideTy = Distance->getType();
6499
6500       return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
6501     }
6502   }
6503
6504   // If the condition controls loop exit (the loop exits only if the expression
6505   // is true) and the addition is no-wrap we can use unsigned divide to
6506   // compute the backedge count.  In this case, the step may not divide the
6507   // distance, but we don't care because if the condition is "missed" the loop
6508   // will have undefined behavior due to wrapping.
6509   if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6510     const SCEV *Exact =
6511         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6512     return ExitLimit(Exact, Exact);
6513   }
6514
6515   // Then, try to solve the above equation provided that Start is constant.
6516   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6517     return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6518                                         -StartC->getValue()->getValue(),
6519                                         *this);
6520   return getCouldNotCompute();
6521 }
6522
6523 /// HowFarToNonZero - Return the number of times a backedge checking the
6524 /// specified value for nonzero will execute.  If not computable, return
6525 /// CouldNotCompute
6526 ScalarEvolution::ExitLimit
6527 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
6528   // Loops that look like: while (X == 0) are very strange indeed.  We don't
6529   // handle them yet except for the trivial case.  This could be expanded in the
6530   // future as needed.
6531
6532   // If the value is a constant, check to see if it is known to be non-zero
6533   // already.  If so, the backedge will execute zero times.
6534   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6535     if (!C->getValue()->isNullValue())
6536       return getZero(C->getType());
6537     return getCouldNotCompute();  // Otherwise it will loop infinitely.
6538   }
6539
6540   // We could implement others, but I really doubt anyone writes loops like
6541   // this, and if they did, they would already be constant folded.
6542   return getCouldNotCompute();
6543 }
6544
6545 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6546 /// (which may not be an immediate predecessor) which has exactly one
6547 /// successor from which BB is reachable, or null if no such block is
6548 /// found.
6549 ///
6550 std::pair<BasicBlock *, BasicBlock *>
6551 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
6552   // If the block has a unique predecessor, then there is no path from the
6553   // predecessor to the block that does not go through the direct edge
6554   // from the predecessor to the block.
6555   if (BasicBlock *Pred = BB->getSinglePredecessor())
6556     return std::make_pair(Pred, BB);
6557
6558   // A loop's header is defined to be a block that dominates the loop.
6559   // If the header has a unique predecessor outside the loop, it must be
6560   // a block that has exactly one successor that can reach the loop.
6561   if (Loop *L = LI.getLoopFor(BB))
6562     return std::make_pair(L->getLoopPredecessor(), L->getHeader());
6563
6564   return std::pair<BasicBlock *, BasicBlock *>();
6565 }
6566
6567 /// HasSameValue - SCEV structural equivalence is usually sufficient for
6568 /// testing whether two expressions are equal, however for the purposes of
6569 /// looking for a condition guarding a loop, it can be useful to be a little
6570 /// more general, since a front-end may have replicated the controlling
6571 /// expression.
6572 ///
6573 static bool HasSameValue(const SCEV *A, const SCEV *B) {
6574   // Quick check to see if they are the same SCEV.
6575   if (A == B) return true;
6576
6577   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
6578     // Not all instructions that are "identical" compute the same value.  For
6579     // instance, two distinct alloca instructions allocating the same type are
6580     // identical and do not read memory; but compute distinct values.
6581     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
6582   };
6583
6584   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6585   // two different instructions with the same value. Check for this case.
6586   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6587     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6588       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6589         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
6590           if (ComputesEqualValues(AI, BI))
6591             return true;
6592
6593   // Otherwise assume they may have a different value.
6594   return false;
6595 }
6596
6597 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
6598 /// predicate Pred. Return true iff any changes were made.
6599 ///
6600 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
6601                                            const SCEV *&LHS, const SCEV *&RHS,
6602                                            unsigned Depth) {
6603   bool Changed = false;
6604
6605   // If we hit the max recursion limit bail out.
6606   if (Depth >= 3)
6607     return false;
6608
6609   // Canonicalize a constant to the right side.
6610   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6611     // Check for both operands constant.
6612     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6613       if (ConstantExpr::getICmp(Pred,
6614                                 LHSC->getValue(),
6615                                 RHSC->getValue())->isNullValue())
6616         goto trivially_false;
6617       else
6618         goto trivially_true;
6619     }
6620     // Otherwise swap the operands to put the constant on the right.
6621     std::swap(LHS, RHS);
6622     Pred = ICmpInst::getSwappedPredicate(Pred);
6623     Changed = true;
6624   }
6625
6626   // If we're comparing an addrec with a value which is loop-invariant in the
6627   // addrec's loop, put the addrec on the left. Also make a dominance check,
6628   // as both operands could be addrecs loop-invariant in each other's loop.
6629   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6630     const Loop *L = AR->getLoop();
6631     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
6632       std::swap(LHS, RHS);
6633       Pred = ICmpInst::getSwappedPredicate(Pred);
6634       Changed = true;
6635     }
6636   }
6637
6638   // If there's a constant operand, canonicalize comparisons with boundary
6639   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6640   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6641     const APInt &RA = RC->getValue()->getValue();
6642     switch (Pred) {
6643     default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6644     case ICmpInst::ICMP_EQ:
6645     case ICmpInst::ICMP_NE:
6646       // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6647       if (!RA)
6648         if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6649           if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
6650             if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6651                 ME->getOperand(0)->isAllOnesValue()) {
6652               RHS = AE->getOperand(1);
6653               LHS = ME->getOperand(1);
6654               Changed = true;
6655             }
6656       break;
6657     case ICmpInst::ICMP_UGE:
6658       if ((RA - 1).isMinValue()) {
6659         Pred = ICmpInst::ICMP_NE;
6660         RHS = getConstant(RA - 1);
6661         Changed = true;
6662         break;
6663       }
6664       if (RA.isMaxValue()) {
6665         Pred = ICmpInst::ICMP_EQ;
6666         Changed = true;
6667         break;
6668       }
6669       if (RA.isMinValue()) goto trivially_true;
6670
6671       Pred = ICmpInst::ICMP_UGT;
6672       RHS = getConstant(RA - 1);
6673       Changed = true;
6674       break;
6675     case ICmpInst::ICMP_ULE:
6676       if ((RA + 1).isMaxValue()) {
6677         Pred = ICmpInst::ICMP_NE;
6678         RHS = getConstant(RA + 1);
6679         Changed = true;
6680         break;
6681       }
6682       if (RA.isMinValue()) {
6683         Pred = ICmpInst::ICMP_EQ;
6684         Changed = true;
6685         break;
6686       }
6687       if (RA.isMaxValue()) goto trivially_true;
6688
6689       Pred = ICmpInst::ICMP_ULT;
6690       RHS = getConstant(RA + 1);
6691       Changed = true;
6692       break;
6693     case ICmpInst::ICMP_SGE:
6694       if ((RA - 1).isMinSignedValue()) {
6695         Pred = ICmpInst::ICMP_NE;
6696         RHS = getConstant(RA - 1);
6697         Changed = true;
6698         break;
6699       }
6700       if (RA.isMaxSignedValue()) {
6701         Pred = ICmpInst::ICMP_EQ;
6702         Changed = true;
6703         break;
6704       }
6705       if (RA.isMinSignedValue()) goto trivially_true;
6706
6707       Pred = ICmpInst::ICMP_SGT;
6708       RHS = getConstant(RA - 1);
6709       Changed = true;
6710       break;
6711     case ICmpInst::ICMP_SLE:
6712       if ((RA + 1).isMaxSignedValue()) {
6713         Pred = ICmpInst::ICMP_NE;
6714         RHS = getConstant(RA + 1);
6715         Changed = true;
6716         break;
6717       }
6718       if (RA.isMinSignedValue()) {
6719         Pred = ICmpInst::ICMP_EQ;
6720         Changed = true;
6721         break;
6722       }
6723       if (RA.isMaxSignedValue()) goto trivially_true;
6724
6725       Pred = ICmpInst::ICMP_SLT;
6726       RHS = getConstant(RA + 1);
6727       Changed = true;
6728       break;
6729     case ICmpInst::ICMP_UGT:
6730       if (RA.isMinValue()) {
6731         Pred = ICmpInst::ICMP_NE;
6732         Changed = true;
6733         break;
6734       }
6735       if ((RA + 1).isMaxValue()) {
6736         Pred = ICmpInst::ICMP_EQ;
6737         RHS = getConstant(RA + 1);
6738         Changed = true;
6739         break;
6740       }
6741       if (RA.isMaxValue()) goto trivially_false;
6742       break;
6743     case ICmpInst::ICMP_ULT:
6744       if (RA.isMaxValue()) {
6745         Pred = ICmpInst::ICMP_NE;
6746         Changed = true;
6747         break;
6748       }
6749       if ((RA - 1).isMinValue()) {
6750         Pred = ICmpInst::ICMP_EQ;
6751         RHS = getConstant(RA - 1);
6752         Changed = true;
6753         break;
6754       }
6755       if (RA.isMinValue()) goto trivially_false;
6756       break;
6757     case ICmpInst::ICMP_SGT:
6758       if (RA.isMinSignedValue()) {
6759         Pred = ICmpInst::ICMP_NE;
6760         Changed = true;
6761         break;
6762       }
6763       if ((RA + 1).isMaxSignedValue()) {
6764         Pred = ICmpInst::ICMP_EQ;
6765         RHS = getConstant(RA + 1);
6766         Changed = true;
6767         break;
6768       }
6769       if (RA.isMaxSignedValue()) goto trivially_false;
6770       break;
6771     case ICmpInst::ICMP_SLT:
6772       if (RA.isMaxSignedValue()) {
6773         Pred = ICmpInst::ICMP_NE;
6774         Changed = true;
6775         break;
6776       }
6777       if ((RA - 1).isMinSignedValue()) {
6778        Pred = ICmpInst::ICMP_EQ;
6779        RHS = getConstant(RA - 1);
6780         Changed = true;
6781        break;
6782       }
6783       if (RA.isMinSignedValue()) goto trivially_false;
6784       break;
6785     }
6786   }
6787
6788   // Check for obvious equality.
6789   if (HasSameValue(LHS, RHS)) {
6790     if (ICmpInst::isTrueWhenEqual(Pred))
6791       goto trivially_true;
6792     if (ICmpInst::isFalseWhenEqual(Pred))
6793       goto trivially_false;
6794   }
6795
6796   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6797   // adding or subtracting 1 from one of the operands.
6798   switch (Pred) {
6799   case ICmpInst::ICMP_SLE:
6800     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6801       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6802                        SCEV::FlagNSW);
6803       Pred = ICmpInst::ICMP_SLT;
6804       Changed = true;
6805     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
6806       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6807                        SCEV::FlagNSW);
6808       Pred = ICmpInst::ICMP_SLT;
6809       Changed = true;
6810     }
6811     break;
6812   case ICmpInst::ICMP_SGE:
6813     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
6814       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6815                        SCEV::FlagNSW);
6816       Pred = ICmpInst::ICMP_SGT;
6817       Changed = true;
6818     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6819       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6820                        SCEV::FlagNSW);
6821       Pred = ICmpInst::ICMP_SGT;
6822       Changed = true;
6823     }
6824     break;
6825   case ICmpInst::ICMP_ULE:
6826     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
6827       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6828                        SCEV::FlagNUW);
6829       Pred = ICmpInst::ICMP_ULT;
6830       Changed = true;
6831     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
6832       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6833                        SCEV::FlagNUW);
6834       Pred = ICmpInst::ICMP_ULT;
6835       Changed = true;
6836     }
6837     break;
6838   case ICmpInst::ICMP_UGE:
6839     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
6840       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6841                        SCEV::FlagNUW);
6842       Pred = ICmpInst::ICMP_UGT;
6843       Changed = true;
6844     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
6845       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6846                        SCEV::FlagNUW);
6847       Pred = ICmpInst::ICMP_UGT;
6848       Changed = true;
6849     }
6850     break;
6851   default:
6852     break;
6853   }
6854
6855   // TODO: More simplifications are possible here.
6856
6857   // Recursively simplify until we either hit a recursion limit or nothing
6858   // changes.
6859   if (Changed)
6860     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6861
6862   return Changed;
6863
6864 trivially_true:
6865   // Return 0 == 0.
6866   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6867   Pred = ICmpInst::ICMP_EQ;
6868   return true;
6869
6870 trivially_false:
6871   // Return 0 != 0.
6872   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6873   Pred = ICmpInst::ICMP_NE;
6874   return true;
6875 }
6876
6877 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6878   return getSignedRange(S).getSignedMax().isNegative();
6879 }
6880
6881 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6882   return getSignedRange(S).getSignedMin().isStrictlyPositive();
6883 }
6884
6885 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6886   return !getSignedRange(S).getSignedMin().isNegative();
6887 }
6888
6889 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6890   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6891 }
6892
6893 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6894   return isKnownNegative(S) || isKnownPositive(S);
6895 }
6896
6897 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6898                                        const SCEV *LHS, const SCEV *RHS) {
6899   // Canonicalize the inputs first.
6900   (void)SimplifyICmpOperands(Pred, LHS, RHS);
6901
6902   // If LHS or RHS is an addrec, check to see if the condition is true in
6903   // every iteration of the loop.
6904   // If LHS and RHS are both addrec, both conditions must be true in
6905   // every iteration of the loop.
6906   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6907   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6908   bool LeftGuarded = false;
6909   bool RightGuarded = false;
6910   if (LAR) {
6911     const Loop *L = LAR->getLoop();
6912     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6913         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6914       if (!RAR) return true;
6915       LeftGuarded = true;
6916     }
6917   }
6918   if (RAR) {
6919     const Loop *L = RAR->getLoop();
6920     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6921         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6922       if (!LAR) return true;
6923       RightGuarded = true;
6924     }
6925   }
6926   if (LeftGuarded && RightGuarded)
6927     return true;
6928
6929   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
6930     return true;
6931
6932   // Otherwise see what can be done with known constant ranges.
6933   return isKnownPredicateWithRanges(Pred, LHS, RHS);
6934 }
6935
6936 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
6937                                            ICmpInst::Predicate Pred,
6938                                            bool &Increasing) {
6939   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
6940
6941 #ifndef NDEBUG
6942   // Verify an invariant: inverting the predicate should turn a monotonically
6943   // increasing change to a monotonically decreasing one, and vice versa.
6944   bool IncreasingSwapped;
6945   bool ResultSwapped = isMonotonicPredicateImpl(
6946       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
6947
6948   assert(Result == ResultSwapped && "should be able to analyze both!");
6949   if (ResultSwapped)
6950     assert(Increasing == !IncreasingSwapped &&
6951            "monotonicity should flip as we flip the predicate");
6952 #endif
6953
6954   return Result;
6955 }
6956
6957 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
6958                                                ICmpInst::Predicate Pred,
6959                                                bool &Increasing) {
6960
6961   // A zero step value for LHS means the induction variable is essentially a
6962   // loop invariant value. We don't really depend on the predicate actually
6963   // flipping from false to true (for increasing predicates, and the other way
6964   // around for decreasing predicates), all we care about is that *if* the
6965   // predicate changes then it only changes from false to true.
6966   //
6967   // A zero step value in itself is not very useful, but there may be places
6968   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
6969   // as general as possible.
6970
6971   switch (Pred) {
6972   default:
6973     return false; // Conservative answer
6974
6975   case ICmpInst::ICMP_UGT:
6976   case ICmpInst::ICMP_UGE:
6977   case ICmpInst::ICMP_ULT:
6978   case ICmpInst::ICMP_ULE:
6979     if (!LHS->getNoWrapFlags(SCEV::FlagNUW))
6980       return false;
6981
6982     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
6983     return true;
6984
6985   case ICmpInst::ICMP_SGT:
6986   case ICmpInst::ICMP_SGE:
6987   case ICmpInst::ICMP_SLT:
6988   case ICmpInst::ICMP_SLE: {
6989     if (!LHS->getNoWrapFlags(SCEV::FlagNSW))
6990       return false;
6991
6992     const SCEV *Step = LHS->getStepRecurrence(*this);
6993
6994     if (isKnownNonNegative(Step)) {
6995       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
6996       return true;
6997     }
6998
6999     if (isKnownNonPositive(Step)) {
7000       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7001       return true;
7002     }
7003
7004     return false;
7005   }
7006
7007   }
7008
7009   llvm_unreachable("switch has default clause!");
7010 }
7011
7012 bool ScalarEvolution::isLoopInvariantPredicate(
7013     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7014     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7015     const SCEV *&InvariantRHS) {
7016
7017   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7018   if (!isLoopInvariant(RHS, L)) {
7019     if (!isLoopInvariant(LHS, L))
7020       return false;
7021
7022     std::swap(LHS, RHS);
7023     Pred = ICmpInst::getSwappedPredicate(Pred);
7024   }
7025
7026   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7027   if (!ArLHS || ArLHS->getLoop() != L)
7028     return false;
7029
7030   bool Increasing;
7031   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7032     return false;
7033
7034   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7035   // true as the loop iterates, and the backedge is control dependent on
7036   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7037   //
7038   //   * if the predicate was false in the first iteration then the predicate
7039   //     is never evaluated again, since the loop exits without taking the
7040   //     backedge.
7041   //   * if the predicate was true in the first iteration then it will
7042   //     continue to be true for all future iterations since it is
7043   //     monotonically increasing.
7044   //
7045   // For both the above possibilities, we can replace the loop varying
7046   // predicate with its value on the first iteration of the loop (which is
7047   // loop invariant).
7048   //
7049   // A similar reasoning applies for a monotonically decreasing predicate, by
7050   // replacing true with false and false with true in the above two bullets.
7051
7052   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7053
7054   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7055     return false;
7056
7057   InvariantPred = Pred;
7058   InvariantLHS = ArLHS->getStart();
7059   InvariantRHS = RHS;
7060   return true;
7061 }
7062
7063 bool
7064 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
7065                                             const SCEV *LHS, const SCEV *RHS) {
7066   if (HasSameValue(LHS, RHS))
7067     return ICmpInst::isTrueWhenEqual(Pred);
7068
7069   // This code is split out from isKnownPredicate because it is called from
7070   // within isLoopEntryGuardedByCond.
7071   switch (Pred) {
7072   default:
7073     llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7074   case ICmpInst::ICMP_SGT:
7075     std::swap(LHS, RHS);
7076   case ICmpInst::ICMP_SLT: {
7077     ConstantRange LHSRange = getSignedRange(LHS);
7078     ConstantRange RHSRange = getSignedRange(RHS);
7079     if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
7080       return true;
7081     if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
7082       return false;
7083     break;
7084   }
7085   case ICmpInst::ICMP_SGE:
7086     std::swap(LHS, RHS);
7087   case ICmpInst::ICMP_SLE: {
7088     ConstantRange LHSRange = getSignedRange(LHS);
7089     ConstantRange RHSRange = getSignedRange(RHS);
7090     if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
7091       return true;
7092     if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
7093       return false;
7094     break;
7095   }
7096   case ICmpInst::ICMP_UGT:
7097     std::swap(LHS, RHS);
7098   case ICmpInst::ICMP_ULT: {
7099     ConstantRange LHSRange = getUnsignedRange(LHS);
7100     ConstantRange RHSRange = getUnsignedRange(RHS);
7101     if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
7102       return true;
7103     if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
7104       return false;
7105     break;
7106   }
7107   case ICmpInst::ICMP_UGE:
7108     std::swap(LHS, RHS);
7109   case ICmpInst::ICMP_ULE: {
7110     ConstantRange LHSRange = getUnsignedRange(LHS);
7111     ConstantRange RHSRange = getUnsignedRange(RHS);
7112     if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
7113       return true;
7114     if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
7115       return false;
7116     break;
7117   }
7118   case ICmpInst::ICMP_NE: {
7119     if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
7120       return true;
7121     if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
7122       return true;
7123
7124     const SCEV *Diff = getMinusSCEV(LHS, RHS);
7125     if (isKnownNonZero(Diff))
7126       return true;
7127     break;
7128   }
7129   case ICmpInst::ICMP_EQ:
7130     // The check at the top of the function catches the case where
7131     // the values are known to be equal.
7132     break;
7133   }
7134   return false;
7135 }
7136
7137 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7138                                                    const SCEV *LHS,
7139                                                    const SCEV *RHS) {
7140   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7141     return false;
7142
7143   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7144   // the stack can result in exponential time complexity.
7145   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7146
7147   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7148   //
7149   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7150   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7151   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7152   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7153   // use isKnownPredicate later if needed.
7154   if (isKnownNonNegative(RHS) &&
7155       isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7156       isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS))
7157     return true;
7158
7159   return false;
7160 }
7161
7162 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7163 /// protected by a conditional between LHS and RHS.  This is used to
7164 /// to eliminate casts.
7165 bool
7166 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7167                                              ICmpInst::Predicate Pred,
7168                                              const SCEV *LHS, const SCEV *RHS) {
7169   // Interpret a null as meaning no loop, where there is obviously no guard
7170   // (interprocedural conditions notwithstanding).
7171   if (!L) return true;
7172
7173   if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
7174
7175   BasicBlock *Latch = L->getLoopLatch();
7176   if (!Latch)
7177     return false;
7178
7179   BranchInst *LoopContinuePredicate =
7180     dyn_cast<BranchInst>(Latch->getTerminator());
7181   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7182       isImpliedCond(Pred, LHS, RHS,
7183                     LoopContinuePredicate->getCondition(),
7184                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7185     return true;
7186
7187   // We don't want more than one activation of the following loops on the stack
7188   // -- that can lead to O(n!) time complexity.
7189   if (WalkingBEDominatingConds)
7190     return false;
7191
7192   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7193
7194   // See if we can exploit a trip count to prove the predicate.
7195   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7196   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7197   if (LatchBECount != getCouldNotCompute()) {
7198     // We know that Latch branches back to the loop header exactly
7199     // LatchBECount times.  This means the backdege condition at Latch is
7200     // equivalent to  "{0,+,1} u< LatchBECount".
7201     Type *Ty = LatchBECount->getType();
7202     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7203     const SCEV *LoopCounter =
7204       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7205     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7206                       LatchBECount))
7207       return true;
7208   }
7209
7210   // Check conditions due to any @llvm.assume intrinsics.
7211   for (auto &AssumeVH : AC.assumptions()) {
7212     if (!AssumeVH)
7213       continue;
7214     auto *CI = cast<CallInst>(AssumeVH);
7215     if (!DT.dominates(CI, Latch->getTerminator()))
7216       continue;
7217
7218     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7219       return true;
7220   }
7221
7222   // If the loop is not reachable from the entry block, we risk running into an
7223   // infinite loop as we walk up into the dom tree.  These loops do not matter
7224   // anyway, so we just return a conservative answer when we see them.
7225   if (!DT.isReachableFromEntry(L->getHeader()))
7226     return false;
7227
7228   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7229        DTN != HeaderDTN; DTN = DTN->getIDom()) {
7230
7231     assert(DTN && "should reach the loop header before reaching the root!");
7232
7233     BasicBlock *BB = DTN->getBlock();
7234     BasicBlock *PBB = BB->getSinglePredecessor();
7235     if (!PBB)
7236       continue;
7237
7238     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7239     if (!ContinuePredicate || !ContinuePredicate->isConditional())
7240       continue;
7241
7242     Value *Condition = ContinuePredicate->getCondition();
7243
7244     // If we have an edge `E` within the loop body that dominates the only
7245     // latch, the condition guarding `E` also guards the backedge.  This
7246     // reasoning works only for loops with a single latch.
7247
7248     BasicBlockEdge DominatingEdge(PBB, BB);
7249     if (DominatingEdge.isSingleEdge()) {
7250       // We're constructively (and conservatively) enumerating edges within the
7251       // loop body that dominate the latch.  The dominator tree better agree
7252       // with us on this:
7253       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
7254
7255       if (isImpliedCond(Pred, LHS, RHS, Condition,
7256                         BB != ContinuePredicate->getSuccessor(0)))
7257         return true;
7258     }
7259   }
7260
7261   return false;
7262 }
7263
7264 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
7265 /// by a conditional between LHS and RHS.  This is used to help avoid max
7266 /// expressions in loop trip counts, and to eliminate casts.
7267 bool
7268 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7269                                           ICmpInst::Predicate Pred,
7270                                           const SCEV *LHS, const SCEV *RHS) {
7271   // Interpret a null as meaning no loop, where there is obviously no guard
7272   // (interprocedural conditions notwithstanding).
7273   if (!L) return false;
7274
7275   if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
7276
7277   // Starting at the loop predecessor, climb up the predecessor chain, as long
7278   // as there are predecessors that can be found that have unique successors
7279   // leading to the original header.
7280   for (std::pair<BasicBlock *, BasicBlock *>
7281          Pair(L->getLoopPredecessor(), L->getHeader());
7282        Pair.first;
7283        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
7284
7285     BranchInst *LoopEntryPredicate =
7286       dyn_cast<BranchInst>(Pair.first->getTerminator());
7287     if (!LoopEntryPredicate ||
7288         LoopEntryPredicate->isUnconditional())
7289       continue;
7290
7291     if (isImpliedCond(Pred, LHS, RHS,
7292                       LoopEntryPredicate->getCondition(),
7293                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
7294       return true;
7295   }
7296
7297   // Check conditions due to any @llvm.assume intrinsics.
7298   for (auto &AssumeVH : AC.assumptions()) {
7299     if (!AssumeVH)
7300       continue;
7301     auto *CI = cast<CallInst>(AssumeVH);
7302     if (!DT.dominates(CI, L->getHeader()))
7303       continue;
7304
7305     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7306       return true;
7307   }
7308
7309   return false;
7310 }
7311
7312 /// RAII wrapper to prevent recursive application of isImpliedCond.
7313 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
7314 /// currently evaluating isImpliedCond.
7315 struct MarkPendingLoopPredicate {
7316   Value *Cond;
7317   DenseSet<Value*> &LoopPreds;
7318   bool Pending;
7319
7320   MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
7321     : Cond(C), LoopPreds(LP) {
7322     Pending = !LoopPreds.insert(Cond).second;
7323   }
7324   ~MarkPendingLoopPredicate() {
7325     if (!Pending)
7326       LoopPreds.erase(Cond);
7327   }
7328 };
7329
7330 /// isImpliedCond - Test whether the condition described by Pred, LHS,
7331 /// and RHS is true whenever the given Cond value evaluates to true.
7332 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
7333                                     const SCEV *LHS, const SCEV *RHS,
7334                                     Value *FoundCondValue,
7335                                     bool Inverse) {
7336   MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
7337   if (Mark.Pending)
7338     return false;
7339
7340   // Recursively handle And and Or conditions.
7341   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
7342     if (BO->getOpcode() == Instruction::And) {
7343       if (!Inverse)
7344         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7345                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
7346     } else if (BO->getOpcode() == Instruction::Or) {
7347       if (Inverse)
7348         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7349                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
7350     }
7351   }
7352
7353   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
7354   if (!ICI) return false;
7355
7356   // Now that we found a conditional branch that dominates the loop or controls
7357   // the loop latch. Check to see if it is the comparison we are looking for.
7358   ICmpInst::Predicate FoundPred;
7359   if (Inverse)
7360     FoundPred = ICI->getInversePredicate();
7361   else
7362     FoundPred = ICI->getPredicate();
7363
7364   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
7365   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
7366
7367   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
7368 }
7369
7370 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
7371                                     const SCEV *RHS,
7372                                     ICmpInst::Predicate FoundPred,
7373                                     const SCEV *FoundLHS,
7374                                     const SCEV *FoundRHS) {
7375   // Balance the types.
7376   if (getTypeSizeInBits(LHS->getType()) <
7377       getTypeSizeInBits(FoundLHS->getType())) {
7378     if (CmpInst::isSigned(Pred)) {
7379       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
7380       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
7381     } else {
7382       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
7383       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
7384     }
7385   } else if (getTypeSizeInBits(LHS->getType()) >
7386       getTypeSizeInBits(FoundLHS->getType())) {
7387     if (CmpInst::isSigned(FoundPred)) {
7388       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
7389       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
7390     } else {
7391       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
7392       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
7393     }
7394   }
7395
7396   // Canonicalize the query to match the way instcombine will have
7397   // canonicalized the comparison.
7398   if (SimplifyICmpOperands(Pred, LHS, RHS))
7399     if (LHS == RHS)
7400       return CmpInst::isTrueWhenEqual(Pred);
7401   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
7402     if (FoundLHS == FoundRHS)
7403       return CmpInst::isFalseWhenEqual(FoundPred);
7404
7405   // Check to see if we can make the LHS or RHS match.
7406   if (LHS == FoundRHS || RHS == FoundLHS) {
7407     if (isa<SCEVConstant>(RHS)) {
7408       std::swap(FoundLHS, FoundRHS);
7409       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
7410     } else {
7411       std::swap(LHS, RHS);
7412       Pred = ICmpInst::getSwappedPredicate(Pred);
7413     }
7414   }
7415
7416   // Check whether the found predicate is the same as the desired predicate.
7417   if (FoundPred == Pred)
7418     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7419
7420   // Check whether swapping the found predicate makes it the same as the
7421   // desired predicate.
7422   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
7423     if (isa<SCEVConstant>(RHS))
7424       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
7425     else
7426       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
7427                                    RHS, LHS, FoundLHS, FoundRHS);
7428   }
7429
7430   // Check if we can make progress by sharpening ranges.
7431   if (FoundPred == ICmpInst::ICMP_NE &&
7432       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
7433
7434     const SCEVConstant *C = nullptr;
7435     const SCEV *V = nullptr;
7436
7437     if (isa<SCEVConstant>(FoundLHS)) {
7438       C = cast<SCEVConstant>(FoundLHS);
7439       V = FoundRHS;
7440     } else {
7441       C = cast<SCEVConstant>(FoundRHS);
7442       V = FoundLHS;
7443     }
7444
7445     // The guarding predicate tells us that C != V. If the known range
7446     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
7447     // range we consider has to correspond to same signedness as the
7448     // predicate we're interested in folding.
7449
7450     APInt Min = ICmpInst::isSigned(Pred) ?
7451         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
7452
7453     if (Min == C->getValue()->getValue()) {
7454       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
7455       // This is true even if (Min + 1) wraps around -- in case of
7456       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
7457
7458       APInt SharperMin = Min + 1;
7459
7460       switch (Pred) {
7461         case ICmpInst::ICMP_SGE:
7462         case ICmpInst::ICMP_UGE:
7463           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
7464           // RHS, we're done.
7465           if (isImpliedCondOperands(Pred, LHS, RHS, V,
7466                                     getConstant(SharperMin)))
7467             return true;
7468
7469         case ICmpInst::ICMP_SGT:
7470         case ICmpInst::ICMP_UGT:
7471           // We know from the range information that (V `Pred` Min ||
7472           // V == Min).  We know from the guarding condition that !(V
7473           // == Min).  This gives us
7474           //
7475           //       V `Pred` Min || V == Min && !(V == Min)
7476           //   =>  V `Pred` Min
7477           //
7478           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
7479
7480           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
7481             return true;
7482
7483         default:
7484           // No change
7485           break;
7486       }
7487     }
7488   }
7489
7490   // Check whether the actual condition is beyond sufficient.
7491   if (FoundPred == ICmpInst::ICMP_EQ)
7492     if (ICmpInst::isTrueWhenEqual(Pred))
7493       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
7494         return true;
7495   if (Pred == ICmpInst::ICMP_NE)
7496     if (!ICmpInst::isTrueWhenEqual(FoundPred))
7497       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
7498         return true;
7499
7500   // Otherwise assume the worst.
7501   return false;
7502 }
7503
7504 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
7505                                      const SCEV *&L, const SCEV *&R,
7506                                      SCEV::NoWrapFlags &Flags) {
7507   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
7508   if (!AE || AE->getNumOperands() != 2)
7509     return false;
7510
7511   L = AE->getOperand(0);
7512   R = AE->getOperand(1);
7513   Flags = AE->getNoWrapFlags();
7514   return true;
7515 }
7516
7517 bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
7518                                                 const SCEV *More,
7519                                                 APInt &C) {
7520   // We avoid subtracting expressions here because this function is usually
7521   // fairly deep in the call stack (i.e. is called many times).
7522
7523   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
7524     const auto *LAR = cast<SCEVAddRecExpr>(Less);
7525     const auto *MAR = cast<SCEVAddRecExpr>(More);
7526
7527     if (LAR->getLoop() != MAR->getLoop())
7528       return false;
7529
7530     // We look at affine expressions only; not for correctness but to keep
7531     // getStepRecurrence cheap.
7532     if (!LAR->isAffine() || !MAR->isAffine())
7533       return false;
7534
7535     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
7536       return false;
7537
7538     Less = LAR->getStart();
7539     More = MAR->getStart();
7540
7541     // fall through
7542   }
7543
7544   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
7545     const auto &M = cast<SCEVConstant>(More)->getValue()->getValue();
7546     const auto &L = cast<SCEVConstant>(Less)->getValue()->getValue();
7547     C = M - L;
7548     return true;
7549   }
7550
7551   const SCEV *L, *R;
7552   SCEV::NoWrapFlags Flags;
7553   if (splitBinaryAdd(Less, L, R, Flags))
7554     if (const auto *LC = dyn_cast<SCEVConstant>(L))
7555       if (R == More) {
7556         C = -(LC->getValue()->getValue());
7557         return true;
7558       }
7559
7560   if (splitBinaryAdd(More, L, R, Flags))
7561     if (const auto *LC = dyn_cast<SCEVConstant>(L))
7562       if (R == Less) {
7563         C = LC->getValue()->getValue();
7564         return true;
7565       }
7566
7567   return false;
7568 }
7569
7570 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
7571     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
7572     const SCEV *FoundLHS, const SCEV *FoundRHS) {
7573   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
7574     return false;
7575
7576   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7577   if (!AddRecLHS)
7578     return false;
7579
7580   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
7581   if (!AddRecFoundLHS)
7582     return false;
7583
7584   // We'd like to let SCEV reason about control dependencies, so we constrain
7585   // both the inequalities to be about add recurrences on the same loop.  This
7586   // way we can use isLoopEntryGuardedByCond later.
7587
7588   const Loop *L = AddRecFoundLHS->getLoop();
7589   if (L != AddRecLHS->getLoop())
7590     return false;
7591
7592   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
7593   //
7594   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
7595   //                                                                  ... (2)
7596   //
7597   // Informal proof for (2), assuming (1) [*]:
7598   //
7599   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
7600   //
7601   // Then
7602   //
7603   //       FoundLHS s< FoundRHS s< INT_MIN - C
7604   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
7605   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
7606   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
7607   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
7608   // <=>  FoundLHS + C s< FoundRHS + C
7609   //
7610   // [*]: (1) can be proved by ruling out overflow.
7611   //
7612   // [**]: This can be proved by analyzing all the four possibilities:
7613   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
7614   //    (A s>= 0, B s>= 0).
7615   //
7616   // Note:
7617   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
7618   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
7619   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
7620   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
7621   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
7622   // C)".
7623
7624   APInt LDiff, RDiff;
7625   if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
7626       !computeConstantDifference(FoundRHS, RHS, RDiff) ||
7627       LDiff != RDiff)
7628     return false;
7629
7630   if (LDiff == 0)
7631     return true;
7632
7633   APInt FoundRHSLimit;
7634
7635   if (Pred == CmpInst::ICMP_ULT) {
7636     FoundRHSLimit = -RDiff;
7637   } else {
7638     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
7639     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
7640   }
7641
7642   // Try to prove (1) or (2), as needed.
7643   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
7644                                   getConstant(FoundRHSLimit));
7645 }
7646
7647 /// isImpliedCondOperands - Test whether the condition described by Pred,
7648 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
7649 /// and FoundRHS is true.
7650 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
7651                                             const SCEV *LHS, const SCEV *RHS,
7652                                             const SCEV *FoundLHS,
7653                                             const SCEV *FoundRHS) {
7654   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
7655     return true;
7656
7657   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
7658     return true;
7659
7660   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
7661                                      FoundLHS, FoundRHS) ||
7662          // ~x < ~y --> x > y
7663          isImpliedCondOperandsHelper(Pred, LHS, RHS,
7664                                      getNotSCEV(FoundRHS),
7665                                      getNotSCEV(FoundLHS));
7666 }
7667
7668
7669 /// If Expr computes ~A, return A else return nullptr
7670 static const SCEV *MatchNotExpr(const SCEV *Expr) {
7671   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
7672   if (!Add || Add->getNumOperands() != 2 ||
7673       !Add->getOperand(0)->isAllOnesValue())
7674     return nullptr;
7675
7676   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
7677   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
7678       !AddRHS->getOperand(0)->isAllOnesValue())
7679     return nullptr;
7680
7681   return AddRHS->getOperand(1);
7682 }
7683
7684
7685 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
7686 template<typename MaxExprType>
7687 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
7688                               const SCEV *Candidate) {
7689   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
7690   if (!MaxExpr) return false;
7691
7692   auto It = std::find(MaxExpr->op_begin(), MaxExpr->op_end(), Candidate);
7693   return It != MaxExpr->op_end();
7694 }
7695
7696
7697 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
7698 template<typename MaxExprType>
7699 static bool IsMinConsistingOf(ScalarEvolution &SE,
7700                               const SCEV *MaybeMinExpr,
7701                               const SCEV *Candidate) {
7702   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
7703   if (!MaybeMaxExpr)
7704     return false;
7705
7706   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
7707 }
7708
7709 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
7710                                            ICmpInst::Predicate Pred,
7711                                            const SCEV *LHS, const SCEV *RHS) {
7712
7713   // If both sides are affine addrecs for the same loop, with equal
7714   // steps, and we know the recurrences don't wrap, then we only
7715   // need to check the predicate on the starting values.
7716
7717   if (!ICmpInst::isRelational(Pred))
7718     return false;
7719
7720   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7721   if (!LAR)
7722     return false;
7723   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7724   if (!RAR)
7725     return false;
7726   if (LAR->getLoop() != RAR->getLoop())
7727     return false;
7728   if (!LAR->isAffine() || !RAR->isAffine())
7729     return false;
7730
7731   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
7732     return false;
7733
7734   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
7735                          SCEV::FlagNSW : SCEV::FlagNUW;
7736   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
7737     return false;
7738
7739   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
7740 }
7741
7742 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
7743 /// expression?
7744 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
7745                                         ICmpInst::Predicate Pred,
7746                                         const SCEV *LHS, const SCEV *RHS) {
7747   switch (Pred) {
7748   default:
7749     return false;
7750
7751   case ICmpInst::ICMP_SGE:
7752     std::swap(LHS, RHS);
7753     // fall through
7754   case ICmpInst::ICMP_SLE:
7755     return
7756       // min(A, ...) <= A
7757       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
7758       // A <= max(A, ...)
7759       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
7760
7761   case ICmpInst::ICMP_UGE:
7762     std::swap(LHS, RHS);
7763     // fall through
7764   case ICmpInst::ICMP_ULE:
7765     return
7766       // min(A, ...) <= A
7767       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
7768       // A <= max(A, ...)
7769       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
7770   }
7771
7772   llvm_unreachable("covered switch fell through?!");
7773 }
7774
7775 /// isImpliedCondOperandsHelper - Test whether the condition described by
7776 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
7777 /// FoundLHS, and FoundRHS is true.
7778 bool
7779 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
7780                                              const SCEV *LHS, const SCEV *RHS,
7781                                              const SCEV *FoundLHS,
7782                                              const SCEV *FoundRHS) {
7783   auto IsKnownPredicateFull =
7784       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7785     return isKnownPredicateWithRanges(Pred, LHS, RHS) ||
7786         IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
7787         IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS);
7788   };
7789
7790   switch (Pred) {
7791   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7792   case ICmpInst::ICMP_EQ:
7793   case ICmpInst::ICMP_NE:
7794     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
7795       return true;
7796     break;
7797   case ICmpInst::ICMP_SLT:
7798   case ICmpInst::ICMP_SLE:
7799     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
7800         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
7801       return true;
7802     break;
7803   case ICmpInst::ICMP_SGT:
7804   case ICmpInst::ICMP_SGE:
7805     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
7806         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
7807       return true;
7808     break;
7809   case ICmpInst::ICMP_ULT:
7810   case ICmpInst::ICMP_ULE:
7811     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
7812         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
7813       return true;
7814     break;
7815   case ICmpInst::ICMP_UGT:
7816   case ICmpInst::ICMP_UGE:
7817     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
7818         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
7819       return true;
7820     break;
7821   }
7822
7823   return false;
7824 }
7825
7826 /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands.
7827 /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1".
7828 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
7829                                                      const SCEV *LHS,
7830                                                      const SCEV *RHS,
7831                                                      const SCEV *FoundLHS,
7832                                                      const SCEV *FoundRHS) {
7833   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
7834     // The restriction on `FoundRHS` be lifted easily -- it exists only to
7835     // reduce the compile time impact of this optimization.
7836     return false;
7837
7838   const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
7839   if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
7840       !isa<SCEVConstant>(AddLHS->getOperand(0)))
7841     return false;
7842
7843   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getValue()->getValue();
7844
7845   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
7846   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
7847   ConstantRange FoundLHSRange =
7848       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
7849
7850   // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
7851   // for `LHS`:
7852   APInt Addend =
7853       cast<SCEVConstant>(AddLHS->getOperand(0))->getValue()->getValue();
7854   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
7855
7856   // We can also compute the range of values for `LHS` that satisfy the
7857   // consequent, "`LHS` `Pred` `RHS`":
7858   APInt ConstRHS = cast<SCEVConstant>(RHS)->getValue()->getValue();
7859   ConstantRange SatisfyingLHSRange =
7860       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
7861
7862   // The antecedent implies the consequent if every value of `LHS` that
7863   // satisfies the antecedent also satisfies the consequent.
7864   return SatisfyingLHSRange.contains(LHSRange);
7865 }
7866
7867 // Verify if an linear IV with positive stride can overflow when in a
7868 // less-than comparison, knowing the invariant term of the comparison, the
7869 // stride and the knowledge of NSW/NUW flags on the recurrence.
7870 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
7871                                          bool IsSigned, bool NoWrap) {
7872   if (NoWrap) return false;
7873
7874   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7875   const SCEV *One = getOne(Stride->getType());
7876
7877   if (IsSigned) {
7878     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
7879     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
7880     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7881                                 .getSignedMax();
7882
7883     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
7884     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
7885   }
7886
7887   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
7888   APInt MaxValue = APInt::getMaxValue(BitWidth);
7889   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7890                               .getUnsignedMax();
7891
7892   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
7893   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
7894 }
7895
7896 // Verify if an linear IV with negative stride can overflow when in a
7897 // greater-than comparison, knowing the invariant term of the comparison,
7898 // the stride and the knowledge of NSW/NUW flags on the recurrence.
7899 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
7900                                          bool IsSigned, bool NoWrap) {
7901   if (NoWrap) return false;
7902
7903   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7904   const SCEV *One = getOne(Stride->getType());
7905
7906   if (IsSigned) {
7907     APInt MinRHS = getSignedRange(RHS).getSignedMin();
7908     APInt MinValue = APInt::getSignedMinValue(BitWidth);
7909     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7910                                .getSignedMax();
7911
7912     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
7913     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
7914   }
7915
7916   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
7917   APInt MinValue = APInt::getMinValue(BitWidth);
7918   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7919                             .getUnsignedMax();
7920
7921   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
7922   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
7923 }
7924
7925 // Compute the backedge taken count knowing the interval difference, the
7926 // stride and presence of the equality in the comparison.
7927 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
7928                                             bool Equality) {
7929   const SCEV *One = getOne(Step->getType());
7930   Delta = Equality ? getAddExpr(Delta, Step)
7931                    : getAddExpr(Delta, getMinusSCEV(Step, One));
7932   return getUDivExpr(Delta, Step);
7933 }
7934
7935 /// HowManyLessThans - Return the number of times a backedge containing the
7936 /// specified less-than comparison will execute.  If not computable, return
7937 /// CouldNotCompute.
7938 ///
7939 /// @param ControlsExit is true when the LHS < RHS condition directly controls
7940 /// the branch (loops exits only if condition is true). In this case, we can use
7941 /// NoWrapFlags to skip overflow checks.
7942 ScalarEvolution::ExitLimit
7943 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
7944                                   const Loop *L, bool IsSigned,
7945                                   bool ControlsExit) {
7946   // We handle only IV < Invariant
7947   if (!isLoopInvariant(RHS, L))
7948     return getCouldNotCompute();
7949
7950   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7951
7952   // Avoid weird loops
7953   if (!IV || IV->getLoop() != L || !IV->isAffine())
7954     return getCouldNotCompute();
7955
7956   bool NoWrap = ControlsExit &&
7957                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7958
7959   const SCEV *Stride = IV->getStepRecurrence(*this);
7960
7961   // Avoid negative or zero stride values
7962   if (!isKnownPositive(Stride))
7963     return getCouldNotCompute();
7964
7965   // Avoid proven overflow cases: this will ensure that the backedge taken count
7966   // will not generate any unsigned overflow. Relaxed no-overflow conditions
7967   // exploit NoWrapFlags, allowing to optimize in presence of undefined
7968   // behaviors like the case of C language.
7969   if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
7970     return getCouldNotCompute();
7971
7972   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
7973                                       : ICmpInst::ICMP_ULT;
7974   const SCEV *Start = IV->getStart();
7975   const SCEV *End = RHS;
7976   if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
7977     const SCEV *Diff = getMinusSCEV(RHS, Start);
7978     // If we have NoWrap set, then we can assume that the increment won't
7979     // overflow, in which case if RHS - Start is a constant, we don't need to
7980     // do a max operation since we can just figure it out statically
7981     if (NoWrap && isa<SCEVConstant>(Diff)) {
7982       APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7983       if (D.isNegative())
7984         End = Start;
7985     } else
7986       End = IsSigned ? getSMaxExpr(RHS, Start)
7987                      : getUMaxExpr(RHS, Start);
7988   }
7989
7990   const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
7991
7992   APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
7993                             : getUnsignedRange(Start).getUnsignedMin();
7994
7995   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7996                              : getUnsignedRange(Stride).getUnsignedMin();
7997
7998   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7999   APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8000                          : APInt::getMaxValue(BitWidth) - (MinStride - 1);
8001
8002   // Although End can be a MAX expression we estimate MaxEnd considering only
8003   // the case End = RHS. This is safe because in the other case (End - Start)
8004   // is zero, leading to a zero maximum backedge taken count.
8005   APInt MaxEnd =
8006     IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8007              : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8008
8009   const SCEV *MaxBECount;
8010   if (isa<SCEVConstant>(BECount))
8011     MaxBECount = BECount;
8012   else
8013     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8014                                 getConstant(MinStride), false);
8015
8016   if (isa<SCEVCouldNotCompute>(MaxBECount))
8017     MaxBECount = BECount;
8018
8019   return ExitLimit(BECount, MaxBECount);
8020 }
8021
8022 ScalarEvolution::ExitLimit
8023 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8024                                      const Loop *L, bool IsSigned,
8025                                      bool ControlsExit) {
8026   // We handle only IV > Invariant
8027   if (!isLoopInvariant(RHS, L))
8028     return getCouldNotCompute();
8029
8030   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8031
8032   // Avoid weird loops
8033   if (!IV || IV->getLoop() != L || !IV->isAffine())
8034     return getCouldNotCompute();
8035
8036   bool NoWrap = ControlsExit &&
8037                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8038
8039   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8040
8041   // Avoid negative or zero stride values
8042   if (!isKnownPositive(Stride))
8043     return getCouldNotCompute();
8044
8045   // Avoid proven overflow cases: this will ensure that the backedge taken count
8046   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8047   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8048   // behaviors like the case of C language.
8049   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8050     return getCouldNotCompute();
8051
8052   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8053                                       : ICmpInst::ICMP_UGT;
8054
8055   const SCEV *Start = IV->getStart();
8056   const SCEV *End = RHS;
8057   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
8058     const SCEV *Diff = getMinusSCEV(RHS, Start);
8059     // If we have NoWrap set, then we can assume that the increment won't
8060     // overflow, in which case if RHS - Start is a constant, we don't need to
8061     // do a max operation since we can just figure it out statically
8062     if (NoWrap && isa<SCEVConstant>(Diff)) {
8063       APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
8064       if (!D.isNegative())
8065         End = Start;
8066     } else
8067       End = IsSigned ? getSMinExpr(RHS, Start)
8068                      : getUMinExpr(RHS, Start);
8069   }
8070
8071   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8072
8073   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8074                             : getUnsignedRange(Start).getUnsignedMax();
8075
8076   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8077                              : getUnsignedRange(Stride).getUnsignedMin();
8078
8079   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8080   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8081                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8082
8083   // Although End can be a MIN expression we estimate MinEnd considering only
8084   // the case End = RHS. This is safe because in the other case (Start - End)
8085   // is zero, leading to a zero maximum backedge taken count.
8086   APInt MinEnd =
8087     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8088              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8089
8090
8091   const SCEV *MaxBECount = getCouldNotCompute();
8092   if (isa<SCEVConstant>(BECount))
8093     MaxBECount = BECount;
8094   else
8095     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8096                                 getConstant(MinStride), false);
8097
8098   if (isa<SCEVCouldNotCompute>(MaxBECount))
8099     MaxBECount = BECount;
8100
8101   return ExitLimit(BECount, MaxBECount);
8102 }
8103
8104 /// getNumIterationsInRange - Return the number of iterations of this loop that
8105 /// produce values in the specified constant range.  Another way of looking at
8106 /// this is that it returns the first iteration number where the value is not in
8107 /// the condition, thus computing the exit count. If the iteration count can't
8108 /// be computed, an instance of SCEVCouldNotCompute is returned.
8109 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
8110                                                     ScalarEvolution &SE) const {
8111   if (Range.isFullSet())  // Infinite loop.
8112     return SE.getCouldNotCompute();
8113
8114   // If the start is a non-zero constant, shift the range to simplify things.
8115   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8116     if (!SC->getValue()->isZero()) {
8117       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8118       Operands[0] = SE.getZero(SC->getType());
8119       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8120                                              getNoWrapFlags(FlagNW));
8121       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8122         return ShiftedAddRec->getNumIterationsInRange(
8123                            Range.subtract(SC->getValue()->getValue()), SE);
8124       // This is strange and shouldn't happen.
8125       return SE.getCouldNotCompute();
8126     }
8127
8128   // The only time we can solve this is when we have all constant indices.
8129   // Otherwise, we cannot determine the overflow conditions.
8130   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
8131     if (!isa<SCEVConstant>(getOperand(i)))
8132       return SE.getCouldNotCompute();
8133
8134
8135   // Okay at this point we know that all elements of the chrec are constants and
8136   // that the start element is zero.
8137
8138   // First check to see if the range contains zero.  If not, the first
8139   // iteration exits.
8140   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8141   if (!Range.contains(APInt(BitWidth, 0)))
8142     return SE.getZero(getType());
8143
8144   if (isAffine()) {
8145     // If this is an affine expression then we have this situation:
8146     //   Solve {0,+,A} in Range  ===  Ax in Range
8147
8148     // We know that zero is in the range.  If A is positive then we know that
8149     // the upper value of the range must be the first possible exit value.
8150     // If A is negative then the lower of the range is the last possible loop
8151     // value.  Also note that we already checked for a full range.
8152     APInt One(BitWidth,1);
8153     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
8154     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8155
8156     // The exit value should be (End+A)/A.
8157     APInt ExitVal = (End + A).udiv(A);
8158     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8159
8160     // Evaluate at the exit value.  If we really did fall out of the valid
8161     // range, then we computed our trip count, otherwise wrap around or other
8162     // things must have happened.
8163     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
8164     if (Range.contains(Val->getValue()))
8165       return SE.getCouldNotCompute();  // Something strange happened
8166
8167     // Ensure that the previous value is in the range.  This is a sanity check.
8168     assert(Range.contains(
8169            EvaluateConstantChrecAtConstant(this,
8170            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
8171            "Linear scev computation is off in a bad way!");
8172     return SE.getConstant(ExitValue);
8173   } else if (isQuadratic()) {
8174     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8175     // quadratic equation to solve it.  To do this, we must frame our problem in
8176     // terms of figuring out when zero is crossed, instead of when
8177     // Range.getUpper() is crossed.
8178     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
8179     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
8180     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8181                                              // getNoWrapFlags(FlagNW)
8182                                              FlagAnyWrap);
8183
8184     // Next, solve the constructed addrec
8185     std::pair<const SCEV *,const SCEV *> Roots =
8186       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
8187     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
8188     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
8189     if (R1) {
8190       // Pick the smallest positive root value.
8191       if (ConstantInt *CB =
8192           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
8193                          R1->getValue(), R2->getValue()))) {
8194         if (!CB->getZExtValue())
8195           std::swap(R1, R2);   // R1 is the minimum root now.
8196
8197         // Make sure the root is not off by one.  The returned iteration should
8198         // not be in the range, but the previous one should be.  When solving
8199         // for "X*X < 5", for example, we should not return a root of 2.
8200         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
8201                                                              R1->getValue(),
8202                                                              SE);
8203         if (Range.contains(R1Val->getValue())) {
8204           // The next iteration must be out of the range...
8205           ConstantInt *NextVal =
8206                 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
8207
8208           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8209           if (!Range.contains(R1Val->getValue()))
8210             return SE.getConstant(NextVal);
8211           return SE.getCouldNotCompute();  // Something strange happened
8212         }
8213
8214         // If R1 was not in the range, then it is a good return value.  Make
8215         // sure that R1-1 WAS in the range though, just in case.
8216         ConstantInt *NextVal =
8217                ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
8218         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8219         if (Range.contains(R1Val->getValue()))
8220           return R1;
8221         return SE.getCouldNotCompute();  // Something strange happened
8222       }
8223     }
8224   }
8225
8226   return SE.getCouldNotCompute();
8227 }
8228
8229 namespace {
8230 struct FindUndefs {
8231   bool Found;
8232   FindUndefs() : Found(false) {}
8233
8234   bool follow(const SCEV *S) {
8235     if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8236       if (isa<UndefValue>(C->getValue()))
8237         Found = true;
8238     } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8239       if (isa<UndefValue>(C->getValue()))
8240         Found = true;
8241     }
8242
8243     // Keep looking if we haven't found it yet.
8244     return !Found;
8245   }
8246   bool isDone() const {
8247     // Stop recursion if we have found an undef.
8248     return Found;
8249   }
8250 };
8251 }
8252
8253 // Return true when S contains at least an undef value.
8254 static inline bool
8255 containsUndefs(const SCEV *S) {
8256   FindUndefs F;
8257   SCEVTraversal<FindUndefs> ST(F);
8258   ST.visitAll(S);
8259
8260   return F.Found;
8261 }
8262
8263 namespace {
8264 // Collect all steps of SCEV expressions.
8265 struct SCEVCollectStrides {
8266   ScalarEvolution &SE;
8267   SmallVectorImpl<const SCEV *> &Strides;
8268
8269   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8270       : SE(SE), Strides(S) {}
8271
8272   bool follow(const SCEV *S) {
8273     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8274       Strides.push_back(AR->getStepRecurrence(SE));
8275     return true;
8276   }
8277   bool isDone() const { return false; }
8278 };
8279
8280 // Collect all SCEVUnknown and SCEVMulExpr expressions.
8281 struct SCEVCollectTerms {
8282   SmallVectorImpl<const SCEV *> &Terms;
8283
8284   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8285       : Terms(T) {}
8286
8287   bool follow(const SCEV *S) {
8288     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
8289       if (!containsUndefs(S))
8290         Terms.push_back(S);
8291
8292       // Stop recursion: once we collected a term, do not walk its operands.
8293       return false;
8294     }
8295
8296     // Keep looking.
8297     return true;
8298   }
8299   bool isDone() const { return false; }
8300 };
8301
8302 // Check if a SCEV contains an AddRecExpr.
8303 struct SCEVHasAddRec {
8304   bool &ContainsAddRec;
8305
8306   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
8307    ContainsAddRec = false;
8308   }
8309
8310   bool follow(const SCEV *S) {
8311     if (isa<SCEVAddRecExpr>(S)) {
8312       ContainsAddRec = true;
8313
8314       // Stop recursion: once we collected a term, do not walk its operands.
8315       return false;
8316     }
8317
8318     // Keep looking.
8319     return true;
8320   }
8321   bool isDone() const { return false; }
8322 };
8323
8324 // Find factors that are multiplied with an expression that (possibly as a
8325 // subexpression) contains an AddRecExpr. In the expression:
8326 //
8327 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
8328 //
8329 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
8330 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
8331 // parameters as they form a product with an induction variable.
8332 //
8333 // This collector expects all array size parameters to be in the same MulExpr.
8334 // It might be necessary to later add support for collecting parameters that are
8335 // spread over different nested MulExpr.
8336 struct SCEVCollectAddRecMultiplies {
8337   SmallVectorImpl<const SCEV *> &Terms;
8338   ScalarEvolution &SE;
8339
8340   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
8341       : Terms(T), SE(SE) {}
8342
8343   bool follow(const SCEV *S) {
8344     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
8345       bool HasAddRec = false;
8346       SmallVector<const SCEV *, 0> Operands;
8347       for (auto Op : Mul->operands()) {
8348         if (isa<SCEVUnknown>(Op)) {
8349           Operands.push_back(Op);
8350         } else {
8351           bool ContainsAddRec;
8352           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
8353           visitAll(Op, ContiansAddRec);
8354           HasAddRec |= ContainsAddRec;
8355         }
8356       }
8357       if (Operands.size() == 0)
8358         return true;
8359
8360       if (!HasAddRec)
8361         return false;
8362
8363       Terms.push_back(SE.getMulExpr(Operands));
8364       // Stop recursion: once we collected a term, do not walk its operands.
8365       return false;
8366     }
8367
8368     // Keep looking.
8369     return true;
8370   }
8371   bool isDone() const { return false; }
8372 };
8373 }
8374
8375 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
8376 /// two places:
8377 ///   1) The strides of AddRec expressions.
8378 ///   2) Unknowns that are multiplied with AddRec expressions.
8379 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
8380     SmallVectorImpl<const SCEV *> &Terms) {
8381   SmallVector<const SCEV *, 4> Strides;
8382   SCEVCollectStrides StrideCollector(*this, Strides);
8383   visitAll(Expr, StrideCollector);
8384
8385   DEBUG({
8386       dbgs() << "Strides:\n";
8387       for (const SCEV *S : Strides)
8388         dbgs() << *S << "\n";
8389     });
8390
8391   for (const SCEV *S : Strides) {
8392     SCEVCollectTerms TermCollector(Terms);
8393     visitAll(S, TermCollector);
8394   }
8395
8396   DEBUG({
8397       dbgs() << "Terms:\n";
8398       for (const SCEV *T : Terms)
8399         dbgs() << *T << "\n";
8400     });
8401
8402   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
8403   visitAll(Expr, MulCollector);
8404 }
8405
8406 static bool findArrayDimensionsRec(ScalarEvolution &SE,
8407                                    SmallVectorImpl<const SCEV *> &Terms,
8408                                    SmallVectorImpl<const SCEV *> &Sizes) {
8409   int Last = Terms.size() - 1;
8410   const SCEV *Step = Terms[Last];
8411
8412   // End of recursion.
8413   if (Last == 0) {
8414     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
8415       SmallVector<const SCEV *, 2> Qs;
8416       for (const SCEV *Op : M->operands())
8417         if (!isa<SCEVConstant>(Op))
8418           Qs.push_back(Op);
8419
8420       Step = SE.getMulExpr(Qs);
8421     }
8422
8423     Sizes.push_back(Step);
8424     return true;
8425   }
8426
8427   for (const SCEV *&Term : Terms) {
8428     // Normalize the terms before the next call to findArrayDimensionsRec.
8429     const SCEV *Q, *R;
8430     SCEVDivision::divide(SE, Term, Step, &Q, &R);
8431
8432     // Bail out when GCD does not evenly divide one of the terms.
8433     if (!R->isZero())
8434       return false;
8435
8436     Term = Q;
8437   }
8438
8439   // Remove all SCEVConstants.
8440   Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
8441                 return isa<SCEVConstant>(E);
8442               }),
8443               Terms.end());
8444
8445   if (Terms.size() > 0)
8446     if (!findArrayDimensionsRec(SE, Terms, Sizes))
8447       return false;
8448
8449   Sizes.push_back(Step);
8450   return true;
8451 }
8452
8453 namespace {
8454 struct FindParameter {
8455   bool FoundParameter;
8456   FindParameter() : FoundParameter(false) {}
8457
8458   bool follow(const SCEV *S) {
8459     if (isa<SCEVUnknown>(S)) {
8460       FoundParameter = true;
8461       // Stop recursion: we found a parameter.
8462       return false;
8463     }
8464     // Keep looking.
8465     return true;
8466   }
8467   bool isDone() const {
8468     // Stop recursion if we have found a parameter.
8469     return FoundParameter;
8470   }
8471 };
8472 }
8473
8474 // Returns true when S contains at least a SCEVUnknown parameter.
8475 static inline bool
8476 containsParameters(const SCEV *S) {
8477   FindParameter F;
8478   SCEVTraversal<FindParameter> ST(F);
8479   ST.visitAll(S);
8480
8481   return F.FoundParameter;
8482 }
8483
8484 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
8485 static inline bool
8486 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
8487   for (const SCEV *T : Terms)
8488     if (containsParameters(T))
8489       return true;
8490   return false;
8491 }
8492
8493 // Return the number of product terms in S.
8494 static inline int numberOfTerms(const SCEV *S) {
8495   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
8496     return Expr->getNumOperands();
8497   return 1;
8498 }
8499
8500 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
8501   if (isa<SCEVConstant>(T))
8502     return nullptr;
8503
8504   if (isa<SCEVUnknown>(T))
8505     return T;
8506
8507   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
8508     SmallVector<const SCEV *, 2> Factors;
8509     for (const SCEV *Op : M->operands())
8510       if (!isa<SCEVConstant>(Op))
8511         Factors.push_back(Op);
8512
8513     return SE.getMulExpr(Factors);
8514   }
8515
8516   return T;
8517 }
8518
8519 /// Return the size of an element read or written by Inst.
8520 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
8521   Type *Ty;
8522   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
8523     Ty = Store->getValueOperand()->getType();
8524   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
8525     Ty = Load->getType();
8526   else
8527     return nullptr;
8528
8529   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
8530   return getSizeOfExpr(ETy, Ty);
8531 }
8532
8533 /// Second step of delinearization: compute the array dimensions Sizes from the
8534 /// set of Terms extracted from the memory access function of this SCEVAddRec.
8535 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
8536                                           SmallVectorImpl<const SCEV *> &Sizes,
8537                                           const SCEV *ElementSize) const {
8538
8539   if (Terms.size() < 1 || !ElementSize)
8540     return;
8541
8542   // Early return when Terms do not contain parameters: we do not delinearize
8543   // non parametric SCEVs.
8544   if (!containsParameters(Terms))
8545     return;
8546
8547   DEBUG({
8548       dbgs() << "Terms:\n";
8549       for (const SCEV *T : Terms)
8550         dbgs() << *T << "\n";
8551     });
8552
8553   // Remove duplicates.
8554   std::sort(Terms.begin(), Terms.end());
8555   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
8556
8557   // Put larger terms first.
8558   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
8559     return numberOfTerms(LHS) > numberOfTerms(RHS);
8560   });
8561
8562   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8563
8564   // Try to divide all terms by the element size. If term is not divisible by
8565   // element size, proceed with the original term.
8566   for (const SCEV *&Term : Terms) {
8567     const SCEV *Q, *R;
8568     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
8569     if (!Q->isZero())
8570       Term = Q;
8571   }
8572
8573   SmallVector<const SCEV *, 4> NewTerms;
8574
8575   // Remove constant factors.
8576   for (const SCEV *T : Terms)
8577     if (const SCEV *NewT = removeConstantFactors(SE, T))
8578       NewTerms.push_back(NewT);
8579
8580   DEBUG({
8581       dbgs() << "Terms after sorting:\n";
8582       for (const SCEV *T : NewTerms)
8583         dbgs() << *T << "\n";
8584     });
8585
8586   if (NewTerms.empty() ||
8587       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
8588     Sizes.clear();
8589     return;
8590   }
8591
8592   // The last element to be pushed into Sizes is the size of an element.
8593   Sizes.push_back(ElementSize);
8594
8595   DEBUG({
8596       dbgs() << "Sizes:\n";
8597       for (const SCEV *S : Sizes)
8598         dbgs() << *S << "\n";
8599     });
8600 }
8601
8602 /// Third step of delinearization: compute the access functions for the
8603 /// Subscripts based on the dimensions in Sizes.
8604 void ScalarEvolution::computeAccessFunctions(
8605     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
8606     SmallVectorImpl<const SCEV *> &Sizes) {
8607
8608   // Early exit in case this SCEV is not an affine multivariate function.
8609   if (Sizes.empty())
8610     return;
8611
8612   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
8613     if (!AR->isAffine())
8614       return;
8615
8616   const SCEV *Res = Expr;
8617   int Last = Sizes.size() - 1;
8618   for (int i = Last; i >= 0; i--) {
8619     const SCEV *Q, *R;
8620     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
8621
8622     DEBUG({
8623         dbgs() << "Res: " << *Res << "\n";
8624         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
8625         dbgs() << "Res divided by Sizes[i]:\n";
8626         dbgs() << "Quotient: " << *Q << "\n";
8627         dbgs() << "Remainder: " << *R << "\n";
8628       });
8629
8630     Res = Q;
8631
8632     // Do not record the last subscript corresponding to the size of elements in
8633     // the array.
8634     if (i == Last) {
8635
8636       // Bail out if the remainder is too complex.
8637       if (isa<SCEVAddRecExpr>(R)) {
8638         Subscripts.clear();
8639         Sizes.clear();
8640         return;
8641       }
8642
8643       continue;
8644     }
8645
8646     // Record the access function for the current subscript.
8647     Subscripts.push_back(R);
8648   }
8649
8650   // Also push in last position the remainder of the last division: it will be
8651   // the access function of the innermost dimension.
8652   Subscripts.push_back(Res);
8653
8654   std::reverse(Subscripts.begin(), Subscripts.end());
8655
8656   DEBUG({
8657       dbgs() << "Subscripts:\n";
8658       for (const SCEV *S : Subscripts)
8659         dbgs() << *S << "\n";
8660     });
8661 }
8662
8663 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
8664 /// sizes of an array access. Returns the remainder of the delinearization that
8665 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
8666 /// the multiples of SCEV coefficients: that is a pattern matching of sub
8667 /// expressions in the stride and base of a SCEV corresponding to the
8668 /// computation of a GCD (greatest common divisor) of base and stride.  When
8669 /// SCEV->delinearize fails, it returns the SCEV unchanged.
8670 ///
8671 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
8672 ///
8673 ///  void foo(long n, long m, long o, double A[n][m][o]) {
8674 ///
8675 ///    for (long i = 0; i < n; i++)
8676 ///      for (long j = 0; j < m; j++)
8677 ///        for (long k = 0; k < o; k++)
8678 ///          A[i][j][k] = 1.0;
8679 ///  }
8680 ///
8681 /// the delinearization input is the following AddRec SCEV:
8682 ///
8683 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
8684 ///
8685 /// From this SCEV, we are able to say that the base offset of the access is %A
8686 /// because it appears as an offset that does not divide any of the strides in
8687 /// the loops:
8688 ///
8689 ///  CHECK: Base offset: %A
8690 ///
8691 /// and then SCEV->delinearize determines the size of some of the dimensions of
8692 /// the array as these are the multiples by which the strides are happening:
8693 ///
8694 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
8695 ///
8696 /// Note that the outermost dimension remains of UnknownSize because there are
8697 /// no strides that would help identifying the size of the last dimension: when
8698 /// the array has been statically allocated, one could compute the size of that
8699 /// dimension by dividing the overall size of the array by the size of the known
8700 /// dimensions: %m * %o * 8.
8701 ///
8702 /// Finally delinearize provides the access functions for the array reference
8703 /// that does correspond to A[i][j][k] of the above C testcase:
8704 ///
8705 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
8706 ///
8707 /// The testcases are checking the output of a function pass:
8708 /// DelinearizationPass that walks through all loads and stores of a function
8709 /// asking for the SCEV of the memory access with respect to all enclosing
8710 /// loops, calling SCEV->delinearize on that and printing the results.
8711
8712 void ScalarEvolution::delinearize(const SCEV *Expr,
8713                                  SmallVectorImpl<const SCEV *> &Subscripts,
8714                                  SmallVectorImpl<const SCEV *> &Sizes,
8715                                  const SCEV *ElementSize) {
8716   // First step: collect parametric terms.
8717   SmallVector<const SCEV *, 4> Terms;
8718   collectParametricTerms(Expr, Terms);
8719
8720   if (Terms.empty())
8721     return;
8722
8723   // Second step: find subscript sizes.
8724   findArrayDimensions(Terms, Sizes, ElementSize);
8725
8726   if (Sizes.empty())
8727     return;
8728
8729   // Third step: compute the access functions for each subscript.
8730   computeAccessFunctions(Expr, Subscripts, Sizes);
8731
8732   if (Subscripts.empty())
8733     return;
8734
8735   DEBUG({
8736       dbgs() << "succeeded to delinearize " << *Expr << "\n";
8737       dbgs() << "ArrayDecl[UnknownSize]";
8738       for (const SCEV *S : Sizes)
8739         dbgs() << "[" << *S << "]";
8740
8741       dbgs() << "\nArrayRef";
8742       for (const SCEV *S : Subscripts)
8743         dbgs() << "[" << *S << "]";
8744       dbgs() << "\n";
8745     });
8746 }
8747
8748 //===----------------------------------------------------------------------===//
8749 //                   SCEVCallbackVH Class Implementation
8750 //===----------------------------------------------------------------------===//
8751
8752 void ScalarEvolution::SCEVCallbackVH::deleted() {
8753   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
8754   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
8755     SE->ConstantEvolutionLoopExitValue.erase(PN);
8756   SE->ValueExprMap.erase(getValPtr());
8757   // this now dangles!
8758 }
8759
8760 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
8761   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
8762
8763   // Forget all the expressions associated with users of the old value,
8764   // so that future queries will recompute the expressions using the new
8765   // value.
8766   Value *Old = getValPtr();
8767   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
8768   SmallPtrSet<User *, 8> Visited;
8769   while (!Worklist.empty()) {
8770     User *U = Worklist.pop_back_val();
8771     // Deleting the Old value will cause this to dangle. Postpone
8772     // that until everything else is done.
8773     if (U == Old)
8774       continue;
8775     if (!Visited.insert(U).second)
8776       continue;
8777     if (PHINode *PN = dyn_cast<PHINode>(U))
8778       SE->ConstantEvolutionLoopExitValue.erase(PN);
8779     SE->ValueExprMap.erase(U);
8780     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
8781   }
8782   // Delete the Old value.
8783   if (PHINode *PN = dyn_cast<PHINode>(Old))
8784     SE->ConstantEvolutionLoopExitValue.erase(PN);
8785   SE->ValueExprMap.erase(Old);
8786   // this now dangles!
8787 }
8788
8789 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
8790   : CallbackVH(V), SE(se) {}
8791
8792 //===----------------------------------------------------------------------===//
8793 //                   ScalarEvolution Class Implementation
8794 //===----------------------------------------------------------------------===//
8795
8796 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
8797                                  AssumptionCache &AC, DominatorTree &DT,
8798                                  LoopInfo &LI)
8799     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
8800       CouldNotCompute(new SCEVCouldNotCompute()),
8801       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
8802       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
8803       FirstUnknown(nullptr) {}
8804
8805 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
8806     : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
8807       CouldNotCompute(std::move(Arg.CouldNotCompute)),
8808       ValueExprMap(std::move(Arg.ValueExprMap)),
8809       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
8810       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
8811       ConstantEvolutionLoopExitValue(
8812           std::move(Arg.ConstantEvolutionLoopExitValue)),
8813       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
8814       LoopDispositions(std::move(Arg.LoopDispositions)),
8815       BlockDispositions(std::move(Arg.BlockDispositions)),
8816       UnsignedRanges(std::move(Arg.UnsignedRanges)),
8817       SignedRanges(std::move(Arg.SignedRanges)),
8818       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
8819       SCEVAllocator(std::move(Arg.SCEVAllocator)),
8820       FirstUnknown(Arg.FirstUnknown) {
8821   Arg.FirstUnknown = nullptr;
8822 }
8823
8824 ScalarEvolution::~ScalarEvolution() {
8825   // Iterate through all the SCEVUnknown instances and call their
8826   // destructors, so that they release their references to their values.
8827   for (SCEVUnknown *U = FirstUnknown; U;) {
8828     SCEVUnknown *Tmp = U;
8829     U = U->Next;
8830     Tmp->~SCEVUnknown();
8831   }
8832   FirstUnknown = nullptr;
8833
8834   ValueExprMap.clear();
8835
8836   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
8837   // that a loop had multiple computable exits.
8838   for (auto &BTCI : BackedgeTakenCounts)
8839     BTCI.second.clear();
8840
8841   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
8842   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
8843   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
8844 }
8845
8846 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
8847   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
8848 }
8849
8850 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
8851                           const Loop *L) {
8852   // Print all inner loops first
8853   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
8854     PrintLoopInfo(OS, SE, *I);
8855
8856   OS << "Loop ";
8857   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
8858   OS << ": ";
8859
8860   SmallVector<BasicBlock *, 8> ExitBlocks;
8861   L->getExitBlocks(ExitBlocks);
8862   if (ExitBlocks.size() != 1)
8863     OS << "<multiple exits> ";
8864
8865   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
8866     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
8867   } else {
8868     OS << "Unpredictable backedge-taken count. ";
8869   }
8870
8871   OS << "\n"
8872         "Loop ";
8873   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
8874   OS << ": ";
8875
8876   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
8877     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
8878   } else {
8879     OS << "Unpredictable max backedge-taken count. ";
8880   }
8881
8882   OS << "\n";
8883 }
8884
8885 void ScalarEvolution::print(raw_ostream &OS) const {
8886   // ScalarEvolution's implementation of the print method is to print
8887   // out SCEV values of all instructions that are interesting. Doing
8888   // this potentially causes it to create new SCEV objects though,
8889   // which technically conflicts with the const qualifier. This isn't
8890   // observable from outside the class though, so casting away the
8891   // const isn't dangerous.
8892   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8893
8894   OS << "Classifying expressions for: ";
8895   F.printAsOperand(OS, /*PrintType=*/false);
8896   OS << "\n";
8897   for (Instruction &I : instructions(F))
8898     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
8899       OS << I << '\n';
8900       OS << "  -->  ";
8901       const SCEV *SV = SE.getSCEV(&I);
8902       SV->print(OS);
8903       if (!isa<SCEVCouldNotCompute>(SV)) {
8904         OS << " U: ";
8905         SE.getUnsignedRange(SV).print(OS);
8906         OS << " S: ";
8907         SE.getSignedRange(SV).print(OS);
8908       }
8909
8910       const Loop *L = LI.getLoopFor(I.getParent());
8911
8912       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
8913       if (AtUse != SV) {
8914         OS << "  -->  ";
8915         AtUse->print(OS);
8916         if (!isa<SCEVCouldNotCompute>(AtUse)) {
8917           OS << " U: ";
8918           SE.getUnsignedRange(AtUse).print(OS);
8919           OS << " S: ";
8920           SE.getSignedRange(AtUse).print(OS);
8921         }
8922       }
8923
8924       if (L) {
8925         OS << "\t\t" "Exits: ";
8926         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
8927         if (!SE.isLoopInvariant(ExitValue, L)) {
8928           OS << "<<Unknown>>";
8929         } else {
8930           OS << *ExitValue;
8931         }
8932       }
8933
8934       OS << "\n";
8935     }
8936
8937   OS << "Determining loop execution counts for: ";
8938   F.printAsOperand(OS, /*PrintType=*/false);
8939   OS << "\n";
8940   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
8941     PrintLoopInfo(OS, &SE, *I);
8942 }
8943
8944 ScalarEvolution::LoopDisposition
8945 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
8946   auto &Values = LoopDispositions[S];
8947   for (auto &V : Values) {
8948     if (V.getPointer() == L)
8949       return V.getInt();
8950   }
8951   Values.emplace_back(L, LoopVariant);
8952   LoopDisposition D = computeLoopDisposition(S, L);
8953   auto &Values2 = LoopDispositions[S];
8954   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
8955     if (V.getPointer() == L) {
8956       V.setInt(D);
8957       break;
8958     }
8959   }
8960   return D;
8961 }
8962
8963 ScalarEvolution::LoopDisposition
8964 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
8965   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
8966   case scConstant:
8967     return LoopInvariant;
8968   case scTruncate:
8969   case scZeroExtend:
8970   case scSignExtend:
8971     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
8972   case scAddRecExpr: {
8973     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8974
8975     // If L is the addrec's loop, it's computable.
8976     if (AR->getLoop() == L)
8977       return LoopComputable;
8978
8979     // Add recurrences are never invariant in the function-body (null loop).
8980     if (!L)
8981       return LoopVariant;
8982
8983     // This recurrence is variant w.r.t. L if L contains AR's loop.
8984     if (L->contains(AR->getLoop()))
8985       return LoopVariant;
8986
8987     // This recurrence is invariant w.r.t. L if AR's loop contains L.
8988     if (AR->getLoop()->contains(L))
8989       return LoopInvariant;
8990
8991     // This recurrence is variant w.r.t. L if any of its operands
8992     // are variant.
8993     for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
8994          I != E; ++I)
8995       if (!isLoopInvariant(*I, L))
8996         return LoopVariant;
8997
8998     // Otherwise it's loop-invariant.
8999     return LoopInvariant;
9000   }
9001   case scAddExpr:
9002   case scMulExpr:
9003   case scUMaxExpr:
9004   case scSMaxExpr: {
9005     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9006     bool HasVarying = false;
9007     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
9008          I != E; ++I) {
9009       LoopDisposition D = getLoopDisposition(*I, L);
9010       if (D == LoopVariant)
9011         return LoopVariant;
9012       if (D == LoopComputable)
9013         HasVarying = true;
9014     }
9015     return HasVarying ? LoopComputable : LoopInvariant;
9016   }
9017   case scUDivExpr: {
9018     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9019     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9020     if (LD == LoopVariant)
9021       return LoopVariant;
9022     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9023     if (RD == LoopVariant)
9024       return LoopVariant;
9025     return (LD == LoopInvariant && RD == LoopInvariant) ?
9026            LoopInvariant : LoopComputable;
9027   }
9028   case scUnknown:
9029     // All non-instruction values are loop invariant.  All instructions are loop
9030     // invariant if they are not contained in the specified loop.
9031     // Instructions are never considered invariant in the function body
9032     // (null loop) because they are defined within the "loop".
9033     if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9034       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9035     return LoopInvariant;
9036   case scCouldNotCompute:
9037     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9038   }
9039   llvm_unreachable("Unknown SCEV kind!");
9040 }
9041
9042 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9043   return getLoopDisposition(S, L) == LoopInvariant;
9044 }
9045
9046 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9047   return getLoopDisposition(S, L) == LoopComputable;
9048 }
9049
9050 ScalarEvolution::BlockDisposition
9051 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9052   auto &Values = BlockDispositions[S];
9053   for (auto &V : Values) {
9054     if (V.getPointer() == BB)
9055       return V.getInt();
9056   }
9057   Values.emplace_back(BB, DoesNotDominateBlock);
9058   BlockDisposition D = computeBlockDisposition(S, BB);
9059   auto &Values2 = BlockDispositions[S];
9060   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9061     if (V.getPointer() == BB) {
9062       V.setInt(D);
9063       break;
9064     }
9065   }
9066   return D;
9067 }
9068
9069 ScalarEvolution::BlockDisposition
9070 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9071   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9072   case scConstant:
9073     return ProperlyDominatesBlock;
9074   case scTruncate:
9075   case scZeroExtend:
9076   case scSignExtend:
9077     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9078   case scAddRecExpr: {
9079     // This uses a "dominates" query instead of "properly dominates" query
9080     // to test for proper dominance too, because the instruction which
9081     // produces the addrec's value is a PHI, and a PHI effectively properly
9082     // dominates its entire containing block.
9083     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9084     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9085       return DoesNotDominateBlock;
9086   }
9087   // FALL THROUGH into SCEVNAryExpr handling.
9088   case scAddExpr:
9089   case scMulExpr:
9090   case scUMaxExpr:
9091   case scSMaxExpr: {
9092     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9093     bool Proper = true;
9094     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
9095          I != E; ++I) {
9096       BlockDisposition D = getBlockDisposition(*I, BB);
9097       if (D == DoesNotDominateBlock)
9098         return DoesNotDominateBlock;
9099       if (D == DominatesBlock)
9100         Proper = false;
9101     }
9102     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9103   }
9104   case scUDivExpr: {
9105     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9106     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9107     BlockDisposition LD = getBlockDisposition(LHS, BB);
9108     if (LD == DoesNotDominateBlock)
9109       return DoesNotDominateBlock;
9110     BlockDisposition RD = getBlockDisposition(RHS, BB);
9111     if (RD == DoesNotDominateBlock)
9112       return DoesNotDominateBlock;
9113     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9114       ProperlyDominatesBlock : DominatesBlock;
9115   }
9116   case scUnknown:
9117     if (Instruction *I =
9118           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9119       if (I->getParent() == BB)
9120         return DominatesBlock;
9121       if (DT.properlyDominates(I->getParent(), BB))
9122         return ProperlyDominatesBlock;
9123       return DoesNotDominateBlock;
9124     }
9125     return ProperlyDominatesBlock;
9126   case scCouldNotCompute:
9127     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9128   }
9129   llvm_unreachable("Unknown SCEV kind!");
9130 }
9131
9132 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9133   return getBlockDisposition(S, BB) >= DominatesBlock;
9134 }
9135
9136 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9137   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9138 }
9139
9140 namespace {
9141 // Search for a SCEV expression node within an expression tree.
9142 // Implements SCEVTraversal::Visitor.
9143 struct SCEVSearch {
9144   const SCEV *Node;
9145   bool IsFound;
9146
9147   SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9148
9149   bool follow(const SCEV *S) {
9150     IsFound |= (S == Node);
9151     return !IsFound;
9152   }
9153   bool isDone() const { return IsFound; }
9154 };
9155 }
9156
9157 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
9158   SCEVSearch Search(Op);
9159   visitAll(S, Search);
9160   return Search.IsFound;
9161 }
9162
9163 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9164   ValuesAtScopes.erase(S);
9165   LoopDispositions.erase(S);
9166   BlockDispositions.erase(S);
9167   UnsignedRanges.erase(S);
9168   SignedRanges.erase(S);
9169
9170   for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
9171          BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
9172     BackedgeTakenInfo &BEInfo = I->second;
9173     if (BEInfo.hasOperand(S, this)) {
9174       BEInfo.clear();
9175       BackedgeTakenCounts.erase(I++);
9176     }
9177     else
9178       ++I;
9179   }
9180 }
9181
9182 typedef DenseMap<const Loop *, std::string> VerifyMap;
9183
9184 /// replaceSubString - Replaces all occurrences of From in Str with To.
9185 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9186   size_t Pos = 0;
9187   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9188     Str.replace(Pos, From.size(), To.data(), To.size());
9189     Pos += To.size();
9190   }
9191 }
9192
9193 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9194 static void
9195 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9196   for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
9197     getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
9198
9199     std::string &S = Map[L];
9200     if (S.empty()) {
9201       raw_string_ostream OS(S);
9202       SE.getBackedgeTakenCount(L)->print(OS);
9203
9204       // false and 0 are semantically equivalent. This can happen in dead loops.
9205       replaceSubString(OS.str(), "false", "0");
9206       // Remove wrap flags, their use in SCEV is highly fragile.
9207       // FIXME: Remove this when SCEV gets smarter about them.
9208       replaceSubString(OS.str(), "<nw>", "");
9209       replaceSubString(OS.str(), "<nsw>", "");
9210       replaceSubString(OS.str(), "<nuw>", "");
9211     }
9212   }
9213 }
9214
9215 void ScalarEvolution::verify() const {
9216   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9217
9218   // Gather stringified backedge taken counts for all loops using SCEV's caches.
9219   // FIXME: It would be much better to store actual values instead of strings,
9220   //        but SCEV pointers will change if we drop the caches.
9221   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
9222   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9223     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9224
9225   // Gather stringified backedge taken counts for all loops using a fresh
9226   // ScalarEvolution object.
9227   ScalarEvolution SE2(F, TLI, AC, DT, LI);
9228   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9229     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
9230
9231   // Now compare whether they're the same with and without caches. This allows
9232   // verifying that no pass changed the cache.
9233   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9234          "New loops suddenly appeared!");
9235
9236   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9237                            OldE = BackedgeDumpsOld.end(),
9238                            NewI = BackedgeDumpsNew.begin();
9239        OldI != OldE; ++OldI, ++NewI) {
9240     assert(OldI->first == NewI->first && "Loop order changed!");
9241
9242     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9243     // changes.
9244     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
9245     // means that a pass is buggy or SCEV has to learn a new pattern but is
9246     // usually not harmful.
9247     if (OldI->second != NewI->second &&
9248         OldI->second.find("undef") == std::string::npos &&
9249         NewI->second.find("undef") == std::string::npos &&
9250         OldI->second != "***COULDNOTCOMPUTE***" &&
9251         NewI->second != "***COULDNOTCOMPUTE***") {
9252       dbgs() << "SCEVValidator: SCEV for loop '"
9253              << OldI->first->getHeader()->getName()
9254              << "' changed from '" << OldI->second
9255              << "' to '" << NewI->second << "'!\n";
9256       std::abort();
9257     }
9258   }
9259
9260   // TODO: Verify more things.
9261 }
9262
9263 char ScalarEvolutionAnalysis::PassID;
9264
9265 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
9266                                              AnalysisManager<Function> *AM) {
9267   return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F),
9268                          AM->getResult<AssumptionAnalysis>(F),
9269                          AM->getResult<DominatorTreeAnalysis>(F),
9270                          AM->getResult<LoopAnalysis>(F));
9271 }
9272
9273 PreservedAnalyses
9274 ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) {
9275   AM->getResult<ScalarEvolutionAnalysis>(F).print(OS);
9276   return PreservedAnalyses::all();
9277 }
9278
9279 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
9280                       "Scalar Evolution Analysis", false, true)
9281 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9282 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
9283 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
9284 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
9285 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
9286                     "Scalar Evolution Analysis", false, true)
9287 char ScalarEvolutionWrapperPass::ID = 0;
9288
9289 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
9290   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
9291 }
9292
9293 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
9294   SE.reset(new ScalarEvolution(
9295       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
9296       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
9297       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
9298       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
9299   return false;
9300 }
9301
9302 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
9303
9304 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
9305   SE->print(OS);
9306 }
9307
9308 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
9309   if (!VerifySCEV)
9310     return;
9311
9312   SE->verify();
9313 }
9314
9315 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
9316   AU.setPreservesAll();
9317   AU.addRequiredTransitive<AssumptionCacheTracker>();
9318   AU.addRequiredTransitive<LoopInfoWrapperPass>();
9319   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
9320   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
9321 }