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