xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision f230b0aa43f9af0da9f5970dac2f41bc7e6e254b)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/ScopeExit.h"
65 #include "llvm/ADT/SmallPtrSet.h"
66 #include "llvm/ADT/Statistic.h"
67 #include "llvm/Analysis/AssumptionCache.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/InstructionSimplify.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
72 #include "llvm/Analysis/TargetLibraryInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Dominators.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/GlobalAlias.h"
81 #include "llvm/IR/GlobalVariable.h"
82 #include "llvm/IR/InstIterator.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/LLVMContext.h"
85 #include "llvm/IR/Metadata.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Debug.h"
90 #include "llvm/Support/ErrorHandling.h"
91 #include "llvm/Support/MathExtras.h"
92 #include "llvm/Support/raw_ostream.h"
93 #include "llvm/Support/SaveAndRestore.h"
94 #include <algorithm>
95 using namespace llvm;
96 
97 #define DEBUG_TYPE "scalar-evolution"
98 
99 STATISTIC(NumArrayLenItCounts,
100           "Number of trip counts computed with array length");
101 STATISTIC(NumTripCountsComputed,
102           "Number of loops with predictable loop counts");
103 STATISTIC(NumTripCountsNotComputed,
104           "Number of loops without predictable loop counts");
105 STATISTIC(NumBruteForceTripCountsComputed,
106           "Number of loops with trip counts computed by force");
107 
108 static cl::opt<unsigned>
109 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
110                         cl::desc("Maximum number of iterations SCEV will "
111                                  "symbolically execute a constant "
112                                  "derived loop"),
113                         cl::init(100));
114 
115 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
116 static cl::opt<bool>
117 VerifySCEV("verify-scev",
118            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
119 static cl::opt<bool>
120     VerifySCEVMap("verify-scev-maps",
121                   cl::desc("Verify no dangling value in ScalarEvolution's "
122                            "ExprValueMap (slow)"));
123 
124 //===----------------------------------------------------------------------===//
125 //                           SCEV class definitions
126 //===----------------------------------------------------------------------===//
127 
128 //===----------------------------------------------------------------------===//
129 // Implementation of the SCEV class.
130 //
131 
132 LLVM_DUMP_METHOD
133 void SCEV::dump() const {
134   print(dbgs());
135   dbgs() << '\n';
136 }
137 
138 void SCEV::print(raw_ostream &OS) const {
139   switch (static_cast<SCEVTypes>(getSCEVType())) {
140   case scConstant:
141     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
142     return;
143   case scTruncate: {
144     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
145     const SCEV *Op = Trunc->getOperand();
146     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
147        << *Trunc->getType() << ")";
148     return;
149   }
150   case scZeroExtend: {
151     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
152     const SCEV *Op = ZExt->getOperand();
153     OS << "(zext " << *Op->getType() << " " << *Op << " to "
154        << *ZExt->getType() << ")";
155     return;
156   }
157   case scSignExtend: {
158     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
159     const SCEV *Op = SExt->getOperand();
160     OS << "(sext " << *Op->getType() << " " << *Op << " to "
161        << *SExt->getType() << ")";
162     return;
163   }
164   case scAddRecExpr: {
165     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
166     OS << "{" << *AR->getOperand(0);
167     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
168       OS << ",+," << *AR->getOperand(i);
169     OS << "}<";
170     if (AR->hasNoUnsignedWrap())
171       OS << "nuw><";
172     if (AR->hasNoSignedWrap())
173       OS << "nsw><";
174     if (AR->hasNoSelfWrap() &&
175         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
176       OS << "nw><";
177     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
178     OS << ">";
179     return;
180   }
181   case scAddExpr:
182   case scMulExpr:
183   case scUMaxExpr:
184   case scSMaxExpr: {
185     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
186     const char *OpStr = nullptr;
187     switch (NAry->getSCEVType()) {
188     case scAddExpr: OpStr = " + "; break;
189     case scMulExpr: OpStr = " * "; break;
190     case scUMaxExpr: OpStr = " umax "; break;
191     case scSMaxExpr: OpStr = " smax "; break;
192     }
193     OS << "(";
194     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
195          I != E; ++I) {
196       OS << **I;
197       if (std::next(I) != E)
198         OS << OpStr;
199     }
200     OS << ")";
201     switch (NAry->getSCEVType()) {
202     case scAddExpr:
203     case scMulExpr:
204       if (NAry->hasNoUnsignedWrap())
205         OS << "<nuw>";
206       if (NAry->hasNoSignedWrap())
207         OS << "<nsw>";
208     }
209     return;
210   }
211   case scUDivExpr: {
212     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
213     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
214     return;
215   }
216   case scUnknown: {
217     const SCEVUnknown *U = cast<SCEVUnknown>(this);
218     Type *AllocTy;
219     if (U->isSizeOf(AllocTy)) {
220       OS << "sizeof(" << *AllocTy << ")";
221       return;
222     }
223     if (U->isAlignOf(AllocTy)) {
224       OS << "alignof(" << *AllocTy << ")";
225       return;
226     }
227 
228     Type *CTy;
229     Constant *FieldNo;
230     if (U->isOffsetOf(CTy, FieldNo)) {
231       OS << "offsetof(" << *CTy << ", ";
232       FieldNo->printAsOperand(OS, false);
233       OS << ")";
234       return;
235     }
236 
237     // Otherwise just print it normally.
238     U->getValue()->printAsOperand(OS, false);
239     return;
240   }
241   case scCouldNotCompute:
242     OS << "***COULDNOTCOMPUTE***";
243     return;
244   }
245   llvm_unreachable("Unknown SCEV kind!");
246 }
247 
248 Type *SCEV::getType() const {
249   switch (static_cast<SCEVTypes>(getSCEVType())) {
250   case scConstant:
251     return cast<SCEVConstant>(this)->getType();
252   case scTruncate:
253   case scZeroExtend:
254   case scSignExtend:
255     return cast<SCEVCastExpr>(this)->getType();
256   case scAddRecExpr:
257   case scMulExpr:
258   case scUMaxExpr:
259   case scSMaxExpr:
260     return cast<SCEVNAryExpr>(this)->getType();
261   case scAddExpr:
262     return cast<SCEVAddExpr>(this)->getType();
263   case scUDivExpr:
264     return cast<SCEVUDivExpr>(this)->getType();
265   case scUnknown:
266     return cast<SCEVUnknown>(this)->getType();
267   case scCouldNotCompute:
268     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
269   }
270   llvm_unreachable("Unknown SCEV kind!");
271 }
272 
273 bool SCEV::isZero() const {
274   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
275     return SC->getValue()->isZero();
276   return false;
277 }
278 
279 bool SCEV::isOne() const {
280   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
281     return SC->getValue()->isOne();
282   return false;
283 }
284 
285 bool SCEV::isAllOnesValue() const {
286   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
287     return SC->getValue()->isAllOnesValue();
288   return false;
289 }
290 
291 bool SCEV::isNonConstantNegative() const {
292   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
293   if (!Mul) return false;
294 
295   // If there is a constant factor, it will be first.
296   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
297   if (!SC) return false;
298 
299   // Return true if the value is negative, this matches things like (-42 * V).
300   return SC->getAPInt().isNegative();
301 }
302 
303 SCEVCouldNotCompute::SCEVCouldNotCompute() :
304   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
305 
306 bool SCEVCouldNotCompute::classof(const SCEV *S) {
307   return S->getSCEVType() == scCouldNotCompute;
308 }
309 
310 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
311   FoldingSetNodeID ID;
312   ID.AddInteger(scConstant);
313   ID.AddPointer(V);
314   void *IP = nullptr;
315   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
316   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
317   UniqueSCEVs.InsertNode(S, IP);
318   return S;
319 }
320 
321 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
322   return getConstant(ConstantInt::get(getContext(), Val));
323 }
324 
325 const SCEV *
326 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
327   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
328   return getConstant(ConstantInt::get(ITy, V, isSigned));
329 }
330 
331 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
332                            unsigned SCEVTy, const SCEV *op, Type *ty)
333   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
334 
335 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
336                                    const SCEV *op, Type *ty)
337   : SCEVCastExpr(ID, scTruncate, op, ty) {
338   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
339          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
340          "Cannot truncate non-integer value!");
341 }
342 
343 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
344                                        const SCEV *op, Type *ty)
345   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
346   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
347          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
348          "Cannot zero extend non-integer value!");
349 }
350 
351 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
352                                        const SCEV *op, Type *ty)
353   : SCEVCastExpr(ID, scSignExtend, op, ty) {
354   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
355          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
356          "Cannot sign extend non-integer value!");
357 }
358 
359 void SCEVUnknown::deleted() {
360   // Clear this SCEVUnknown from various maps.
361   SE->forgetMemoizedResults(this);
362 
363   // Remove this SCEVUnknown from the uniquing map.
364   SE->UniqueSCEVs.RemoveNode(this);
365 
366   // Release the value.
367   setValPtr(nullptr);
368 }
369 
370 void SCEVUnknown::allUsesReplacedWith(Value *New) {
371   // Clear this SCEVUnknown from various maps.
372   SE->forgetMemoizedResults(this);
373 
374   // Remove this SCEVUnknown from the uniquing map.
375   SE->UniqueSCEVs.RemoveNode(this);
376 
377   // Update this SCEVUnknown to point to the new value. This is needed
378   // because there may still be outstanding SCEVs which still point to
379   // this SCEVUnknown.
380   setValPtr(New);
381 }
382 
383 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
384   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
385     if (VCE->getOpcode() == Instruction::PtrToInt)
386       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
387         if (CE->getOpcode() == Instruction::GetElementPtr &&
388             CE->getOperand(0)->isNullValue() &&
389             CE->getNumOperands() == 2)
390           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
391             if (CI->isOne()) {
392               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
393                                  ->getElementType();
394               return true;
395             }
396 
397   return false;
398 }
399 
400 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
401   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
402     if (VCE->getOpcode() == Instruction::PtrToInt)
403       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
404         if (CE->getOpcode() == Instruction::GetElementPtr &&
405             CE->getOperand(0)->isNullValue()) {
406           Type *Ty =
407             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
408           if (StructType *STy = dyn_cast<StructType>(Ty))
409             if (!STy->isPacked() &&
410                 CE->getNumOperands() == 3 &&
411                 CE->getOperand(1)->isNullValue()) {
412               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
413                 if (CI->isOne() &&
414                     STy->getNumElements() == 2 &&
415                     STy->getElementType(0)->isIntegerTy(1)) {
416                   AllocTy = STy->getElementType(1);
417                   return true;
418                 }
419             }
420         }
421 
422   return false;
423 }
424 
425 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
426   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
427     if (VCE->getOpcode() == Instruction::PtrToInt)
428       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
429         if (CE->getOpcode() == Instruction::GetElementPtr &&
430             CE->getNumOperands() == 3 &&
431             CE->getOperand(0)->isNullValue() &&
432             CE->getOperand(1)->isNullValue()) {
433           Type *Ty =
434             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
435           // Ignore vector types here so that ScalarEvolutionExpander doesn't
436           // emit getelementptrs that index into vectors.
437           if (Ty->isStructTy() || Ty->isArrayTy()) {
438             CTy = Ty;
439             FieldNo = CE->getOperand(2);
440             return true;
441           }
442         }
443 
444   return false;
445 }
446 
447 //===----------------------------------------------------------------------===//
448 //                               SCEV Utilities
449 //===----------------------------------------------------------------------===//
450 
451 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
452 // than RHS, respectively. A three-way result allows recursive comparisons to be
453 // more efficient.
454 static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
455                                  const SCEV *RHS) {
456   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
457   if (LHS == RHS)
458     return 0;
459 
460   // Primarily, sort the SCEVs by their getSCEVType().
461   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
462   if (LType != RType)
463     return (int)LType - (int)RType;
464 
465   // Aside from the getSCEVType() ordering, the particular ordering
466   // isn't very important except that it's beneficial to be consistent,
467   // so that (a + b) and (b + a) don't end up as different expressions.
468   switch (static_cast<SCEVTypes>(LType)) {
469   case scUnknown: {
470     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
471     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
472 
473     // Sort SCEVUnknown values with some loose heuristics. TODO: This is
474     // not as complete as it could be.
475     const Value *LV = LU->getValue(), *RV = RU->getValue();
476 
477     // Order pointer values after integer values. This helps SCEVExpander
478     // form GEPs.
479     bool LIsPointer = LV->getType()->isPointerTy(),
480          RIsPointer = RV->getType()->isPointerTy();
481     if (LIsPointer != RIsPointer)
482       return (int)LIsPointer - (int)RIsPointer;
483 
484     // Compare getValueID values.
485     unsigned LID = LV->getValueID(), RID = RV->getValueID();
486     if (LID != RID)
487       return (int)LID - (int)RID;
488 
489     // Sort arguments by their position.
490     if (const Argument *LA = dyn_cast<Argument>(LV)) {
491       const Argument *RA = cast<Argument>(RV);
492       unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
493       return (int)LArgNo - (int)RArgNo;
494     }
495 
496     // For instructions, compare their loop depth, and their operand
497     // count.  This is pretty loose.
498     if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
499       const Instruction *RInst = cast<Instruction>(RV);
500 
501       // Compare loop depths.
502       const BasicBlock *LParent = LInst->getParent(),
503                        *RParent = RInst->getParent();
504       if (LParent != RParent) {
505         unsigned LDepth = LI->getLoopDepth(LParent),
506                  RDepth = LI->getLoopDepth(RParent);
507         if (LDepth != RDepth)
508           return (int)LDepth - (int)RDepth;
509       }
510 
511       // Compare the number of operands.
512       unsigned LNumOps = LInst->getNumOperands(),
513                RNumOps = RInst->getNumOperands();
514       return (int)LNumOps - (int)RNumOps;
515     }
516 
517     return 0;
518   }
519 
520   case scConstant: {
521     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
522     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
523 
524     // Compare constant values.
525     const APInt &LA = LC->getAPInt();
526     const APInt &RA = RC->getAPInt();
527     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
528     if (LBitWidth != RBitWidth)
529       return (int)LBitWidth - (int)RBitWidth;
530     return LA.ult(RA) ? -1 : 1;
531   }
532 
533   case scAddRecExpr: {
534     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
535     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
536 
537     // Compare addrec loop depths.
538     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
539     if (LLoop != RLoop) {
540       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
541       if (LDepth != RDepth)
542         return (int)LDepth - (int)RDepth;
543     }
544 
545     // Addrec complexity grows with operand count.
546     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
547     if (LNumOps != RNumOps)
548       return (int)LNumOps - (int)RNumOps;
549 
550     // Lexicographically compare.
551     for (unsigned i = 0; i != LNumOps; ++i) {
552       long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i));
553       if (X != 0)
554         return X;
555     }
556 
557     return 0;
558   }
559 
560   case scAddExpr:
561   case scMulExpr:
562   case scSMaxExpr:
563   case scUMaxExpr: {
564     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
565     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
566 
567     // Lexicographically compare n-ary expressions.
568     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
569     if (LNumOps != RNumOps)
570       return (int)LNumOps - (int)RNumOps;
571 
572     for (unsigned i = 0; i != LNumOps; ++i) {
573       if (i >= RNumOps)
574         return 1;
575       long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i));
576       if (X != 0)
577         return X;
578     }
579     return (int)LNumOps - (int)RNumOps;
580   }
581 
582   case scUDivExpr: {
583     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
584     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
585 
586     // Lexicographically compare udiv expressions.
587     long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS());
588     if (X != 0)
589       return X;
590     return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS());
591   }
592 
593   case scTruncate:
594   case scZeroExtend:
595   case scSignExtend: {
596     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
597     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
598 
599     // Compare cast expressions by operand.
600     return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand());
601   }
602 
603   case scCouldNotCompute:
604     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
605   }
606   llvm_unreachable("Unknown SCEV kind!");
607 }
608 
609 /// Given a list of SCEV objects, order them by their complexity, and group
610 /// objects of the same complexity together by value.  When this routine is
611 /// finished, we know that any duplicates in the vector are consecutive and that
612 /// complexity is monotonically increasing.
613 ///
614 /// Note that we go take special precautions to ensure that we get deterministic
615 /// results from this routine.  In other words, we don't want the results of
616 /// this to depend on where the addresses of various SCEV objects happened to
617 /// land in memory.
618 ///
619 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
620                               LoopInfo *LI) {
621   if (Ops.size() < 2) return;  // Noop
622   if (Ops.size() == 2) {
623     // This is the common case, which also happens to be trivially simple.
624     // Special case it.
625     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
626     if (CompareSCEVComplexity(LI, RHS, LHS) < 0)
627       std::swap(LHS, RHS);
628     return;
629   }
630 
631   // Do the rough sort by complexity.
632   std::stable_sort(Ops.begin(), Ops.end(),
633                    [LI](const SCEV *LHS, const SCEV *RHS) {
634                      return CompareSCEVComplexity(LI, LHS, RHS) < 0;
635                    });
636 
637   // Now that we are sorted by complexity, group elements of the same
638   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
639   // be extremely short in practice.  Note that we take this approach because we
640   // do not want to depend on the addresses of the objects we are grouping.
641   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
642     const SCEV *S = Ops[i];
643     unsigned Complexity = S->getSCEVType();
644 
645     // If there are any objects of the same complexity and same value as this
646     // one, group them.
647     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
648       if (Ops[j] == S) { // Found a duplicate.
649         // Move it to immediately after i'th element.
650         std::swap(Ops[i+1], Ops[j]);
651         ++i;   // no need to rescan it.
652         if (i == e-2) return;  // Done!
653       }
654     }
655   }
656 }
657 
658 // Returns the size of the SCEV S.
659 static inline int sizeOfSCEV(const SCEV *S) {
660   struct FindSCEVSize {
661     int Size;
662     FindSCEVSize() : Size(0) {}
663 
664     bool follow(const SCEV *S) {
665       ++Size;
666       // Keep looking at all operands of S.
667       return true;
668     }
669     bool isDone() const {
670       return false;
671     }
672   };
673 
674   FindSCEVSize F;
675   SCEVTraversal<FindSCEVSize> ST(F);
676   ST.visitAll(S);
677   return F.Size;
678 }
679 
680 namespace {
681 
682 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
683 public:
684   // Computes the Quotient and Remainder of the division of Numerator by
685   // Denominator.
686   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
687                      const SCEV *Denominator, const SCEV **Quotient,
688                      const SCEV **Remainder) {
689     assert(Numerator && Denominator && "Uninitialized SCEV");
690 
691     SCEVDivision D(SE, Numerator, Denominator);
692 
693     // Check for the trivial case here to avoid having to check for it in the
694     // rest of the code.
695     if (Numerator == Denominator) {
696       *Quotient = D.One;
697       *Remainder = D.Zero;
698       return;
699     }
700 
701     if (Numerator->isZero()) {
702       *Quotient = D.Zero;
703       *Remainder = D.Zero;
704       return;
705     }
706 
707     // A simple case when N/1. The quotient is N.
708     if (Denominator->isOne()) {
709       *Quotient = Numerator;
710       *Remainder = D.Zero;
711       return;
712     }
713 
714     // Split the Denominator when it is a product.
715     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
716       const SCEV *Q, *R;
717       *Quotient = Numerator;
718       for (const SCEV *Op : T->operands()) {
719         divide(SE, *Quotient, Op, &Q, &R);
720         *Quotient = Q;
721 
722         // Bail out when the Numerator is not divisible by one of the terms of
723         // the Denominator.
724         if (!R->isZero()) {
725           *Quotient = D.Zero;
726           *Remainder = Numerator;
727           return;
728         }
729       }
730       *Remainder = D.Zero;
731       return;
732     }
733 
734     D.visit(Numerator);
735     *Quotient = D.Quotient;
736     *Remainder = D.Remainder;
737   }
738 
739   // Except in the trivial case described above, we do not know how to divide
740   // Expr by Denominator for the following functions with empty implementation.
741   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
742   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
743   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
744   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
745   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
746   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
747   void visitUnknown(const SCEVUnknown *Numerator) {}
748   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
749 
750   void visitConstant(const SCEVConstant *Numerator) {
751     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
752       APInt NumeratorVal = Numerator->getAPInt();
753       APInt DenominatorVal = D->getAPInt();
754       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
755       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
756 
757       if (NumeratorBW > DenominatorBW)
758         DenominatorVal = DenominatorVal.sext(NumeratorBW);
759       else if (NumeratorBW < DenominatorBW)
760         NumeratorVal = NumeratorVal.sext(DenominatorBW);
761 
762       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
763       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
764       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
765       Quotient = SE.getConstant(QuotientVal);
766       Remainder = SE.getConstant(RemainderVal);
767       return;
768     }
769   }
770 
771   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
772     const SCEV *StartQ, *StartR, *StepQ, *StepR;
773     if (!Numerator->isAffine())
774       return cannotDivide(Numerator);
775     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
776     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
777     // Bail out if the types do not match.
778     Type *Ty = Denominator->getType();
779     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
780         Ty != StepQ->getType() || Ty != StepR->getType())
781       return cannotDivide(Numerator);
782     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
783                                 Numerator->getNoWrapFlags());
784     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
785                                  Numerator->getNoWrapFlags());
786   }
787 
788   void visitAddExpr(const SCEVAddExpr *Numerator) {
789     SmallVector<const SCEV *, 2> Qs, Rs;
790     Type *Ty = Denominator->getType();
791 
792     for (const SCEV *Op : Numerator->operands()) {
793       const SCEV *Q, *R;
794       divide(SE, Op, Denominator, &Q, &R);
795 
796       // Bail out if types do not match.
797       if (Ty != Q->getType() || Ty != R->getType())
798         return cannotDivide(Numerator);
799 
800       Qs.push_back(Q);
801       Rs.push_back(R);
802     }
803 
804     if (Qs.size() == 1) {
805       Quotient = Qs[0];
806       Remainder = Rs[0];
807       return;
808     }
809 
810     Quotient = SE.getAddExpr(Qs);
811     Remainder = SE.getAddExpr(Rs);
812   }
813 
814   void visitMulExpr(const SCEVMulExpr *Numerator) {
815     SmallVector<const SCEV *, 2> Qs;
816     Type *Ty = Denominator->getType();
817 
818     bool FoundDenominatorTerm = false;
819     for (const SCEV *Op : Numerator->operands()) {
820       // Bail out if types do not match.
821       if (Ty != Op->getType())
822         return cannotDivide(Numerator);
823 
824       if (FoundDenominatorTerm) {
825         Qs.push_back(Op);
826         continue;
827       }
828 
829       // Check whether Denominator divides one of the product operands.
830       const SCEV *Q, *R;
831       divide(SE, Op, Denominator, &Q, &R);
832       if (!R->isZero()) {
833         Qs.push_back(Op);
834         continue;
835       }
836 
837       // Bail out if types do not match.
838       if (Ty != Q->getType())
839         return cannotDivide(Numerator);
840 
841       FoundDenominatorTerm = true;
842       Qs.push_back(Q);
843     }
844 
845     if (FoundDenominatorTerm) {
846       Remainder = Zero;
847       if (Qs.size() == 1)
848         Quotient = Qs[0];
849       else
850         Quotient = SE.getMulExpr(Qs);
851       return;
852     }
853 
854     if (!isa<SCEVUnknown>(Denominator))
855       return cannotDivide(Numerator);
856 
857     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
858     ValueToValueMap RewriteMap;
859     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
860         cast<SCEVConstant>(Zero)->getValue();
861     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
862 
863     if (Remainder->isZero()) {
864       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
865       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
866           cast<SCEVConstant>(One)->getValue();
867       Quotient =
868           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
869       return;
870     }
871 
872     // Quotient is (Numerator - Remainder) divided by Denominator.
873     const SCEV *Q, *R;
874     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
875     // This SCEV does not seem to simplify: fail the division here.
876     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
877       return cannotDivide(Numerator);
878     divide(SE, Diff, Denominator, &Q, &R);
879     if (R != Zero)
880       return cannotDivide(Numerator);
881     Quotient = Q;
882   }
883 
884 private:
885   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
886                const SCEV *Denominator)
887       : SE(S), Denominator(Denominator) {
888     Zero = SE.getZero(Denominator->getType());
889     One = SE.getOne(Denominator->getType());
890 
891     // We generally do not know how to divide Expr by Denominator. We
892     // initialize the division to a "cannot divide" state to simplify the rest
893     // of the code.
894     cannotDivide(Numerator);
895   }
896 
897   // Convenience function for giving up on the division. We set the quotient to
898   // be equal to zero and the remainder to be equal to the numerator.
899   void cannotDivide(const SCEV *Numerator) {
900     Quotient = Zero;
901     Remainder = Numerator;
902   }
903 
904   ScalarEvolution &SE;
905   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
906 };
907 
908 }
909 
910 //===----------------------------------------------------------------------===//
911 //                      Simple SCEV method implementations
912 //===----------------------------------------------------------------------===//
913 
914 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
915 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
916                                        ScalarEvolution &SE,
917                                        Type *ResultTy) {
918   // Handle the simplest case efficiently.
919   if (K == 1)
920     return SE.getTruncateOrZeroExtend(It, ResultTy);
921 
922   // We are using the following formula for BC(It, K):
923   //
924   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
925   //
926   // Suppose, W is the bitwidth of the return value.  We must be prepared for
927   // overflow.  Hence, we must assure that the result of our computation is
928   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
929   // safe in modular arithmetic.
930   //
931   // However, this code doesn't use exactly that formula; the formula it uses
932   // is something like the following, where T is the number of factors of 2 in
933   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
934   // exponentiation:
935   //
936   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
937   //
938   // This formula is trivially equivalent to the previous formula.  However,
939   // this formula can be implemented much more efficiently.  The trick is that
940   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
941   // arithmetic.  To do exact division in modular arithmetic, all we have
942   // to do is multiply by the inverse.  Therefore, this step can be done at
943   // width W.
944   //
945   // The next issue is how to safely do the division by 2^T.  The way this
946   // is done is by doing the multiplication step at a width of at least W + T
947   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
948   // when we perform the division by 2^T (which is equivalent to a right shift
949   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
950   // truncated out after the division by 2^T.
951   //
952   // In comparison to just directly using the first formula, this technique
953   // is much more efficient; using the first formula requires W * K bits,
954   // but this formula less than W + K bits. Also, the first formula requires
955   // a division step, whereas this formula only requires multiplies and shifts.
956   //
957   // It doesn't matter whether the subtraction step is done in the calculation
958   // width or the input iteration count's width; if the subtraction overflows,
959   // the result must be zero anyway.  We prefer here to do it in the width of
960   // the induction variable because it helps a lot for certain cases; CodeGen
961   // isn't smart enough to ignore the overflow, which leads to much less
962   // efficient code if the width of the subtraction is wider than the native
963   // register width.
964   //
965   // (It's possible to not widen at all by pulling out factors of 2 before
966   // the multiplication; for example, K=2 can be calculated as
967   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
968   // extra arithmetic, so it's not an obvious win, and it gets
969   // much more complicated for K > 3.)
970 
971   // Protection from insane SCEVs; this bound is conservative,
972   // but it probably doesn't matter.
973   if (K > 1000)
974     return SE.getCouldNotCompute();
975 
976   unsigned W = SE.getTypeSizeInBits(ResultTy);
977 
978   // Calculate K! / 2^T and T; we divide out the factors of two before
979   // multiplying for calculating K! / 2^T to avoid overflow.
980   // Other overflow doesn't matter because we only care about the bottom
981   // W bits of the result.
982   APInt OddFactorial(W, 1);
983   unsigned T = 1;
984   for (unsigned i = 3; i <= K; ++i) {
985     APInt Mult(W, i);
986     unsigned TwoFactors = Mult.countTrailingZeros();
987     T += TwoFactors;
988     Mult = Mult.lshr(TwoFactors);
989     OddFactorial *= Mult;
990   }
991 
992   // We need at least W + T bits for the multiplication step
993   unsigned CalculationBits = W + T;
994 
995   // Calculate 2^T, at width T+W.
996   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
997 
998   // Calculate the multiplicative inverse of K! / 2^T;
999   // this multiplication factor will perform the exact division by
1000   // K! / 2^T.
1001   APInt Mod = APInt::getSignedMinValue(W+1);
1002   APInt MultiplyFactor = OddFactorial.zext(W+1);
1003   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1004   MultiplyFactor = MultiplyFactor.trunc(W);
1005 
1006   // Calculate the product, at width T+W
1007   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1008                                                       CalculationBits);
1009   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1010   for (unsigned i = 1; i != K; ++i) {
1011     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1012     Dividend = SE.getMulExpr(Dividend,
1013                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1014   }
1015 
1016   // Divide by 2^T
1017   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1018 
1019   // Truncate the result, and divide by K! / 2^T.
1020 
1021   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1022                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1023 }
1024 
1025 /// Return the value of this chain of recurrences at the specified iteration
1026 /// number.  We can evaluate this recurrence by multiplying each element in the
1027 /// chain by the binomial coefficient corresponding to it.  In other words, we
1028 /// can evaluate {A,+,B,+,C,+,D} as:
1029 ///
1030 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1031 ///
1032 /// where BC(It, k) stands for binomial coefficient.
1033 ///
1034 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1035                                                 ScalarEvolution &SE) const {
1036   const SCEV *Result = getStart();
1037   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1038     // The computation is correct in the face of overflow provided that the
1039     // multiplication is performed _after_ the evaluation of the binomial
1040     // coefficient.
1041     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1042     if (isa<SCEVCouldNotCompute>(Coeff))
1043       return Coeff;
1044 
1045     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1046   }
1047   return Result;
1048 }
1049 
1050 //===----------------------------------------------------------------------===//
1051 //                    SCEV Expression folder implementations
1052 //===----------------------------------------------------------------------===//
1053 
1054 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1055                                              Type *Ty) {
1056   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1057          "This is not a truncating conversion!");
1058   assert(isSCEVable(Ty) &&
1059          "This is not a conversion to a SCEVable type!");
1060   Ty = getEffectiveSCEVType(Ty);
1061 
1062   FoldingSetNodeID ID;
1063   ID.AddInteger(scTruncate);
1064   ID.AddPointer(Op);
1065   ID.AddPointer(Ty);
1066   void *IP = nullptr;
1067   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1068 
1069   // Fold if the operand is constant.
1070   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1071     return getConstant(
1072       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1073 
1074   // trunc(trunc(x)) --> trunc(x)
1075   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1076     return getTruncateExpr(ST->getOperand(), Ty);
1077 
1078   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1079   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1080     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1081 
1082   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1083   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1084     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1085 
1086   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1087   // eliminate all the truncates, or we replace other casts with truncates.
1088   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1089     SmallVector<const SCEV *, 4> Operands;
1090     bool hasTrunc = false;
1091     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1092       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1093       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1094         hasTrunc = isa<SCEVTruncateExpr>(S);
1095       Operands.push_back(S);
1096     }
1097     if (!hasTrunc)
1098       return getAddExpr(Operands);
1099     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1100   }
1101 
1102   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1103   // eliminate all the truncates, or we replace other casts with truncates.
1104   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1105     SmallVector<const SCEV *, 4> Operands;
1106     bool hasTrunc = false;
1107     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1108       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1109       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1110         hasTrunc = isa<SCEVTruncateExpr>(S);
1111       Operands.push_back(S);
1112     }
1113     if (!hasTrunc)
1114       return getMulExpr(Operands);
1115     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1116   }
1117 
1118   // If the input value is a chrec scev, truncate the chrec's operands.
1119   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1120     SmallVector<const SCEV *, 4> Operands;
1121     for (const SCEV *Op : AddRec->operands())
1122       Operands.push_back(getTruncateExpr(Op, Ty));
1123     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1124   }
1125 
1126   // The cast wasn't folded; create an explicit cast node. We can reuse
1127   // the existing insert position since if we get here, we won't have
1128   // made any changes which would invalidate it.
1129   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1130                                                  Op, Ty);
1131   UniqueSCEVs.InsertNode(S, IP);
1132   return S;
1133 }
1134 
1135 // Get the limit of a recurrence such that incrementing by Step cannot cause
1136 // signed overflow as long as the value of the recurrence within the
1137 // loop does not exceed this limit before incrementing.
1138 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1139                                                  ICmpInst::Predicate *Pred,
1140                                                  ScalarEvolution *SE) {
1141   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1142   if (SE->isKnownPositive(Step)) {
1143     *Pred = ICmpInst::ICMP_SLT;
1144     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1145                            SE->getSignedRange(Step).getSignedMax());
1146   }
1147   if (SE->isKnownNegative(Step)) {
1148     *Pred = ICmpInst::ICMP_SGT;
1149     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1150                            SE->getSignedRange(Step).getSignedMin());
1151   }
1152   return nullptr;
1153 }
1154 
1155 // Get the limit of a recurrence such that incrementing by Step cannot cause
1156 // unsigned overflow as long as the value of the recurrence within the loop does
1157 // not exceed this limit before incrementing.
1158 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1159                                                    ICmpInst::Predicate *Pred,
1160                                                    ScalarEvolution *SE) {
1161   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1162   *Pred = ICmpInst::ICMP_ULT;
1163 
1164   return SE->getConstant(APInt::getMinValue(BitWidth) -
1165                          SE->getUnsignedRange(Step).getUnsignedMax());
1166 }
1167 
1168 namespace {
1169 
1170 struct ExtendOpTraitsBase {
1171   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1172 };
1173 
1174 // Used to make code generic over signed and unsigned overflow.
1175 template <typename ExtendOp> struct ExtendOpTraits {
1176   // Members present:
1177   //
1178   // static const SCEV::NoWrapFlags WrapType;
1179   //
1180   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1181   //
1182   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1183   //                                           ICmpInst::Predicate *Pred,
1184   //                                           ScalarEvolution *SE);
1185 };
1186 
1187 template <>
1188 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1189   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1190 
1191   static const GetExtendExprTy GetExtendExpr;
1192 
1193   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1194                                              ICmpInst::Predicate *Pred,
1195                                              ScalarEvolution *SE) {
1196     return getSignedOverflowLimitForStep(Step, Pred, SE);
1197   }
1198 };
1199 
1200 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1201     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1202 
1203 template <>
1204 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1205   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1206 
1207   static const GetExtendExprTy GetExtendExpr;
1208 
1209   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1210                                              ICmpInst::Predicate *Pred,
1211                                              ScalarEvolution *SE) {
1212     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1213   }
1214 };
1215 
1216 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1217     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1218 }
1219 
1220 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1221 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1222 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1223 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1224 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1225 // expression "Step + sext/zext(PreIncAR)" is congruent with
1226 // "sext/zext(PostIncAR)"
1227 template <typename ExtendOpTy>
1228 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1229                                         ScalarEvolution *SE) {
1230   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1231   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1232 
1233   const Loop *L = AR->getLoop();
1234   const SCEV *Start = AR->getStart();
1235   const SCEV *Step = AR->getStepRecurrence(*SE);
1236 
1237   // Check for a simple looking step prior to loop entry.
1238   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1239   if (!SA)
1240     return nullptr;
1241 
1242   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1243   // subtraction is expensive. For this purpose, perform a quick and dirty
1244   // difference, by checking for Step in the operand list.
1245   SmallVector<const SCEV *, 4> DiffOps;
1246   for (const SCEV *Op : SA->operands())
1247     if (Op != Step)
1248       DiffOps.push_back(Op);
1249 
1250   if (DiffOps.size() == SA->getNumOperands())
1251     return nullptr;
1252 
1253   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1254   // `Step`:
1255 
1256   // 1. NSW/NUW flags on the step increment.
1257   auto PreStartFlags =
1258     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1259   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1260   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1261       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1262 
1263   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1264   // "S+X does not sign/unsign-overflow".
1265   //
1266 
1267   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1268   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1269       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1270     return PreStart;
1271 
1272   // 2. Direct overflow check on the step operation's expression.
1273   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1274   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1275   const SCEV *OperandExtendedStart =
1276       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1277                      (SE->*GetExtendExpr)(Step, WideTy));
1278   if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1279     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1280       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1281       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1282       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1283       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1284     }
1285     return PreStart;
1286   }
1287 
1288   // 3. Loop precondition.
1289   ICmpInst::Predicate Pred;
1290   const SCEV *OverflowLimit =
1291       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1292 
1293   if (OverflowLimit &&
1294       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1295     return PreStart;
1296 
1297   return nullptr;
1298 }
1299 
1300 // Get the normalized zero or sign extended expression for this AddRec's Start.
1301 template <typename ExtendOpTy>
1302 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1303                                         ScalarEvolution *SE) {
1304   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1305 
1306   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1307   if (!PreStart)
1308     return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1309 
1310   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1311                         (SE->*GetExtendExpr)(PreStart, Ty));
1312 }
1313 
1314 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1315 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1316 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1317 //
1318 // Formally:
1319 //
1320 //     {S,+,X} == {S-T,+,X} + T
1321 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1322 //
1323 // If ({S-T,+,X} + T) does not overflow  ... (1)
1324 //
1325 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1326 //
1327 // If {S-T,+,X} does not overflow  ... (2)
1328 //
1329 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1330 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1331 //
1332 // If (S-T)+T does not overflow  ... (3)
1333 //
1334 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1335 //      == {Ext(S),+,Ext(X)} == LHS
1336 //
1337 // Thus, if (1), (2) and (3) are true for some T, then
1338 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1339 //
1340 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1341 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1342 // to check for (1) and (2).
1343 //
1344 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1345 // is `Delta` (defined below).
1346 //
1347 template <typename ExtendOpTy>
1348 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1349                                                 const SCEV *Step,
1350                                                 const Loop *L) {
1351   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1352 
1353   // We restrict `Start` to a constant to prevent SCEV from spending too much
1354   // time here.  It is correct (but more expensive) to continue with a
1355   // non-constant `Start` and do a general SCEV subtraction to compute
1356   // `PreStart` below.
1357   //
1358   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1359   if (!StartC)
1360     return false;
1361 
1362   APInt StartAI = StartC->getAPInt();
1363 
1364   for (unsigned Delta : {-2, -1, 1, 2}) {
1365     const SCEV *PreStart = getConstant(StartAI - Delta);
1366 
1367     FoldingSetNodeID ID;
1368     ID.AddInteger(scAddRecExpr);
1369     ID.AddPointer(PreStart);
1370     ID.AddPointer(Step);
1371     ID.AddPointer(L);
1372     void *IP = nullptr;
1373     const auto *PreAR =
1374       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1375 
1376     // Give up if we don't already have the add recurrence we need because
1377     // actually constructing an add recurrence is relatively expensive.
1378     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1379       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1380       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1381       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1382           DeltaS, &Pred, this);
1383       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1384         return true;
1385     }
1386   }
1387 
1388   return false;
1389 }
1390 
1391 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1392                                                Type *Ty) {
1393   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1394          "This is not an extending conversion!");
1395   assert(isSCEVable(Ty) &&
1396          "This is not a conversion to a SCEVable type!");
1397   Ty = getEffectiveSCEVType(Ty);
1398 
1399   // Fold if the operand is constant.
1400   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1401     return getConstant(
1402       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1403 
1404   // zext(zext(x)) --> zext(x)
1405   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1406     return getZeroExtendExpr(SZ->getOperand(), Ty);
1407 
1408   // Before doing any expensive analysis, check to see if we've already
1409   // computed a SCEV for this Op and Ty.
1410   FoldingSetNodeID ID;
1411   ID.AddInteger(scZeroExtend);
1412   ID.AddPointer(Op);
1413   ID.AddPointer(Ty);
1414   void *IP = nullptr;
1415   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1416 
1417   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1418   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1419     // It's possible the bits taken off by the truncate were all zero bits. If
1420     // so, we should be able to simplify this further.
1421     const SCEV *X = ST->getOperand();
1422     ConstantRange CR = getUnsignedRange(X);
1423     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1424     unsigned NewBits = getTypeSizeInBits(Ty);
1425     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1426             CR.zextOrTrunc(NewBits)))
1427       return getTruncateOrZeroExtend(X, Ty);
1428   }
1429 
1430   // If the input value is a chrec scev, and we can prove that the value
1431   // did not overflow the old, smaller, value, we can zero extend all of the
1432   // operands (often constants).  This allows analysis of something like
1433   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1434   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1435     if (AR->isAffine()) {
1436       const SCEV *Start = AR->getStart();
1437       const SCEV *Step = AR->getStepRecurrence(*this);
1438       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1439       const Loop *L = AR->getLoop();
1440 
1441       if (!AR->hasNoUnsignedWrap()) {
1442         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1443         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1444       }
1445 
1446       // If we have special knowledge that this addrec won't overflow,
1447       // we don't need to do any further analysis.
1448       if (AR->hasNoUnsignedWrap())
1449         return getAddRecExpr(
1450             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1451             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1452 
1453       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1454       // Note that this serves two purposes: It filters out loops that are
1455       // simply not analyzable, and it covers the case where this code is
1456       // being called from within backedge-taken count analysis, such that
1457       // attempting to ask for the backedge-taken count would likely result
1458       // in infinite recursion. In the later case, the analysis code will
1459       // cope with a conservative value, and it will take care to purge
1460       // that value once it has finished.
1461       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1462       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1463         // Manually compute the final value for AR, checking for
1464         // overflow.
1465 
1466         // Check whether the backedge-taken count can be losslessly casted to
1467         // the addrec's type. The count is always unsigned.
1468         const SCEV *CastedMaxBECount =
1469           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1470         const SCEV *RecastedMaxBECount =
1471           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1472         if (MaxBECount == RecastedMaxBECount) {
1473           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1474           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1475           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1476           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1477           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1478           const SCEV *WideMaxBECount =
1479             getZeroExtendExpr(CastedMaxBECount, WideTy);
1480           const SCEV *OperandExtendedAdd =
1481             getAddExpr(WideStart,
1482                        getMulExpr(WideMaxBECount,
1483                                   getZeroExtendExpr(Step, WideTy)));
1484           if (ZAdd == OperandExtendedAdd) {
1485             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1486             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1487             // Return the expression with the addrec on the outside.
1488             return getAddRecExpr(
1489                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1490                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1491           }
1492           // Similar to above, only this time treat the step value as signed.
1493           // This covers loops that count down.
1494           OperandExtendedAdd =
1495             getAddExpr(WideStart,
1496                        getMulExpr(WideMaxBECount,
1497                                   getSignExtendExpr(Step, WideTy)));
1498           if (ZAdd == OperandExtendedAdd) {
1499             // Cache knowledge of AR NW, which is propagated to this AddRec.
1500             // Negative step causes unsigned wrap, but it still can't self-wrap.
1501             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1502             // Return the expression with the addrec on the outside.
1503             return getAddRecExpr(
1504                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1505                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1506           }
1507         }
1508       }
1509 
1510       // Normally, in the cases we can prove no-overflow via a
1511       // backedge guarding condition, we can also compute a backedge
1512       // taken count for the loop.  The exceptions are assumptions and
1513       // guards present in the loop -- SCEV is not great at exploiting
1514       // these to compute max backedge taken counts, but can still use
1515       // these to prove lack of overflow.  Use this fact to avoid
1516       // doing extra work that may not pay off.
1517       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1518           !AC.assumptions().empty()) {
1519         // If the backedge is guarded by a comparison with the pre-inc
1520         // value the addrec is safe. Also, if the entry is guarded by
1521         // a comparison with the start value and the backedge is
1522         // guarded by a comparison with the post-inc value, the addrec
1523         // 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
1532             // AddRec.
1533             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1534             // Return the expression with the addrec on the outside.
1535             return getAddRecExpr(
1536                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1537                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1538           }
1539         } else if (isKnownNegative(Step)) {
1540           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1541                                       getSignedRange(Step).getSignedMin());
1542           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1543               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1544                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1545                                            AR->getPostIncExpr(*this), N))) {
1546             // Cache knowledge of AR NW, which is propagated to this
1547             // AddRec.  Negative step causes unsigned wrap, but it
1548             // still can't self-wrap.
1549             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1550             // Return the expression with the addrec on the outside.
1551             return getAddRecExpr(
1552                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1553                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1554           }
1555         }
1556       }
1557 
1558       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1559         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1560         return getAddRecExpr(
1561             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1562             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1563       }
1564     }
1565 
1566   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1567     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1568     if (SA->hasNoUnsignedWrap()) {
1569       // If the addition does not unsign overflow then we can, by definition,
1570       // commute the zero extension with the addition operation.
1571       SmallVector<const SCEV *, 4> Ops;
1572       for (const auto *Op : SA->operands())
1573         Ops.push_back(getZeroExtendExpr(Op, Ty));
1574       return getAddExpr(Ops, SCEV::FlagNUW);
1575     }
1576   }
1577 
1578   // The cast wasn't folded; create an explicit cast node.
1579   // Recompute the insert position, as it may have been invalidated.
1580   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1581   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1582                                                    Op, Ty);
1583   UniqueSCEVs.InsertNode(S, IP);
1584   return S;
1585 }
1586 
1587 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1588                                                Type *Ty) {
1589   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1590          "This is not an extending conversion!");
1591   assert(isSCEVable(Ty) &&
1592          "This is not a conversion to a SCEVable type!");
1593   Ty = getEffectiveSCEVType(Ty);
1594 
1595   // Fold if the operand is constant.
1596   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1597     return getConstant(
1598       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1599 
1600   // sext(sext(x)) --> sext(x)
1601   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1602     return getSignExtendExpr(SS->getOperand(), Ty);
1603 
1604   // sext(zext(x)) --> zext(x)
1605   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1606     return getZeroExtendExpr(SZ->getOperand(), Ty);
1607 
1608   // Before doing any expensive analysis, check to see if we've already
1609   // computed a SCEV for this Op and Ty.
1610   FoldingSetNodeID ID;
1611   ID.AddInteger(scSignExtend);
1612   ID.AddPointer(Op);
1613   ID.AddPointer(Ty);
1614   void *IP = nullptr;
1615   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1616 
1617   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1618   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1619     // It's possible the bits taken off by the truncate were all sign bits. If
1620     // so, we should be able to simplify this further.
1621     const SCEV *X = ST->getOperand();
1622     ConstantRange CR = getSignedRange(X);
1623     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1624     unsigned NewBits = getTypeSizeInBits(Ty);
1625     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1626             CR.sextOrTrunc(NewBits)))
1627       return getTruncateOrSignExtend(X, Ty);
1628   }
1629 
1630   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1631   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1632     if (SA->getNumOperands() == 2) {
1633       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1634       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1635       if (SMul && SC1) {
1636         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1637           const APInt &C1 = SC1->getAPInt();
1638           const APInt &C2 = SC2->getAPInt();
1639           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1640               C2.ugt(C1) && C2.isPowerOf2())
1641             return getAddExpr(getSignExtendExpr(SC1, Ty),
1642                               getSignExtendExpr(SMul, Ty));
1643         }
1644       }
1645     }
1646 
1647     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1648     if (SA->hasNoSignedWrap()) {
1649       // If the addition does not sign overflow then we can, by definition,
1650       // commute the sign extension with the addition operation.
1651       SmallVector<const SCEV *, 4> Ops;
1652       for (const auto *Op : SA->operands())
1653         Ops.push_back(getSignExtendExpr(Op, Ty));
1654       return getAddExpr(Ops, SCEV::FlagNSW);
1655     }
1656   }
1657   // If the input value is a chrec scev, and we can prove that the value
1658   // did not overflow the old, smaller, value, we can sign extend all of the
1659   // operands (often constants).  This allows analysis of something like
1660   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1661   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1662     if (AR->isAffine()) {
1663       const SCEV *Start = AR->getStart();
1664       const SCEV *Step = AR->getStepRecurrence(*this);
1665       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1666       const Loop *L = AR->getLoop();
1667 
1668       if (!AR->hasNoSignedWrap()) {
1669         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1670         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1671       }
1672 
1673       // If we have special knowledge that this addrec won't overflow,
1674       // we don't need to do any further analysis.
1675       if (AR->hasNoSignedWrap())
1676         return getAddRecExpr(
1677             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1678             getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1679 
1680       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1681       // Note that this serves two purposes: It filters out loops that are
1682       // simply not analyzable, and it covers the case where this code is
1683       // being called from within backedge-taken count analysis, such that
1684       // attempting to ask for the backedge-taken count would likely result
1685       // in infinite recursion. In the later case, the analysis code will
1686       // cope with a conservative value, and it will take care to purge
1687       // that value once it has finished.
1688       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1689       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1690         // Manually compute the final value for AR, checking for
1691         // overflow.
1692 
1693         // Check whether the backedge-taken count can be losslessly casted to
1694         // the addrec's type. The count is always unsigned.
1695         const SCEV *CastedMaxBECount =
1696           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1697         const SCEV *RecastedMaxBECount =
1698           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1699         if (MaxBECount == RecastedMaxBECount) {
1700           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1701           // Check whether Start+Step*MaxBECount has no signed overflow.
1702           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1703           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1704           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1705           const SCEV *WideMaxBECount =
1706             getZeroExtendExpr(CastedMaxBECount, WideTy);
1707           const SCEV *OperandExtendedAdd =
1708             getAddExpr(WideStart,
1709                        getMulExpr(WideMaxBECount,
1710                                   getSignExtendExpr(Step, WideTy)));
1711           if (SAdd == OperandExtendedAdd) {
1712             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1713             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1714             // Return the expression with the addrec on the outside.
1715             return getAddRecExpr(
1716                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1717                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1718           }
1719           // Similar to above, only this time treat the step value as unsigned.
1720           // This covers loops that count up with an unsigned step.
1721           OperandExtendedAdd =
1722             getAddExpr(WideStart,
1723                        getMulExpr(WideMaxBECount,
1724                                   getZeroExtendExpr(Step, WideTy)));
1725           if (SAdd == OperandExtendedAdd) {
1726             // If AR wraps around then
1727             //
1728             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1729             // => SAdd != OperandExtendedAdd
1730             //
1731             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1732             // (SAdd == OperandExtendedAdd => AR is NW)
1733 
1734             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1735 
1736             // Return the expression with the addrec on the outside.
1737             return getAddRecExpr(
1738                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1739                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1740           }
1741         }
1742       }
1743 
1744       // Normally, in the cases we can prove no-overflow via a
1745       // backedge guarding condition, we can also compute a backedge
1746       // taken count for the loop.  The exceptions are assumptions and
1747       // guards present in the loop -- SCEV is not great at exploiting
1748       // these to compute max backedge taken counts, but can still use
1749       // these to prove lack of overflow.  Use this fact to avoid
1750       // doing extra work that may not pay off.
1751 
1752       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1753           !AC.assumptions().empty()) {
1754         // If the backedge is guarded by a comparison with the pre-inc
1755         // value the addrec is safe. Also, if the entry is guarded by
1756         // a comparison with the start value and the backedge is
1757         // guarded by a comparison with the post-inc value, the addrec
1758         // is safe.
1759         ICmpInst::Predicate Pred;
1760         const SCEV *OverflowLimit =
1761             getSignedOverflowLimitForStep(Step, &Pred, this);
1762         if (OverflowLimit &&
1763             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1764              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1765               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1766                                           OverflowLimit)))) {
1767           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1768           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1769           return getAddRecExpr(
1770               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1771               getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1772         }
1773       }
1774 
1775       // If Start and Step are constants, check if we can apply this
1776       // transformation:
1777       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1778       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1779       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1780       if (SC1 && SC2) {
1781         const APInt &C1 = SC1->getAPInt();
1782         const APInt &C2 = SC2->getAPInt();
1783         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1784             C2.isPowerOf2()) {
1785           Start = getSignExtendExpr(Start, Ty);
1786           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1787                                             AR->getNoWrapFlags());
1788           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1789         }
1790       }
1791 
1792       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1793         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1794         return getAddRecExpr(
1795             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1796             getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1797       }
1798     }
1799 
1800   // If the input value is provably positive and we could not simplify
1801   // away the sext build a zext instead.
1802   if (isKnownNonNegative(Op))
1803     return getZeroExtendExpr(Op, Ty);
1804 
1805   // The cast wasn't folded; create an explicit cast node.
1806   // Recompute the insert position, as it may have been invalidated.
1807   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1808   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1809                                                    Op, Ty);
1810   UniqueSCEVs.InsertNode(S, IP);
1811   return S;
1812 }
1813 
1814 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1815 /// unspecified bits out to the given type.
1816 ///
1817 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1818                                               Type *Ty) {
1819   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1820          "This is not an extending conversion!");
1821   assert(isSCEVable(Ty) &&
1822          "This is not a conversion to a SCEVable type!");
1823   Ty = getEffectiveSCEVType(Ty);
1824 
1825   // Sign-extend negative constants.
1826   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1827     if (SC->getAPInt().isNegative())
1828       return getSignExtendExpr(Op, Ty);
1829 
1830   // Peel off a truncate cast.
1831   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1832     const SCEV *NewOp = T->getOperand();
1833     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1834       return getAnyExtendExpr(NewOp, Ty);
1835     return getTruncateOrNoop(NewOp, Ty);
1836   }
1837 
1838   // Next try a zext cast. If the cast is folded, use it.
1839   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1840   if (!isa<SCEVZeroExtendExpr>(ZExt))
1841     return ZExt;
1842 
1843   // Next try a sext cast. If the cast is folded, use it.
1844   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1845   if (!isa<SCEVSignExtendExpr>(SExt))
1846     return SExt;
1847 
1848   // Force the cast to be folded into the operands of an addrec.
1849   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1850     SmallVector<const SCEV *, 4> Ops;
1851     for (const SCEV *Op : AR->operands())
1852       Ops.push_back(getAnyExtendExpr(Op, Ty));
1853     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1854   }
1855 
1856   // If the expression is obviously signed, use the sext cast value.
1857   if (isa<SCEVSMaxExpr>(Op))
1858     return SExt;
1859 
1860   // Absent any other information, use the zext cast value.
1861   return ZExt;
1862 }
1863 
1864 /// Process the given Ops list, which is a list of operands to be added under
1865 /// the given scale, update the given map. This is a helper function for
1866 /// getAddRecExpr. As an example of what it does, given a sequence of operands
1867 /// that would form an add expression like this:
1868 ///
1869 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1870 ///
1871 /// where A and B are constants, update the map with these values:
1872 ///
1873 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1874 ///
1875 /// and add 13 + A*B*29 to AccumulatedConstant.
1876 /// This will allow getAddRecExpr to produce this:
1877 ///
1878 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1879 ///
1880 /// This form often exposes folding opportunities that are hidden in
1881 /// the original operand list.
1882 ///
1883 /// Return true iff it appears that any interesting folding opportunities
1884 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1885 /// the common case where no interesting opportunities are present, and
1886 /// is also used as a check to avoid infinite recursion.
1887 ///
1888 static bool
1889 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1890                              SmallVectorImpl<const SCEV *> &NewOps,
1891                              APInt &AccumulatedConstant,
1892                              const SCEV *const *Ops, size_t NumOperands,
1893                              const APInt &Scale,
1894                              ScalarEvolution &SE) {
1895   bool Interesting = false;
1896 
1897   // Iterate over the add operands. They are sorted, with constants first.
1898   unsigned i = 0;
1899   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1900     ++i;
1901     // Pull a buried constant out to the outside.
1902     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1903       Interesting = true;
1904     AccumulatedConstant += Scale * C->getAPInt();
1905   }
1906 
1907   // Next comes everything else. We're especially interested in multiplies
1908   // here, but they're in the middle, so just visit the rest with one loop.
1909   for (; i != NumOperands; ++i) {
1910     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1911     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1912       APInt NewScale =
1913           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
1914       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1915         // A multiplication of a constant with another add; recurse.
1916         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1917         Interesting |=
1918           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1919                                        Add->op_begin(), Add->getNumOperands(),
1920                                        NewScale, SE);
1921       } else {
1922         // A multiplication of a constant with some other value. Update
1923         // the map.
1924         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1925         const SCEV *Key = SE.getMulExpr(MulOps);
1926         auto Pair = M.insert({Key, NewScale});
1927         if (Pair.second) {
1928           NewOps.push_back(Pair.first->first);
1929         } else {
1930           Pair.first->second += NewScale;
1931           // The map already had an entry for this value, which may indicate
1932           // a folding opportunity.
1933           Interesting = true;
1934         }
1935       }
1936     } else {
1937       // An ordinary operand. Update the map.
1938       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1939           M.insert({Ops[i], Scale});
1940       if (Pair.second) {
1941         NewOps.push_back(Pair.first->first);
1942       } else {
1943         Pair.first->second += Scale;
1944         // The map already had an entry for this value, which may indicate
1945         // a folding opportunity.
1946         Interesting = true;
1947       }
1948     }
1949   }
1950 
1951   return Interesting;
1952 }
1953 
1954 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1955 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
1956 // can't-overflow flags for the operation if possible.
1957 static SCEV::NoWrapFlags
1958 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1959                       const SmallVectorImpl<const SCEV *> &Ops,
1960                       SCEV::NoWrapFlags Flags) {
1961   using namespace std::placeholders;
1962   typedef OverflowingBinaryOperator OBO;
1963 
1964   bool CanAnalyze =
1965       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1966   (void)CanAnalyze;
1967   assert(CanAnalyze && "don't call from other places!");
1968 
1969   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1970   SCEV::NoWrapFlags SignOrUnsignWrap =
1971       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1972 
1973   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1974   auto IsKnownNonNegative = [&](const SCEV *S) {
1975     return SE->isKnownNonNegative(S);
1976   };
1977 
1978   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
1979     Flags =
1980         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1981 
1982   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1983 
1984   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1985       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1986 
1987     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
1988     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
1989 
1990     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
1991     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
1992       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1993           Instruction::Add, C, OBO::NoSignedWrap);
1994       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
1995         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
1996     }
1997     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
1998       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1999           Instruction::Add, C, OBO::NoUnsignedWrap);
2000       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2001         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2002     }
2003   }
2004 
2005   return Flags;
2006 }
2007 
2008 /// Get a canonical add expression, or something simpler if possible.
2009 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2010                                         SCEV::NoWrapFlags Flags) {
2011   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2012          "only nuw or nsw allowed");
2013   assert(!Ops.empty() && "Cannot get empty add!");
2014   if (Ops.size() == 1) return Ops[0];
2015 #ifndef NDEBUG
2016   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2017   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2018     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2019            "SCEVAddExpr operand types don't match!");
2020 #endif
2021 
2022   // Sort by complexity, this groups all similar expression types together.
2023   GroupByComplexity(Ops, &LI);
2024 
2025   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2026 
2027   // If there are any constants, fold them together.
2028   unsigned Idx = 0;
2029   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2030     ++Idx;
2031     assert(Idx < Ops.size());
2032     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2033       // We found two constants, fold them together!
2034       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2035       if (Ops.size() == 2) return Ops[0];
2036       Ops.erase(Ops.begin()+1);  // Erase the folded element
2037       LHSC = cast<SCEVConstant>(Ops[0]);
2038     }
2039 
2040     // If we are left with a constant zero being added, strip it off.
2041     if (LHSC->getValue()->isZero()) {
2042       Ops.erase(Ops.begin());
2043       --Idx;
2044     }
2045 
2046     if (Ops.size() == 1) return Ops[0];
2047   }
2048 
2049   // Okay, check to see if the same value occurs in the operand list more than
2050   // once.  If so, merge them together into an multiply expression.  Since we
2051   // sorted the list, these values are required to be adjacent.
2052   Type *Ty = Ops[0]->getType();
2053   bool FoundMatch = false;
2054   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2055     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2056       // Scan ahead to count how many equal operands there are.
2057       unsigned Count = 2;
2058       while (i+Count != e && Ops[i+Count] == Ops[i])
2059         ++Count;
2060       // Merge the values into a multiply.
2061       const SCEV *Scale = getConstant(Ty, Count);
2062       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2063       if (Ops.size() == Count)
2064         return Mul;
2065       Ops[i] = Mul;
2066       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2067       --i; e -= Count - 1;
2068       FoundMatch = true;
2069     }
2070   if (FoundMatch)
2071     return getAddExpr(Ops, Flags);
2072 
2073   // Check for truncates. If all the operands are truncated from the same
2074   // type, see if factoring out the truncate would permit the result to be
2075   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2076   // if the contents of the resulting outer trunc fold to something simple.
2077   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2078     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2079     Type *DstType = Trunc->getType();
2080     Type *SrcType = Trunc->getOperand()->getType();
2081     SmallVector<const SCEV *, 8> LargeOps;
2082     bool Ok = true;
2083     // Check all the operands to see if they can be represented in the
2084     // source type of the truncate.
2085     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2086       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2087         if (T->getOperand()->getType() != SrcType) {
2088           Ok = false;
2089           break;
2090         }
2091         LargeOps.push_back(T->getOperand());
2092       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2093         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2094       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2095         SmallVector<const SCEV *, 8> LargeMulOps;
2096         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2097           if (const SCEVTruncateExpr *T =
2098                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2099             if (T->getOperand()->getType() != SrcType) {
2100               Ok = false;
2101               break;
2102             }
2103             LargeMulOps.push_back(T->getOperand());
2104           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2105             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2106           } else {
2107             Ok = false;
2108             break;
2109           }
2110         }
2111         if (Ok)
2112           LargeOps.push_back(getMulExpr(LargeMulOps));
2113       } else {
2114         Ok = false;
2115         break;
2116       }
2117     }
2118     if (Ok) {
2119       // Evaluate the expression in the larger type.
2120       const SCEV *Fold = getAddExpr(LargeOps, Flags);
2121       // If it folds to something simple, use it. Otherwise, don't.
2122       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2123         return getTruncateExpr(Fold, DstType);
2124     }
2125   }
2126 
2127   // Skip past any other cast SCEVs.
2128   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2129     ++Idx;
2130 
2131   // If there are add operands they would be next.
2132   if (Idx < Ops.size()) {
2133     bool DeletedAdd = false;
2134     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2135       // If we have an add, expand the add operands onto the end of the operands
2136       // list.
2137       Ops.erase(Ops.begin()+Idx);
2138       Ops.append(Add->op_begin(), Add->op_end());
2139       DeletedAdd = true;
2140     }
2141 
2142     // If we deleted at least one add, we added operands to the end of the list,
2143     // and they are not necessarily sorted.  Recurse to resort and resimplify
2144     // any operands we just acquired.
2145     if (DeletedAdd)
2146       return getAddExpr(Ops);
2147   }
2148 
2149   // Skip over the add expression until we get to a multiply.
2150   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2151     ++Idx;
2152 
2153   // Check to see if there are any folding opportunities present with
2154   // operands multiplied by constant values.
2155   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2156     uint64_t BitWidth = getTypeSizeInBits(Ty);
2157     DenseMap<const SCEV *, APInt> M;
2158     SmallVector<const SCEV *, 8> NewOps;
2159     APInt AccumulatedConstant(BitWidth, 0);
2160     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2161                                      Ops.data(), Ops.size(),
2162                                      APInt(BitWidth, 1), *this)) {
2163       struct APIntCompare {
2164         bool operator()(const APInt &LHS, const APInt &RHS) const {
2165           return LHS.ult(RHS);
2166         }
2167       };
2168 
2169       // Some interesting folding opportunity is present, so its worthwhile to
2170       // re-generate the operands list. Group the operands by constant scale,
2171       // to avoid multiplying by the same constant scale multiple times.
2172       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2173       for (const SCEV *NewOp : NewOps)
2174         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2175       // Re-generate the operands list.
2176       Ops.clear();
2177       if (AccumulatedConstant != 0)
2178         Ops.push_back(getConstant(AccumulatedConstant));
2179       for (auto &MulOp : MulOpLists)
2180         if (MulOp.first != 0)
2181           Ops.push_back(getMulExpr(getConstant(MulOp.first),
2182                                    getAddExpr(MulOp.second)));
2183       if (Ops.empty())
2184         return getZero(Ty);
2185       if (Ops.size() == 1)
2186         return Ops[0];
2187       return getAddExpr(Ops);
2188     }
2189   }
2190 
2191   // If we are adding something to a multiply expression, make sure the
2192   // something is not already an operand of the multiply.  If so, merge it into
2193   // the multiply.
2194   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2195     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2196     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2197       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2198       if (isa<SCEVConstant>(MulOpSCEV))
2199         continue;
2200       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2201         if (MulOpSCEV == Ops[AddOp]) {
2202           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2203           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2204           if (Mul->getNumOperands() != 2) {
2205             // If the multiply has more than two operands, we must get the
2206             // Y*Z term.
2207             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2208                                                 Mul->op_begin()+MulOp);
2209             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2210             InnerMul = getMulExpr(MulOps);
2211           }
2212           const SCEV *One = getOne(Ty);
2213           const SCEV *AddOne = getAddExpr(One, InnerMul);
2214           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2215           if (Ops.size() == 2) return OuterMul;
2216           if (AddOp < Idx) {
2217             Ops.erase(Ops.begin()+AddOp);
2218             Ops.erase(Ops.begin()+Idx-1);
2219           } else {
2220             Ops.erase(Ops.begin()+Idx);
2221             Ops.erase(Ops.begin()+AddOp-1);
2222           }
2223           Ops.push_back(OuterMul);
2224           return getAddExpr(Ops);
2225         }
2226 
2227       // Check this multiply against other multiplies being added together.
2228       for (unsigned OtherMulIdx = Idx+1;
2229            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2230            ++OtherMulIdx) {
2231         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2232         // If MulOp occurs in OtherMul, we can fold the two multiplies
2233         // together.
2234         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2235              OMulOp != e; ++OMulOp)
2236           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2237             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2238             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2239             if (Mul->getNumOperands() != 2) {
2240               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2241                                                   Mul->op_begin()+MulOp);
2242               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2243               InnerMul1 = getMulExpr(MulOps);
2244             }
2245             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2246             if (OtherMul->getNumOperands() != 2) {
2247               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2248                                                   OtherMul->op_begin()+OMulOp);
2249               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2250               InnerMul2 = getMulExpr(MulOps);
2251             }
2252             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2253             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2254             if (Ops.size() == 2) return OuterMul;
2255             Ops.erase(Ops.begin()+Idx);
2256             Ops.erase(Ops.begin()+OtherMulIdx-1);
2257             Ops.push_back(OuterMul);
2258             return getAddExpr(Ops);
2259           }
2260       }
2261     }
2262   }
2263 
2264   // If there are any add recurrences in the operands list, see if any other
2265   // added values are loop invariant.  If so, we can fold them into the
2266   // recurrence.
2267   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2268     ++Idx;
2269 
2270   // Scan over all recurrences, trying to fold loop invariants into them.
2271   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2272     // Scan all of the other operands to this add and add them to the vector if
2273     // they are loop invariant w.r.t. the recurrence.
2274     SmallVector<const SCEV *, 8> LIOps;
2275     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2276     const Loop *AddRecLoop = AddRec->getLoop();
2277     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2278       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2279         LIOps.push_back(Ops[i]);
2280         Ops.erase(Ops.begin()+i);
2281         --i; --e;
2282       }
2283 
2284     // If we found some loop invariants, fold them into the recurrence.
2285     if (!LIOps.empty()) {
2286       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2287       LIOps.push_back(AddRec->getStart());
2288 
2289       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2290                                              AddRec->op_end());
2291       // This follows from the fact that the no-wrap flags on the outer add
2292       // expression are applicable on the 0th iteration, when the add recurrence
2293       // will be equal to its start value.
2294       AddRecOps[0] = getAddExpr(LIOps, Flags);
2295 
2296       // Build the new addrec. Propagate the NUW and NSW flags if both the
2297       // outer add and the inner addrec are guaranteed to have no overflow.
2298       // Always propagate NW.
2299       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2300       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2301 
2302       // If all of the other operands were loop invariant, we are done.
2303       if (Ops.size() == 1) return NewRec;
2304 
2305       // Otherwise, add the folded AddRec by the non-invariant parts.
2306       for (unsigned i = 0;; ++i)
2307         if (Ops[i] == AddRec) {
2308           Ops[i] = NewRec;
2309           break;
2310         }
2311       return getAddExpr(Ops);
2312     }
2313 
2314     // Okay, if there weren't any loop invariants to be folded, check to see if
2315     // there are multiple AddRec's with the same loop induction variable being
2316     // added together.  If so, we can fold them.
2317     for (unsigned OtherIdx = Idx+1;
2318          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2319          ++OtherIdx)
2320       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2321         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2322         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2323                                                AddRec->op_end());
2324         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2325              ++OtherIdx)
2326           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2327             if (OtherAddRec->getLoop() == AddRecLoop) {
2328               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2329                    i != e; ++i) {
2330                 if (i >= AddRecOps.size()) {
2331                   AddRecOps.append(OtherAddRec->op_begin()+i,
2332                                    OtherAddRec->op_end());
2333                   break;
2334                 }
2335                 AddRecOps[i] = getAddExpr(AddRecOps[i],
2336                                           OtherAddRec->getOperand(i));
2337               }
2338               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2339             }
2340         // Step size has changed, so we cannot guarantee no self-wraparound.
2341         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2342         return getAddExpr(Ops);
2343       }
2344 
2345     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2346     // next one.
2347   }
2348 
2349   // Okay, it looks like we really DO need an add expr.  Check to see if we
2350   // already have one, otherwise create a new one.
2351   FoldingSetNodeID ID;
2352   ID.AddInteger(scAddExpr);
2353   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2354     ID.AddPointer(Ops[i]);
2355   void *IP = nullptr;
2356   SCEVAddExpr *S =
2357     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2358   if (!S) {
2359     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2360     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2361     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2362                                         O, Ops.size());
2363     UniqueSCEVs.InsertNode(S, IP);
2364   }
2365   S->setNoWrapFlags(Flags);
2366   return S;
2367 }
2368 
2369 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2370   uint64_t k = i*j;
2371   if (j > 1 && k / j != i) Overflow = true;
2372   return k;
2373 }
2374 
2375 /// Compute the result of "n choose k", the binomial coefficient.  If an
2376 /// intermediate computation overflows, Overflow will be set and the return will
2377 /// be garbage. Overflow is not cleared on absence of overflow.
2378 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2379   // We use the multiplicative formula:
2380   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2381   // At each iteration, we take the n-th term of the numeral and divide by the
2382   // (k-n)th term of the denominator.  This division will always produce an
2383   // integral result, and helps reduce the chance of overflow in the
2384   // intermediate computations. However, we can still overflow even when the
2385   // final result would fit.
2386 
2387   if (n == 0 || n == k) return 1;
2388   if (k > n) return 0;
2389 
2390   if (k > n/2)
2391     k = n-k;
2392 
2393   uint64_t r = 1;
2394   for (uint64_t i = 1; i <= k; ++i) {
2395     r = umul_ov(r, n-(i-1), Overflow);
2396     r /= i;
2397   }
2398   return r;
2399 }
2400 
2401 /// Determine if any of the operands in this SCEV are a constant or if
2402 /// any of the add or multiply expressions in this SCEV contain a constant.
2403 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2404   SmallVector<const SCEV *, 4> Ops;
2405   Ops.push_back(StartExpr);
2406   while (!Ops.empty()) {
2407     const SCEV *CurrentExpr = Ops.pop_back_val();
2408     if (isa<SCEVConstant>(*CurrentExpr))
2409       return true;
2410 
2411     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2412       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2413       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2414     }
2415   }
2416   return false;
2417 }
2418 
2419 /// Get a canonical multiply expression, or something simpler if possible.
2420 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2421                                         SCEV::NoWrapFlags Flags) {
2422   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2423          "only nuw or nsw allowed");
2424   assert(!Ops.empty() && "Cannot get empty mul!");
2425   if (Ops.size() == 1) return Ops[0];
2426 #ifndef NDEBUG
2427   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2428   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2429     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2430            "SCEVMulExpr operand types don't match!");
2431 #endif
2432 
2433   // Sort by complexity, this groups all similar expression types together.
2434   GroupByComplexity(Ops, &LI);
2435 
2436   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2437 
2438   // If there are any constants, fold them together.
2439   unsigned Idx = 0;
2440   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2441 
2442     // C1*(C2+V) -> C1*C2 + C1*V
2443     if (Ops.size() == 2)
2444         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2445           // If any of Add's ops are Adds or Muls with a constant,
2446           // apply this transformation as well.
2447           if (Add->getNumOperands() == 2)
2448             if (containsConstantSomewhere(Add))
2449               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2450                                 getMulExpr(LHSC, Add->getOperand(1)));
2451 
2452     ++Idx;
2453     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2454       // We found two constants, fold them together!
2455       ConstantInt *Fold =
2456           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2457       Ops[0] = getConstant(Fold);
2458       Ops.erase(Ops.begin()+1);  // Erase the folded element
2459       if (Ops.size() == 1) return Ops[0];
2460       LHSC = cast<SCEVConstant>(Ops[0]);
2461     }
2462 
2463     // If we are left with a constant one being multiplied, strip it off.
2464     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2465       Ops.erase(Ops.begin());
2466       --Idx;
2467     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2468       // If we have a multiply of zero, it will always be zero.
2469       return Ops[0];
2470     } else if (Ops[0]->isAllOnesValue()) {
2471       // If we have a mul by -1 of an add, try distributing the -1 among the
2472       // add operands.
2473       if (Ops.size() == 2) {
2474         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2475           SmallVector<const SCEV *, 4> NewOps;
2476           bool AnyFolded = false;
2477           for (const SCEV *AddOp : Add->operands()) {
2478             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2479             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2480             NewOps.push_back(Mul);
2481           }
2482           if (AnyFolded)
2483             return getAddExpr(NewOps);
2484         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2485           // Negation preserves a recurrence's no self-wrap property.
2486           SmallVector<const SCEV *, 4> Operands;
2487           for (const SCEV *AddRecOp : AddRec->operands())
2488             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2489 
2490           return getAddRecExpr(Operands, AddRec->getLoop(),
2491                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2492         }
2493       }
2494     }
2495 
2496     if (Ops.size() == 1)
2497       return Ops[0];
2498   }
2499 
2500   // Skip over the add expression until we get to a multiply.
2501   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2502     ++Idx;
2503 
2504   // If there are mul operands inline them all into this expression.
2505   if (Idx < Ops.size()) {
2506     bool DeletedMul = false;
2507     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2508       // If we have an mul, expand the mul operands onto the end of the operands
2509       // list.
2510       Ops.erase(Ops.begin()+Idx);
2511       Ops.append(Mul->op_begin(), Mul->op_end());
2512       DeletedMul = true;
2513     }
2514 
2515     // If we deleted at least one mul, we added operands to the end of the list,
2516     // and they are not necessarily sorted.  Recurse to resort and resimplify
2517     // any operands we just acquired.
2518     if (DeletedMul)
2519       return getMulExpr(Ops);
2520   }
2521 
2522   // If there are any add recurrences in the operands list, see if any other
2523   // added values are loop invariant.  If so, we can fold them into the
2524   // recurrence.
2525   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2526     ++Idx;
2527 
2528   // Scan over all recurrences, trying to fold loop invariants into them.
2529   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2530     // Scan all of the other operands to this mul and add them to the vector if
2531     // they are loop invariant w.r.t. the recurrence.
2532     SmallVector<const SCEV *, 8> LIOps;
2533     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2534     const Loop *AddRecLoop = AddRec->getLoop();
2535     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2536       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2537         LIOps.push_back(Ops[i]);
2538         Ops.erase(Ops.begin()+i);
2539         --i; --e;
2540       }
2541 
2542     // If we found some loop invariants, fold them into the recurrence.
2543     if (!LIOps.empty()) {
2544       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2545       SmallVector<const SCEV *, 4> NewOps;
2546       NewOps.reserve(AddRec->getNumOperands());
2547       const SCEV *Scale = getMulExpr(LIOps);
2548       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2549         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2550 
2551       // Build the new addrec. Propagate the NUW and NSW flags if both the
2552       // outer mul and the inner addrec are guaranteed to have no overflow.
2553       //
2554       // No self-wrap cannot be guaranteed after changing the step size, but
2555       // will be inferred if either NUW or NSW is true.
2556       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2557       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2558 
2559       // If all of the other operands were loop invariant, we are done.
2560       if (Ops.size() == 1) return NewRec;
2561 
2562       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2563       for (unsigned i = 0;; ++i)
2564         if (Ops[i] == AddRec) {
2565           Ops[i] = NewRec;
2566           break;
2567         }
2568       return getMulExpr(Ops);
2569     }
2570 
2571     // Okay, if there weren't any loop invariants to be folded, check to see if
2572     // there are multiple AddRec's with the same loop induction variable being
2573     // multiplied together.  If so, we can fold them.
2574 
2575     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2576     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2577     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2578     //   ]]],+,...up to x=2n}.
2579     // Note that the arguments to choose() are always integers with values
2580     // known at compile time, never SCEV objects.
2581     //
2582     // The implementation avoids pointless extra computations when the two
2583     // addrec's are of different length (mathematically, it's equivalent to
2584     // an infinite stream of zeros on the right).
2585     bool OpsModified = false;
2586     for (unsigned OtherIdx = Idx+1;
2587          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2588          ++OtherIdx) {
2589       const SCEVAddRecExpr *OtherAddRec =
2590         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2591       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2592         continue;
2593 
2594       bool Overflow = false;
2595       Type *Ty = AddRec->getType();
2596       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2597       SmallVector<const SCEV*, 7> AddRecOps;
2598       for (int x = 0, xe = AddRec->getNumOperands() +
2599              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2600         const SCEV *Term = getZero(Ty);
2601         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2602           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2603           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2604                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2605                z < ze && !Overflow; ++z) {
2606             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2607             uint64_t Coeff;
2608             if (LargerThan64Bits)
2609               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2610             else
2611               Coeff = Coeff1*Coeff2;
2612             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2613             const SCEV *Term1 = AddRec->getOperand(y-z);
2614             const SCEV *Term2 = OtherAddRec->getOperand(z);
2615             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2616           }
2617         }
2618         AddRecOps.push_back(Term);
2619       }
2620       if (!Overflow) {
2621         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2622                                               SCEV::FlagAnyWrap);
2623         if (Ops.size() == 2) return NewAddRec;
2624         Ops[Idx] = NewAddRec;
2625         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2626         OpsModified = true;
2627         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2628         if (!AddRec)
2629           break;
2630       }
2631     }
2632     if (OpsModified)
2633       return getMulExpr(Ops);
2634 
2635     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2636     // next one.
2637   }
2638 
2639   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2640   // already have one, otherwise create a new one.
2641   FoldingSetNodeID ID;
2642   ID.AddInteger(scMulExpr);
2643   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2644     ID.AddPointer(Ops[i]);
2645   void *IP = nullptr;
2646   SCEVMulExpr *S =
2647     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2648   if (!S) {
2649     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2650     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2651     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2652                                         O, Ops.size());
2653     UniqueSCEVs.InsertNode(S, IP);
2654   }
2655   S->setNoWrapFlags(Flags);
2656   return S;
2657 }
2658 
2659 /// Get a canonical unsigned division expression, or something simpler if
2660 /// possible.
2661 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2662                                          const SCEV *RHS) {
2663   assert(getEffectiveSCEVType(LHS->getType()) ==
2664          getEffectiveSCEVType(RHS->getType()) &&
2665          "SCEVUDivExpr operand types don't match!");
2666 
2667   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2668     if (RHSC->getValue()->equalsInt(1))
2669       return LHS;                               // X udiv 1 --> x
2670     // If the denominator is zero, the result of the udiv is undefined. Don't
2671     // try to analyze it, because the resolution chosen here may differ from
2672     // the resolution chosen in other parts of the compiler.
2673     if (!RHSC->getValue()->isZero()) {
2674       // Determine if the division can be folded into the operands of
2675       // its operands.
2676       // TODO: Generalize this to non-constants by using known-bits information.
2677       Type *Ty = LHS->getType();
2678       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2679       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2680       // For non-power-of-two values, effectively round the value up to the
2681       // nearest power of two.
2682       if (!RHSC->getAPInt().isPowerOf2())
2683         ++MaxShiftAmt;
2684       IntegerType *ExtTy =
2685         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2686       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2687         if (const SCEVConstant *Step =
2688             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2689           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2690           const APInt &StepInt = Step->getAPInt();
2691           const APInt &DivInt = RHSC->getAPInt();
2692           if (!StepInt.urem(DivInt) &&
2693               getZeroExtendExpr(AR, ExtTy) ==
2694               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2695                             getZeroExtendExpr(Step, ExtTy),
2696                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2697             SmallVector<const SCEV *, 4> Operands;
2698             for (const SCEV *Op : AR->operands())
2699               Operands.push_back(getUDivExpr(Op, RHS));
2700             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2701           }
2702           /// Get a canonical UDivExpr for a recurrence.
2703           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2704           // We can currently only fold X%N if X is constant.
2705           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2706           if (StartC && !DivInt.urem(StepInt) &&
2707               getZeroExtendExpr(AR, ExtTy) ==
2708               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2709                             getZeroExtendExpr(Step, ExtTy),
2710                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2711             const APInt &StartInt = StartC->getAPInt();
2712             const APInt &StartRem = StartInt.urem(StepInt);
2713             if (StartRem != 0)
2714               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2715                                   AR->getLoop(), SCEV::FlagNW);
2716           }
2717         }
2718       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2719       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2720         SmallVector<const SCEV *, 4> Operands;
2721         for (const SCEV *Op : M->operands())
2722           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2723         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2724           // Find an operand that's safely divisible.
2725           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2726             const SCEV *Op = M->getOperand(i);
2727             const SCEV *Div = getUDivExpr(Op, RHSC);
2728             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2729               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2730                                                       M->op_end());
2731               Operands[i] = Div;
2732               return getMulExpr(Operands);
2733             }
2734           }
2735       }
2736       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2737       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2738         SmallVector<const SCEV *, 4> Operands;
2739         for (const SCEV *Op : A->operands())
2740           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2741         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2742           Operands.clear();
2743           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2744             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2745             if (isa<SCEVUDivExpr>(Op) ||
2746                 getMulExpr(Op, RHS) != A->getOperand(i))
2747               break;
2748             Operands.push_back(Op);
2749           }
2750           if (Operands.size() == A->getNumOperands())
2751             return getAddExpr(Operands);
2752         }
2753       }
2754 
2755       // Fold if both operands are constant.
2756       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2757         Constant *LHSCV = LHSC->getValue();
2758         Constant *RHSCV = RHSC->getValue();
2759         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2760                                                                    RHSCV)));
2761       }
2762     }
2763   }
2764 
2765   FoldingSetNodeID ID;
2766   ID.AddInteger(scUDivExpr);
2767   ID.AddPointer(LHS);
2768   ID.AddPointer(RHS);
2769   void *IP = nullptr;
2770   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2771   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2772                                              LHS, RHS);
2773   UniqueSCEVs.InsertNode(S, IP);
2774   return S;
2775 }
2776 
2777 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2778   APInt A = C1->getAPInt().abs();
2779   APInt B = C2->getAPInt().abs();
2780   uint32_t ABW = A.getBitWidth();
2781   uint32_t BBW = B.getBitWidth();
2782 
2783   if (ABW > BBW)
2784     B = B.zext(ABW);
2785   else if (ABW < BBW)
2786     A = A.zext(BBW);
2787 
2788   return APIntOps::GreatestCommonDivisor(A, B);
2789 }
2790 
2791 /// Get a canonical unsigned division expression, or something simpler if
2792 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2793 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2794 /// it's not exact because the udiv may be clearing bits.
2795 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2796                                               const SCEV *RHS) {
2797   // TODO: we could try to find factors in all sorts of things, but for now we
2798   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2799   // end of this file for inspiration.
2800 
2801   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2802   if (!Mul)
2803     return getUDivExpr(LHS, RHS);
2804 
2805   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2806     // If the mulexpr multiplies by a constant, then that constant must be the
2807     // first element of the mulexpr.
2808     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2809       if (LHSCst == RHSCst) {
2810         SmallVector<const SCEV *, 2> Operands;
2811         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2812         return getMulExpr(Operands);
2813       }
2814 
2815       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2816       // that there's a factor provided by one of the other terms. We need to
2817       // check.
2818       APInt Factor = gcd(LHSCst, RHSCst);
2819       if (!Factor.isIntN(1)) {
2820         LHSCst =
2821             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2822         RHSCst =
2823             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
2824         SmallVector<const SCEV *, 2> Operands;
2825         Operands.push_back(LHSCst);
2826         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2827         LHS = getMulExpr(Operands);
2828         RHS = RHSCst;
2829         Mul = dyn_cast<SCEVMulExpr>(LHS);
2830         if (!Mul)
2831           return getUDivExactExpr(LHS, RHS);
2832       }
2833     }
2834   }
2835 
2836   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2837     if (Mul->getOperand(i) == RHS) {
2838       SmallVector<const SCEV *, 2> Operands;
2839       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2840       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2841       return getMulExpr(Operands);
2842     }
2843   }
2844 
2845   return getUDivExpr(LHS, RHS);
2846 }
2847 
2848 /// Get an add recurrence expression for the specified loop.  Simplify the
2849 /// expression as much as possible.
2850 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2851                                            const Loop *L,
2852                                            SCEV::NoWrapFlags Flags) {
2853   SmallVector<const SCEV *, 4> Operands;
2854   Operands.push_back(Start);
2855   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2856     if (StepChrec->getLoop() == L) {
2857       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2858       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2859     }
2860 
2861   Operands.push_back(Step);
2862   return getAddRecExpr(Operands, L, Flags);
2863 }
2864 
2865 /// Get an add recurrence expression for the specified loop.  Simplify the
2866 /// expression as much as possible.
2867 const SCEV *
2868 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2869                                const Loop *L, SCEV::NoWrapFlags Flags) {
2870   if (Operands.size() == 1) return Operands[0];
2871 #ifndef NDEBUG
2872   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2873   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2874     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2875            "SCEVAddRecExpr operand types don't match!");
2876   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2877     assert(isLoopInvariant(Operands[i], L) &&
2878            "SCEVAddRecExpr operand is not loop-invariant!");
2879 #endif
2880 
2881   if (Operands.back()->isZero()) {
2882     Operands.pop_back();
2883     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
2884   }
2885 
2886   // It's tempting to want to call getMaxBackedgeTakenCount count here and
2887   // use that information to infer NUW and NSW flags. However, computing a
2888   // BE count requires calling getAddRecExpr, so we may not yet have a
2889   // meaningful BE count at this point (and if we don't, we'd be stuck
2890   // with a SCEVCouldNotCompute as the cached BE count).
2891 
2892   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
2893 
2894   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2895   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2896     const Loop *NestedLoop = NestedAR->getLoop();
2897     if (L->contains(NestedLoop)
2898             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2899             : (!NestedLoop->contains(L) &&
2900                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
2901       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2902                                                   NestedAR->op_end());
2903       Operands[0] = NestedAR->getStart();
2904       // AddRecs require their operands be loop-invariant with respect to their
2905       // loops. Don't perform this transformation if it would break this
2906       // requirement.
2907       bool AllInvariant = all_of(
2908           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
2909 
2910       if (AllInvariant) {
2911         // Create a recurrence for the outer loop with the same step size.
2912         //
2913         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2914         // inner recurrence has the same property.
2915         SCEV::NoWrapFlags OuterFlags =
2916           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2917 
2918         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2919         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2920           return isLoopInvariant(Op, NestedLoop);
2921         });
2922 
2923         if (AllInvariant) {
2924           // Ok, both add recurrences are valid after the transformation.
2925           //
2926           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2927           // the outer recurrence has the same property.
2928           SCEV::NoWrapFlags InnerFlags =
2929             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2930           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2931         }
2932       }
2933       // Reset Operands to its original state.
2934       Operands[0] = NestedAR;
2935     }
2936   }
2937 
2938   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
2939   // already have one, otherwise create a new one.
2940   FoldingSetNodeID ID;
2941   ID.AddInteger(scAddRecExpr);
2942   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2943     ID.AddPointer(Operands[i]);
2944   ID.AddPointer(L);
2945   void *IP = nullptr;
2946   SCEVAddRecExpr *S =
2947     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2948   if (!S) {
2949     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2950     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2951     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2952                                            O, Operands.size(), L);
2953     UniqueSCEVs.InsertNode(S, IP);
2954   }
2955   S->setNoWrapFlags(Flags);
2956   return S;
2957 }
2958 
2959 const SCEV *
2960 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2961                             const SmallVectorImpl<const SCEV *> &IndexExprs,
2962                             bool InBounds) {
2963   // getSCEV(Base)->getType() has the same address space as Base->getType()
2964   // because SCEV::getType() preserves the address space.
2965   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2966   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2967   // instruction to its SCEV, because the Instruction may be guarded by control
2968   // flow and the no-overflow bits may not be valid for the expression in any
2969   // context. This can be fixed similarly to how these flags are handled for
2970   // adds.
2971   SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2972 
2973   const SCEV *TotalOffset = getZero(IntPtrTy);
2974   // The address space is unimportant. The first thing we do on CurTy is getting
2975   // its element type.
2976   Type *CurTy = PointerType::getUnqual(PointeeType);
2977   for (const SCEV *IndexExpr : IndexExprs) {
2978     // Compute the (potentially symbolic) offset in bytes for this index.
2979     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2980       // For a struct, add the member offset.
2981       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2982       unsigned FieldNo = Index->getZExtValue();
2983       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2984 
2985       // Add the field offset to the running total offset.
2986       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2987 
2988       // Update CurTy to the type of the field at Index.
2989       CurTy = STy->getTypeAtIndex(Index);
2990     } else {
2991       // Update CurTy to its element type.
2992       CurTy = cast<SequentialType>(CurTy)->getElementType();
2993       // For an array, add the element offset, explicitly scaled.
2994       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
2995       // Getelementptr indices are signed.
2996       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
2997 
2998       // Multiply the index by the element size to compute the element offset.
2999       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3000 
3001       // Add the element offset to the running total offset.
3002       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3003     }
3004   }
3005 
3006   // Add the total offset from all the GEP indices to the base.
3007   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3008 }
3009 
3010 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3011                                          const SCEV *RHS) {
3012   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3013   return getSMaxExpr(Ops);
3014 }
3015 
3016 const SCEV *
3017 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3018   assert(!Ops.empty() && "Cannot get empty smax!");
3019   if (Ops.size() == 1) return Ops[0];
3020 #ifndef NDEBUG
3021   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3022   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3023     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3024            "SCEVSMaxExpr operand types don't match!");
3025 #endif
3026 
3027   // Sort by complexity, this groups all similar expression types together.
3028   GroupByComplexity(Ops, &LI);
3029 
3030   // If there are any constants, fold them together.
3031   unsigned Idx = 0;
3032   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3033     ++Idx;
3034     assert(Idx < Ops.size());
3035     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3036       // We found two constants, fold them together!
3037       ConstantInt *Fold = ConstantInt::get(
3038           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3039       Ops[0] = getConstant(Fold);
3040       Ops.erase(Ops.begin()+1);  // Erase the folded element
3041       if (Ops.size() == 1) return Ops[0];
3042       LHSC = cast<SCEVConstant>(Ops[0]);
3043     }
3044 
3045     // If we are left with a constant minimum-int, strip it off.
3046     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3047       Ops.erase(Ops.begin());
3048       --Idx;
3049     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3050       // If we have an smax with a constant maximum-int, it will always be
3051       // maximum-int.
3052       return Ops[0];
3053     }
3054 
3055     if (Ops.size() == 1) return Ops[0];
3056   }
3057 
3058   // Find the first SMax
3059   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3060     ++Idx;
3061 
3062   // Check to see if one of the operands is an SMax. If so, expand its operands
3063   // onto our operand list, and recurse to simplify.
3064   if (Idx < Ops.size()) {
3065     bool DeletedSMax = false;
3066     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3067       Ops.erase(Ops.begin()+Idx);
3068       Ops.append(SMax->op_begin(), SMax->op_end());
3069       DeletedSMax = true;
3070     }
3071 
3072     if (DeletedSMax)
3073       return getSMaxExpr(Ops);
3074   }
3075 
3076   // Okay, check to see if the same value occurs in the operand list twice.  If
3077   // so, delete one.  Since we sorted the list, these values are required to
3078   // be adjacent.
3079   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3080     //  X smax Y smax Y  -->  X smax Y
3081     //  X smax Y         -->  X, if X is always greater than Y
3082     if (Ops[i] == Ops[i+1] ||
3083         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3084       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3085       --i; --e;
3086     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3087       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3088       --i; --e;
3089     }
3090 
3091   if (Ops.size() == 1) return Ops[0];
3092 
3093   assert(!Ops.empty() && "Reduced smax down to nothing!");
3094 
3095   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3096   // already have one, otherwise create a new one.
3097   FoldingSetNodeID ID;
3098   ID.AddInteger(scSMaxExpr);
3099   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3100     ID.AddPointer(Ops[i]);
3101   void *IP = nullptr;
3102   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3103   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3104   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3105   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3106                                              O, Ops.size());
3107   UniqueSCEVs.InsertNode(S, IP);
3108   return S;
3109 }
3110 
3111 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3112                                          const SCEV *RHS) {
3113   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3114   return getUMaxExpr(Ops);
3115 }
3116 
3117 const SCEV *
3118 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3119   assert(!Ops.empty() && "Cannot get empty umax!");
3120   if (Ops.size() == 1) return Ops[0];
3121 #ifndef NDEBUG
3122   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3123   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3124     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3125            "SCEVUMaxExpr operand types don't match!");
3126 #endif
3127 
3128   // Sort by complexity, this groups all similar expression types together.
3129   GroupByComplexity(Ops, &LI);
3130 
3131   // If there are any constants, fold them together.
3132   unsigned Idx = 0;
3133   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3134     ++Idx;
3135     assert(Idx < Ops.size());
3136     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3137       // We found two constants, fold them together!
3138       ConstantInt *Fold = ConstantInt::get(
3139           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3140       Ops[0] = getConstant(Fold);
3141       Ops.erase(Ops.begin()+1);  // Erase the folded element
3142       if (Ops.size() == 1) return Ops[0];
3143       LHSC = cast<SCEVConstant>(Ops[0]);
3144     }
3145 
3146     // If we are left with a constant minimum-int, strip it off.
3147     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3148       Ops.erase(Ops.begin());
3149       --Idx;
3150     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3151       // If we have an umax with a constant maximum-int, it will always be
3152       // maximum-int.
3153       return Ops[0];
3154     }
3155 
3156     if (Ops.size() == 1) return Ops[0];
3157   }
3158 
3159   // Find the first UMax
3160   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3161     ++Idx;
3162 
3163   // Check to see if one of the operands is a UMax. If so, expand its operands
3164   // onto our operand list, and recurse to simplify.
3165   if (Idx < Ops.size()) {
3166     bool DeletedUMax = false;
3167     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3168       Ops.erase(Ops.begin()+Idx);
3169       Ops.append(UMax->op_begin(), UMax->op_end());
3170       DeletedUMax = true;
3171     }
3172 
3173     if (DeletedUMax)
3174       return getUMaxExpr(Ops);
3175   }
3176 
3177   // Okay, check to see if the same value occurs in the operand list twice.  If
3178   // so, delete one.  Since we sorted the list, these values are required to
3179   // be adjacent.
3180   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3181     //  X umax Y umax Y  -->  X umax Y
3182     //  X umax Y         -->  X, if X is always greater than Y
3183     if (Ops[i] == Ops[i+1] ||
3184         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3185       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3186       --i; --e;
3187     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3188       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3189       --i; --e;
3190     }
3191 
3192   if (Ops.size() == 1) return Ops[0];
3193 
3194   assert(!Ops.empty() && "Reduced umax down to nothing!");
3195 
3196   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3197   // already have one, otherwise create a new one.
3198   FoldingSetNodeID ID;
3199   ID.AddInteger(scUMaxExpr);
3200   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3201     ID.AddPointer(Ops[i]);
3202   void *IP = nullptr;
3203   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3204   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3205   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3206   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3207                                              O, Ops.size());
3208   UniqueSCEVs.InsertNode(S, IP);
3209   return S;
3210 }
3211 
3212 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3213                                          const SCEV *RHS) {
3214   // ~smax(~x, ~y) == smin(x, y).
3215   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3216 }
3217 
3218 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3219                                          const SCEV *RHS) {
3220   // ~umax(~x, ~y) == umin(x, y)
3221   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3222 }
3223 
3224 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3225   // We can bypass creating a target-independent
3226   // constant expression and then folding it back into a ConstantInt.
3227   // This is just a compile-time optimization.
3228   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3229 }
3230 
3231 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3232                                              StructType *STy,
3233                                              unsigned FieldNo) {
3234   // We can bypass creating a target-independent
3235   // constant expression and then folding it back into a ConstantInt.
3236   // This is just a compile-time optimization.
3237   return getConstant(
3238       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3239 }
3240 
3241 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3242   // Don't attempt to do anything other than create a SCEVUnknown object
3243   // here.  createSCEV only calls getUnknown after checking for all other
3244   // interesting possibilities, and any other code that calls getUnknown
3245   // is doing so in order to hide a value from SCEV canonicalization.
3246 
3247   FoldingSetNodeID ID;
3248   ID.AddInteger(scUnknown);
3249   ID.AddPointer(V);
3250   void *IP = nullptr;
3251   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3252     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3253            "Stale SCEVUnknown in uniquing map!");
3254     return S;
3255   }
3256   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3257                                             FirstUnknown);
3258   FirstUnknown = cast<SCEVUnknown>(S);
3259   UniqueSCEVs.InsertNode(S, IP);
3260   return S;
3261 }
3262 
3263 //===----------------------------------------------------------------------===//
3264 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3265 //
3266 
3267 /// Test if values of the given type are analyzable within the SCEV
3268 /// framework. This primarily includes integer types, and it can optionally
3269 /// include pointer types if the ScalarEvolution class has access to
3270 /// target-specific information.
3271 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3272   // Integers and pointers are always SCEVable.
3273   return Ty->isIntegerTy() || Ty->isPointerTy();
3274 }
3275 
3276 /// Return the size in bits of the specified type, for which isSCEVable must
3277 /// return true.
3278 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3279   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3280   return getDataLayout().getTypeSizeInBits(Ty);
3281 }
3282 
3283 /// Return a type with the same bitwidth as the given type and which represents
3284 /// how SCEV will treat the given type, for which isSCEVable must return
3285 /// true. For pointer types, 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 getDataLayout().getIntPtrType(Ty);
3295 }
3296 
3297 const SCEV *ScalarEvolution::getCouldNotCompute() {
3298   return CouldNotCompute.get();
3299 }
3300 
3301 
3302 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3303   // Helper class working with SCEVTraversal to figure out if a SCEV contains
3304   // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3305   // is set iff if find such SCEVUnknown.
3306   //
3307   struct FindInvalidSCEVUnknown {
3308     bool FindOne;
3309     FindInvalidSCEVUnknown() { FindOne = false; }
3310     bool follow(const SCEV *S) {
3311       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3312       case scConstant:
3313         return false;
3314       case scUnknown:
3315         if (!cast<SCEVUnknown>(S)->getValue())
3316           FindOne = true;
3317         return false;
3318       default:
3319         return true;
3320       }
3321     }
3322     bool isDone() const { return FindOne; }
3323   };
3324 
3325   FindInvalidSCEVUnknown F;
3326   SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3327   ST.visitAll(S);
3328 
3329   return !F.FindOne;
3330 }
3331 
3332 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3333   // Helper class working with SCEVTraversal to figure out if a SCEV contains a
3334   // sub SCEV of scAddRecExpr type.  FindInvalidSCEVUnknown::FoundOne is set iff
3335   // if such sub scAddRecExpr type SCEV is found.
3336   struct FindAddRecurrence {
3337     bool FoundOne;
3338     FindAddRecurrence() : FoundOne(false) {}
3339 
3340     bool follow(const SCEV *S) {
3341       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3342       case scAddRecExpr:
3343         FoundOne = true;
3344       case scConstant:
3345       case scUnknown:
3346       case scCouldNotCompute:
3347         return false;
3348       default:
3349         return true;
3350       }
3351     }
3352     bool isDone() const { return FoundOne; }
3353   };
3354 
3355   HasRecMapType::iterator I = HasRecMap.find(S);
3356   if (I != HasRecMap.end())
3357     return I->second;
3358 
3359   FindAddRecurrence F;
3360   SCEVTraversal<FindAddRecurrence> ST(F);
3361   ST.visitAll(S);
3362   HasRecMap.insert({S, F.FoundOne});
3363   return F.FoundOne;
3364 }
3365 
3366 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3367 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3368 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3369 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3370   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3371   if (!Add)
3372     return {S, nullptr};
3373 
3374   if (Add->getNumOperands() != 2)
3375     return {S, nullptr};
3376 
3377   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3378   if (!ConstOp)
3379     return {S, nullptr};
3380 
3381   return {Add->getOperand(1), ConstOp->getValue()};
3382 }
3383 
3384 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3385 /// by the value and offset from any ValueOffsetPair in the set.
3386 SetVector<ScalarEvolution::ValueOffsetPair> *
3387 ScalarEvolution::getSCEVValues(const SCEV *S) {
3388   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3389   if (SI == ExprValueMap.end())
3390     return nullptr;
3391 #ifndef NDEBUG
3392   if (VerifySCEVMap) {
3393     // Check there is no dangling Value in the set returned.
3394     for (const auto &VE : SI->second)
3395       assert(ValueExprMap.count(VE.first));
3396   }
3397 #endif
3398   return &SI->second;
3399 }
3400 
3401 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3402 /// cannot be used separately. eraseValueFromMap should be used to remove
3403 /// V from ValueExprMap and ExprValueMap at the same time.
3404 void ScalarEvolution::eraseValueFromMap(Value *V) {
3405   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3406   if (I != ValueExprMap.end()) {
3407     const SCEV *S = I->second;
3408     // Remove {V, 0} from the set of ExprValueMap[S]
3409     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3410       SV->remove({V, nullptr});
3411 
3412     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3413     const SCEV *Stripped;
3414     ConstantInt *Offset;
3415     std::tie(Stripped, Offset) = splitAddExpr(S);
3416     if (Offset != nullptr) {
3417       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3418         SV->remove({V, Offset});
3419     }
3420     ValueExprMap.erase(V);
3421   }
3422 }
3423 
3424 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3425 /// create a new one.
3426 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3427   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3428 
3429   const SCEV *S = getExistingSCEV(V);
3430   if (S == nullptr) {
3431     S = createSCEV(V);
3432     // During PHI resolution, it is possible to create two SCEVs for the same
3433     // V, so it is needed to double check whether V->S is inserted into
3434     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3435     std::pair<ValueExprMapType::iterator, bool> Pair =
3436         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3437     if (Pair.second) {
3438       ExprValueMap[S].insert({V, nullptr});
3439 
3440       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3441       // ExprValueMap.
3442       const SCEV *Stripped = S;
3443       ConstantInt *Offset = nullptr;
3444       std::tie(Stripped, Offset) = splitAddExpr(S);
3445       // If stripped is SCEVUnknown, don't bother to save
3446       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3447       // increase the complexity of the expansion code.
3448       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3449       // because it may generate add/sub instead of GEP in SCEV expansion.
3450       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3451           !isa<GetElementPtrInst>(V))
3452         ExprValueMap[Stripped].insert({V, Offset});
3453     }
3454   }
3455   return S;
3456 }
3457 
3458 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3459   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3460 
3461   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3462   if (I != ValueExprMap.end()) {
3463     const SCEV *S = I->second;
3464     if (checkValidity(S))
3465       return S;
3466     eraseValueFromMap(V);
3467     forgetMemoizedResults(S);
3468   }
3469   return nullptr;
3470 }
3471 
3472 /// Return a SCEV corresponding to -V = -1*V
3473 ///
3474 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3475                                              SCEV::NoWrapFlags Flags) {
3476   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3477     return getConstant(
3478                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3479 
3480   Type *Ty = V->getType();
3481   Ty = getEffectiveSCEVType(Ty);
3482   return getMulExpr(
3483       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3484 }
3485 
3486 /// Return a SCEV corresponding to ~V = -1-V
3487 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3488   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3489     return getConstant(
3490                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3491 
3492   Type *Ty = V->getType();
3493   Ty = getEffectiveSCEVType(Ty);
3494   const SCEV *AllOnes =
3495                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3496   return getMinusSCEV(AllOnes, V);
3497 }
3498 
3499 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3500                                           SCEV::NoWrapFlags Flags) {
3501   // Fast path: X - X --> 0.
3502   if (LHS == RHS)
3503     return getZero(LHS->getType());
3504 
3505   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3506   // makes it so that we cannot make much use of NUW.
3507   auto AddFlags = SCEV::FlagAnyWrap;
3508   const bool RHSIsNotMinSigned =
3509       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3510   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3511     // Let M be the minimum representable signed value. Then (-1)*RHS
3512     // signed-wraps if and only if RHS is M. That can happen even for
3513     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3514     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3515     // (-1)*RHS, we need to prove that RHS != M.
3516     //
3517     // If LHS is non-negative and we know that LHS - RHS does not
3518     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3519     // either by proving that RHS > M or that LHS >= 0.
3520     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3521       AddFlags = SCEV::FlagNSW;
3522     }
3523   }
3524 
3525   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3526   // RHS is NSW and LHS >= 0.
3527   //
3528   // The difficulty here is that the NSW flag may have been proven
3529   // relative to a loop that is to be found in a recurrence in LHS and
3530   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3531   // larger scope than intended.
3532   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3533 
3534   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3535 }
3536 
3537 const SCEV *
3538 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3539   Type *SrcTy = V->getType();
3540   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3541          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3542          "Cannot truncate or zero extend with non-integer arguments!");
3543   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3544     return V;  // No conversion
3545   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3546     return getTruncateExpr(V, Ty);
3547   return getZeroExtendExpr(V, Ty);
3548 }
3549 
3550 const SCEV *
3551 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3552                                          Type *Ty) {
3553   Type *SrcTy = V->getType();
3554   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3555          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3556          "Cannot truncate or zero extend with non-integer arguments!");
3557   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3558     return V;  // No conversion
3559   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3560     return getTruncateExpr(V, Ty);
3561   return getSignExtendExpr(V, Ty);
3562 }
3563 
3564 const SCEV *
3565 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3566   Type *SrcTy = V->getType();
3567   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3568          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3569          "Cannot noop or zero extend with non-integer arguments!");
3570   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3571          "getNoopOrZeroExtend cannot truncate!");
3572   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3573     return V;  // No conversion
3574   return getZeroExtendExpr(V, Ty);
3575 }
3576 
3577 const SCEV *
3578 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3579   Type *SrcTy = V->getType();
3580   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3581          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3582          "Cannot noop or sign extend with non-integer arguments!");
3583   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3584          "getNoopOrSignExtend cannot truncate!");
3585   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3586     return V;  // No conversion
3587   return getSignExtendExpr(V, Ty);
3588 }
3589 
3590 const SCEV *
3591 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3592   Type *SrcTy = V->getType();
3593   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3594          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3595          "Cannot noop or any extend with non-integer arguments!");
3596   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3597          "getNoopOrAnyExtend cannot truncate!");
3598   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3599     return V;  // No conversion
3600   return getAnyExtendExpr(V, Ty);
3601 }
3602 
3603 const SCEV *
3604 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3605   Type *SrcTy = V->getType();
3606   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3607          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3608          "Cannot truncate or noop with non-integer arguments!");
3609   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3610          "getTruncateOrNoop cannot extend!");
3611   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3612     return V;  // No conversion
3613   return getTruncateExpr(V, Ty);
3614 }
3615 
3616 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3617                                                         const SCEV *RHS) {
3618   const SCEV *PromotedLHS = LHS;
3619   const SCEV *PromotedRHS = RHS;
3620 
3621   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3622     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3623   else
3624     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3625 
3626   return getUMaxExpr(PromotedLHS, PromotedRHS);
3627 }
3628 
3629 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3630                                                         const SCEV *RHS) {
3631   const SCEV *PromotedLHS = LHS;
3632   const SCEV *PromotedRHS = RHS;
3633 
3634   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3635     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3636   else
3637     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3638 
3639   return getUMinExpr(PromotedLHS, PromotedRHS);
3640 }
3641 
3642 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3643   // A pointer operand may evaluate to a nonpointer expression, such as null.
3644   if (!V->getType()->isPointerTy())
3645     return V;
3646 
3647   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3648     return getPointerBase(Cast->getOperand());
3649   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3650     const SCEV *PtrOp = nullptr;
3651     for (const SCEV *NAryOp : NAry->operands()) {
3652       if (NAryOp->getType()->isPointerTy()) {
3653         // Cannot find the base of an expression with multiple pointer operands.
3654         if (PtrOp)
3655           return V;
3656         PtrOp = NAryOp;
3657       }
3658     }
3659     if (!PtrOp)
3660       return V;
3661     return getPointerBase(PtrOp);
3662   }
3663   return V;
3664 }
3665 
3666 /// Push users of the given Instruction onto the given Worklist.
3667 static void
3668 PushDefUseChildren(Instruction *I,
3669                    SmallVectorImpl<Instruction *> &Worklist) {
3670   // Push the def-use children onto the Worklist stack.
3671   for (User *U : I->users())
3672     Worklist.push_back(cast<Instruction>(U));
3673 }
3674 
3675 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3676   SmallVector<Instruction *, 16> Worklist;
3677   PushDefUseChildren(PN, Worklist);
3678 
3679   SmallPtrSet<Instruction *, 8> Visited;
3680   Visited.insert(PN);
3681   while (!Worklist.empty()) {
3682     Instruction *I = Worklist.pop_back_val();
3683     if (!Visited.insert(I).second)
3684       continue;
3685 
3686     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3687     if (It != ValueExprMap.end()) {
3688       const SCEV *Old = It->second;
3689 
3690       // Short-circuit the def-use traversal if the symbolic name
3691       // ceases to appear in expressions.
3692       if (Old != SymName && !hasOperand(Old, SymName))
3693         continue;
3694 
3695       // SCEVUnknown for a PHI either means that it has an unrecognized
3696       // structure, it's a PHI that's in the progress of being computed
3697       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3698       // additional loop trip count information isn't going to change anything.
3699       // In the second case, createNodeForPHI will perform the necessary
3700       // updates on its own when it gets to that point. In the third, we do
3701       // want to forget the SCEVUnknown.
3702       if (!isa<PHINode>(I) ||
3703           !isa<SCEVUnknown>(Old) ||
3704           (I != PN && Old == SymName)) {
3705         eraseValueFromMap(It->first);
3706         forgetMemoizedResults(Old);
3707       }
3708     }
3709 
3710     PushDefUseChildren(I, Worklist);
3711   }
3712 }
3713 
3714 namespace {
3715 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3716 public:
3717   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3718                              ScalarEvolution &SE) {
3719     SCEVInitRewriter Rewriter(L, SE);
3720     const SCEV *Result = Rewriter.visit(S);
3721     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3722   }
3723 
3724   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3725       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3726 
3727   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3728     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3729       Valid = false;
3730     return Expr;
3731   }
3732 
3733   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3734     // Only allow AddRecExprs for this loop.
3735     if (Expr->getLoop() == L)
3736       return Expr->getStart();
3737     Valid = false;
3738     return Expr;
3739   }
3740 
3741   bool isValid() { return Valid; }
3742 
3743 private:
3744   const Loop *L;
3745   bool Valid;
3746 };
3747 
3748 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3749 public:
3750   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3751                              ScalarEvolution &SE) {
3752     SCEVShiftRewriter Rewriter(L, SE);
3753     const SCEV *Result = Rewriter.visit(S);
3754     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3755   }
3756 
3757   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3758       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3759 
3760   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3761     // Only allow AddRecExprs for this loop.
3762     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3763       Valid = false;
3764     return Expr;
3765   }
3766 
3767   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3768     if (Expr->getLoop() == L && Expr->isAffine())
3769       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3770     Valid = false;
3771     return Expr;
3772   }
3773   bool isValid() { return Valid; }
3774 
3775 private:
3776   const Loop *L;
3777   bool Valid;
3778 };
3779 } // end anonymous namespace
3780 
3781 SCEV::NoWrapFlags
3782 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3783   if (!AR->isAffine())
3784     return SCEV::FlagAnyWrap;
3785 
3786   typedef OverflowingBinaryOperator OBO;
3787   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3788 
3789   if (!AR->hasNoSignedWrap()) {
3790     ConstantRange AddRecRange = getSignedRange(AR);
3791     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3792 
3793     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3794         Instruction::Add, IncRange, OBO::NoSignedWrap);
3795     if (NSWRegion.contains(AddRecRange))
3796       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3797   }
3798 
3799   if (!AR->hasNoUnsignedWrap()) {
3800     ConstantRange AddRecRange = getUnsignedRange(AR);
3801     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3802 
3803     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3804         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3805     if (NUWRegion.contains(AddRecRange))
3806       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3807   }
3808 
3809   return Result;
3810 }
3811 
3812 namespace {
3813 /// Represents an abstract binary operation.  This may exist as a
3814 /// normal instruction or constant expression, or may have been
3815 /// derived from an expression tree.
3816 struct BinaryOp {
3817   unsigned Opcode;
3818   Value *LHS;
3819   Value *RHS;
3820   bool IsNSW;
3821   bool IsNUW;
3822 
3823   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3824   /// constant expression.
3825   Operator *Op;
3826 
3827   explicit BinaryOp(Operator *Op)
3828       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3829         IsNSW(false), IsNUW(false), Op(Op) {
3830     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3831       IsNSW = OBO->hasNoSignedWrap();
3832       IsNUW = OBO->hasNoUnsignedWrap();
3833     }
3834   }
3835 
3836   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3837                     bool IsNUW = false)
3838       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3839         Op(nullptr) {}
3840 };
3841 }
3842 
3843 
3844 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3845 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3846   auto *Op = dyn_cast<Operator>(V);
3847   if (!Op)
3848     return None;
3849 
3850   // Implementation detail: all the cleverness here should happen without
3851   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3852   // SCEV expressions when possible, and we should not break that.
3853 
3854   switch (Op->getOpcode()) {
3855   case Instruction::Add:
3856   case Instruction::Sub:
3857   case Instruction::Mul:
3858   case Instruction::UDiv:
3859   case Instruction::And:
3860   case Instruction::Or:
3861   case Instruction::AShr:
3862   case Instruction::Shl:
3863     return BinaryOp(Op);
3864 
3865   case Instruction::Xor:
3866     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3867       // If the RHS of the xor is a signbit, then this is just an add.
3868       // Instcombine turns add of signbit into xor as a strength reduction step.
3869       if (RHSC->getValue().isSignBit())
3870         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3871     return BinaryOp(Op);
3872 
3873   case Instruction::LShr:
3874     // Turn logical shift right of a constant into a unsigned divide.
3875     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3876       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3877 
3878       // If the shift count is not less than the bitwidth, the result of
3879       // the shift is undefined. Don't try to analyze it, because the
3880       // resolution chosen here may differ from the resolution chosen in
3881       // other parts of the compiler.
3882       if (SA->getValue().ult(BitWidth)) {
3883         Constant *X =
3884             ConstantInt::get(SA->getContext(),
3885                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3886         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3887       }
3888     }
3889     return BinaryOp(Op);
3890 
3891   case Instruction::ExtractValue: {
3892     auto *EVI = cast<ExtractValueInst>(Op);
3893     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3894       break;
3895 
3896     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3897     if (!CI)
3898       break;
3899 
3900     if (auto *F = CI->getCalledFunction())
3901       switch (F->getIntrinsicID()) {
3902       case Intrinsic::sadd_with_overflow:
3903       case Intrinsic::uadd_with_overflow: {
3904         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3905           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3906                           CI->getArgOperand(1));
3907 
3908         // Now that we know that all uses of the arithmetic-result component of
3909         // CI are guarded by the overflow check, we can go ahead and pretend
3910         // that the arithmetic is non-overflowing.
3911         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3912           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3913                           CI->getArgOperand(1), /* IsNSW = */ true,
3914                           /* IsNUW = */ false);
3915         else
3916           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3917                           CI->getArgOperand(1), /* IsNSW = */ false,
3918                           /* IsNUW*/ true);
3919       }
3920 
3921       case Intrinsic::ssub_with_overflow:
3922       case Intrinsic::usub_with_overflow:
3923         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3924                         CI->getArgOperand(1));
3925 
3926       case Intrinsic::smul_with_overflow:
3927       case Intrinsic::umul_with_overflow:
3928         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3929                         CI->getArgOperand(1));
3930       default:
3931         break;
3932       }
3933   }
3934 
3935   default:
3936     break;
3937   }
3938 
3939   return None;
3940 }
3941 
3942 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3943   const Loop *L = LI.getLoopFor(PN->getParent());
3944   if (!L || L->getHeader() != PN->getParent())
3945     return nullptr;
3946 
3947   // The loop may have multiple entrances or multiple exits; we can analyze
3948   // this phi as an addrec if it has a unique entry value and a unique
3949   // backedge value.
3950   Value *BEValueV = nullptr, *StartValueV = nullptr;
3951   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3952     Value *V = PN->getIncomingValue(i);
3953     if (L->contains(PN->getIncomingBlock(i))) {
3954       if (!BEValueV) {
3955         BEValueV = V;
3956       } else if (BEValueV != V) {
3957         BEValueV = nullptr;
3958         break;
3959       }
3960     } else if (!StartValueV) {
3961       StartValueV = V;
3962     } else if (StartValueV != V) {
3963       StartValueV = nullptr;
3964       break;
3965     }
3966   }
3967   if (BEValueV && StartValueV) {
3968     // While we are analyzing this PHI node, handle its value symbolically.
3969     const SCEV *SymbolicName = getUnknown(PN);
3970     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3971            "PHI node already processed?");
3972     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
3973 
3974     // Using this symbolic name for the PHI, analyze the value coming around
3975     // the back-edge.
3976     const SCEV *BEValue = getSCEV(BEValueV);
3977 
3978     // NOTE: If BEValue is loop invariant, we know that the PHI node just
3979     // has a special value for the first iteration of the loop.
3980 
3981     // If the value coming around the backedge is an add with the symbolic
3982     // value we just inserted, then we found a simple induction variable!
3983     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3984       // If there is a single occurrence of the symbolic value, replace it
3985       // with a recurrence.
3986       unsigned FoundIndex = Add->getNumOperands();
3987       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3988         if (Add->getOperand(i) == SymbolicName)
3989           if (FoundIndex == e) {
3990             FoundIndex = i;
3991             break;
3992           }
3993 
3994       if (FoundIndex != Add->getNumOperands()) {
3995         // Create an add with everything but the specified operand.
3996         SmallVector<const SCEV *, 8> Ops;
3997         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3998           if (i != FoundIndex)
3999             Ops.push_back(Add->getOperand(i));
4000         const SCEV *Accum = getAddExpr(Ops);
4001 
4002         // This is not a valid addrec if the step amount is varying each
4003         // loop iteration, but is not itself an addrec in this loop.
4004         if (isLoopInvariant(Accum, L) ||
4005             (isa<SCEVAddRecExpr>(Accum) &&
4006              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4007           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4008 
4009           if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4010             if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4011               if (BO->IsNUW)
4012                 Flags = setFlags(Flags, SCEV::FlagNUW);
4013               if (BO->IsNSW)
4014                 Flags = setFlags(Flags, SCEV::FlagNSW);
4015             }
4016           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4017             // If the increment is an inbounds GEP, then we know the address
4018             // space cannot be wrapped around. We cannot make any guarantee
4019             // about signed or unsigned overflow because pointers are
4020             // unsigned but we may have a negative index from the base
4021             // pointer. We can guarantee that no unsigned wrap occurs if the
4022             // indices form a positive value.
4023             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4024               Flags = setFlags(Flags, SCEV::FlagNW);
4025 
4026               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4027               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4028                 Flags = setFlags(Flags, SCEV::FlagNUW);
4029             }
4030 
4031             // We cannot transfer nuw and nsw flags from subtraction
4032             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4033             // for instance.
4034           }
4035 
4036           const SCEV *StartVal = getSCEV(StartValueV);
4037           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4038 
4039           // Okay, for the entire analysis of this edge we assumed the PHI
4040           // to be symbolic.  We now need to go back and purge all of the
4041           // entries for the scalars that use the symbolic expression.
4042           forgetSymbolicName(PN, SymbolicName);
4043           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4044 
4045           // We can add Flags to the post-inc expression only if we
4046           // know that it us *undefined behavior* for BEValueV to
4047           // overflow.
4048           if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4049             if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4050               (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4051 
4052           return PHISCEV;
4053         }
4054       }
4055     } else {
4056       // Otherwise, this could be a loop like this:
4057       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4058       // In this case, j = {1,+,1}  and BEValue is j.
4059       // Because the other in-value of i (0) fits the evolution of BEValue
4060       // i really is an addrec evolution.
4061       //
4062       // We can generalize this saying that i is the shifted value of BEValue
4063       // by one iteration:
4064       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4065       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4066       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4067       if (Shifted != getCouldNotCompute() &&
4068           Start != getCouldNotCompute()) {
4069         const SCEV *StartVal = getSCEV(StartValueV);
4070         if (Start == StartVal) {
4071           // Okay, for the entire analysis of this edge we assumed the PHI
4072           // to be symbolic.  We now need to go back and purge all of the
4073           // entries for the scalars that use the symbolic expression.
4074           forgetSymbolicName(PN, SymbolicName);
4075           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4076           return Shifted;
4077         }
4078       }
4079     }
4080 
4081     // Remove the temporary PHI node SCEV that has been inserted while intending
4082     // to create an AddRecExpr for this PHI node. We can not keep this temporary
4083     // as it will prevent later (possibly simpler) SCEV expressions to be added
4084     // to the ValueExprMap.
4085     eraseValueFromMap(PN);
4086   }
4087 
4088   return nullptr;
4089 }
4090 
4091 // Checks if the SCEV S is available at BB.  S is considered available at BB
4092 // if S can be materialized at BB without introducing a fault.
4093 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4094                                BasicBlock *BB) {
4095   struct CheckAvailable {
4096     bool TraversalDone = false;
4097     bool Available = true;
4098 
4099     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4100     BasicBlock *BB = nullptr;
4101     DominatorTree &DT;
4102 
4103     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4104       : L(L), BB(BB), DT(DT) {}
4105 
4106     bool setUnavailable() {
4107       TraversalDone = true;
4108       Available = false;
4109       return false;
4110     }
4111 
4112     bool follow(const SCEV *S) {
4113       switch (S->getSCEVType()) {
4114       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4115       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4116         // These expressions are available if their operand(s) is/are.
4117         return true;
4118 
4119       case scAddRecExpr: {
4120         // We allow add recurrences that are on the loop BB is in, or some
4121         // outer loop.  This guarantees availability because the value of the
4122         // add recurrence at BB is simply the "current" value of the induction
4123         // variable.  We can relax this in the future; for instance an add
4124         // recurrence on a sibling dominating loop is also available at BB.
4125         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4126         if (L && (ARLoop == L || ARLoop->contains(L)))
4127           return true;
4128 
4129         return setUnavailable();
4130       }
4131 
4132       case scUnknown: {
4133         // For SCEVUnknown, we check for simple dominance.
4134         const auto *SU = cast<SCEVUnknown>(S);
4135         Value *V = SU->getValue();
4136 
4137         if (isa<Argument>(V))
4138           return false;
4139 
4140         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4141           return false;
4142 
4143         return setUnavailable();
4144       }
4145 
4146       case scUDivExpr:
4147       case scCouldNotCompute:
4148         // We do not try to smart about these at all.
4149         return setUnavailable();
4150       }
4151       llvm_unreachable("switch should be fully covered!");
4152     }
4153 
4154     bool isDone() { return TraversalDone; }
4155   };
4156 
4157   CheckAvailable CA(L, BB, DT);
4158   SCEVTraversal<CheckAvailable> ST(CA);
4159 
4160   ST.visitAll(S);
4161   return CA.Available;
4162 }
4163 
4164 // Try to match a control flow sequence that branches out at BI and merges back
4165 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4166 // match.
4167 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4168                           Value *&C, Value *&LHS, Value *&RHS) {
4169   C = BI->getCondition();
4170 
4171   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4172   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4173 
4174   if (!LeftEdge.isSingleEdge())
4175     return false;
4176 
4177   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4178 
4179   Use &LeftUse = Merge->getOperandUse(0);
4180   Use &RightUse = Merge->getOperandUse(1);
4181 
4182   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4183     LHS = LeftUse;
4184     RHS = RightUse;
4185     return true;
4186   }
4187 
4188   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4189     LHS = RightUse;
4190     RHS = LeftUse;
4191     return true;
4192   }
4193 
4194   return false;
4195 }
4196 
4197 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4198   auto IsReachable =
4199       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4200   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4201     const Loop *L = LI.getLoopFor(PN->getParent());
4202 
4203     // We don't want to break LCSSA, even in a SCEV expression tree.
4204     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4205       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4206         return nullptr;
4207 
4208     // Try to match
4209     //
4210     //  br %cond, label %left, label %right
4211     // left:
4212     //  br label %merge
4213     // right:
4214     //  br label %merge
4215     // merge:
4216     //  V = phi [ %x, %left ], [ %y, %right ]
4217     //
4218     // as "select %cond, %x, %y"
4219 
4220     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4221     assert(IDom && "At least the entry block should dominate PN");
4222 
4223     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4224     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4225 
4226     if (BI && BI->isConditional() &&
4227         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4228         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4229         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4230       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4231   }
4232 
4233   return nullptr;
4234 }
4235 
4236 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4237   if (const SCEV *S = createAddRecFromPHI(PN))
4238     return S;
4239 
4240   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4241     return S;
4242 
4243   // If the PHI has a single incoming value, follow that value, unless the
4244   // PHI's incoming blocks are in a different loop, in which case doing so
4245   // risks breaking LCSSA form. Instcombine would normally zap these, but
4246   // it doesn't have DominatorTree information, so it may miss cases.
4247   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4248     if (LI.replacementPreservesLCSSAForm(PN, V))
4249       return getSCEV(V);
4250 
4251   // If it's not a loop phi, we can't handle it yet.
4252   return getUnknown(PN);
4253 }
4254 
4255 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4256                                                       Value *Cond,
4257                                                       Value *TrueVal,
4258                                                       Value *FalseVal) {
4259   // Handle "constant" branch or select. This can occur for instance when a
4260   // loop pass transforms an inner loop and moves on to process the outer loop.
4261   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4262     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4263 
4264   // Try to match some simple smax or umax patterns.
4265   auto *ICI = dyn_cast<ICmpInst>(Cond);
4266   if (!ICI)
4267     return getUnknown(I);
4268 
4269   Value *LHS = ICI->getOperand(0);
4270   Value *RHS = ICI->getOperand(1);
4271 
4272   switch (ICI->getPredicate()) {
4273   case ICmpInst::ICMP_SLT:
4274   case ICmpInst::ICMP_SLE:
4275     std::swap(LHS, RHS);
4276     LLVM_FALLTHROUGH;
4277   case ICmpInst::ICMP_SGT:
4278   case ICmpInst::ICMP_SGE:
4279     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4280     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4281     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4282       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4283       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4284       const SCEV *LA = getSCEV(TrueVal);
4285       const SCEV *RA = getSCEV(FalseVal);
4286       const SCEV *LDiff = getMinusSCEV(LA, LS);
4287       const SCEV *RDiff = getMinusSCEV(RA, RS);
4288       if (LDiff == RDiff)
4289         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4290       LDiff = getMinusSCEV(LA, RS);
4291       RDiff = getMinusSCEV(RA, LS);
4292       if (LDiff == RDiff)
4293         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4294     }
4295     break;
4296   case ICmpInst::ICMP_ULT:
4297   case ICmpInst::ICMP_ULE:
4298     std::swap(LHS, RHS);
4299     LLVM_FALLTHROUGH;
4300   case ICmpInst::ICMP_UGT:
4301   case ICmpInst::ICMP_UGE:
4302     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4303     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4304     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4305       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4306       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4307       const SCEV *LA = getSCEV(TrueVal);
4308       const SCEV *RA = getSCEV(FalseVal);
4309       const SCEV *LDiff = getMinusSCEV(LA, LS);
4310       const SCEV *RDiff = getMinusSCEV(RA, RS);
4311       if (LDiff == RDiff)
4312         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4313       LDiff = getMinusSCEV(LA, RS);
4314       RDiff = getMinusSCEV(RA, LS);
4315       if (LDiff == RDiff)
4316         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4317     }
4318     break;
4319   case ICmpInst::ICMP_NE:
4320     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4321     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4322         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4323       const SCEV *One = getOne(I->getType());
4324       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4325       const SCEV *LA = getSCEV(TrueVal);
4326       const SCEV *RA = getSCEV(FalseVal);
4327       const SCEV *LDiff = getMinusSCEV(LA, LS);
4328       const SCEV *RDiff = getMinusSCEV(RA, One);
4329       if (LDiff == RDiff)
4330         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4331     }
4332     break;
4333   case ICmpInst::ICMP_EQ:
4334     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4335     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4336         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4337       const SCEV *One = getOne(I->getType());
4338       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4339       const SCEV *LA = getSCEV(TrueVal);
4340       const SCEV *RA = getSCEV(FalseVal);
4341       const SCEV *LDiff = getMinusSCEV(LA, One);
4342       const SCEV *RDiff = getMinusSCEV(RA, LS);
4343       if (LDiff == RDiff)
4344         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4345     }
4346     break;
4347   default:
4348     break;
4349   }
4350 
4351   return getUnknown(I);
4352 }
4353 
4354 /// Expand GEP instructions into add and multiply operations. This allows them
4355 /// to be analyzed by regular SCEV code.
4356 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4357   // Don't attempt to analyze GEPs over unsized objects.
4358   if (!GEP->getSourceElementType()->isSized())
4359     return getUnknown(GEP);
4360 
4361   SmallVector<const SCEV *, 4> IndexExprs;
4362   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4363     IndexExprs.push_back(getSCEV(*Index));
4364   return getGEPExpr(GEP->getSourceElementType(),
4365                     getSCEV(GEP->getPointerOperand()),
4366                     IndexExprs, GEP->isInBounds());
4367 }
4368 
4369 uint32_t
4370 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4371   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4372     return C->getAPInt().countTrailingZeros();
4373 
4374   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4375     return std::min(GetMinTrailingZeros(T->getOperand()),
4376                     (uint32_t)getTypeSizeInBits(T->getType()));
4377 
4378   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4379     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4380     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4381              getTypeSizeInBits(E->getType()) : OpRes;
4382   }
4383 
4384   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4385     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4386     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4387              getTypeSizeInBits(E->getType()) : OpRes;
4388   }
4389 
4390   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4391     // The result is the min of all operands results.
4392     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4393     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4394       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4395     return MinOpRes;
4396   }
4397 
4398   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4399     // The result is the sum of all operands results.
4400     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4401     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4402     for (unsigned i = 1, e = M->getNumOperands();
4403          SumOpRes != BitWidth && i != e; ++i)
4404       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
4405                           BitWidth);
4406     return SumOpRes;
4407   }
4408 
4409   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4410     // The result is the min of all operands results.
4411     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4412     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4413       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4414     return MinOpRes;
4415   }
4416 
4417   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4418     // The result is the min of all operands results.
4419     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4420     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4421       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4422     return MinOpRes;
4423   }
4424 
4425   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4426     // The result is the min of all operands results.
4427     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4428     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4429       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4430     return MinOpRes;
4431   }
4432 
4433   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4434     // For a SCEVUnknown, ask ValueTracking.
4435     unsigned BitWidth = getTypeSizeInBits(U->getType());
4436     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4437     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4438                      nullptr, &DT);
4439     return Zeros.countTrailingOnes();
4440   }
4441 
4442   // SCEVUDivExpr
4443   return 0;
4444 }
4445 
4446 /// Helper method to assign a range to V from metadata present in the IR.
4447 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4448   if (Instruction *I = dyn_cast<Instruction>(V))
4449     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4450       return getConstantRangeFromMetadata(*MD);
4451 
4452   return None;
4453 }
4454 
4455 /// Determine the range for a particular SCEV.  If SignHint is
4456 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4457 /// with a "cleaner" unsigned (resp. signed) representation.
4458 ConstantRange
4459 ScalarEvolution::getRange(const SCEV *S,
4460                           ScalarEvolution::RangeSignHint SignHint) {
4461   DenseMap<const SCEV *, ConstantRange> &Cache =
4462       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4463                                                        : SignedRanges;
4464 
4465   // See if we've computed this range already.
4466   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4467   if (I != Cache.end())
4468     return I->second;
4469 
4470   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4471     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4472 
4473   unsigned BitWidth = getTypeSizeInBits(S->getType());
4474   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4475 
4476   // If the value has known zeros, the maximum value will have those known zeros
4477   // as well.
4478   uint32_t TZ = GetMinTrailingZeros(S);
4479   if (TZ != 0) {
4480     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4481       ConservativeResult =
4482           ConstantRange(APInt::getMinValue(BitWidth),
4483                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4484     else
4485       ConservativeResult = ConstantRange(
4486           APInt::getSignedMinValue(BitWidth),
4487           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4488   }
4489 
4490   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4491     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4492     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4493       X = X.add(getRange(Add->getOperand(i), SignHint));
4494     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4495   }
4496 
4497   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4498     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4499     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4500       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4501     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4502   }
4503 
4504   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4505     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4506     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4507       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4508     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4509   }
4510 
4511   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4512     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4513     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4514       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4515     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4516   }
4517 
4518   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4519     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4520     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4521     return setRange(UDiv, SignHint,
4522                     ConservativeResult.intersectWith(X.udiv(Y)));
4523   }
4524 
4525   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4526     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4527     return setRange(ZExt, SignHint,
4528                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4529   }
4530 
4531   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4532     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4533     return setRange(SExt, SignHint,
4534                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4535   }
4536 
4537   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4538     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4539     return setRange(Trunc, SignHint,
4540                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4541   }
4542 
4543   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4544     // If there's no unsigned wrap, the value will never be less than its
4545     // initial value.
4546     if (AddRec->hasNoUnsignedWrap())
4547       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4548         if (!C->getValue()->isZero())
4549           ConservativeResult = ConservativeResult.intersectWith(
4550               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4551 
4552     // If there's no signed wrap, and all the operands have the same sign or
4553     // zero, the value won't ever change sign.
4554     if (AddRec->hasNoSignedWrap()) {
4555       bool AllNonNeg = true;
4556       bool AllNonPos = true;
4557       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4558         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4559         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4560       }
4561       if (AllNonNeg)
4562         ConservativeResult = ConservativeResult.intersectWith(
4563           ConstantRange(APInt(BitWidth, 0),
4564                         APInt::getSignedMinValue(BitWidth)));
4565       else if (AllNonPos)
4566         ConservativeResult = ConservativeResult.intersectWith(
4567           ConstantRange(APInt::getSignedMinValue(BitWidth),
4568                         APInt(BitWidth, 1)));
4569     }
4570 
4571     // TODO: non-affine addrec
4572     if (AddRec->isAffine()) {
4573       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4574       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4575           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4576         auto RangeFromAffine = getRangeForAffineAR(
4577             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4578             BitWidth);
4579         if (!RangeFromAffine.isFullSet())
4580           ConservativeResult =
4581               ConservativeResult.intersectWith(RangeFromAffine);
4582 
4583         auto RangeFromFactoring = getRangeViaFactoring(
4584             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4585             BitWidth);
4586         if (!RangeFromFactoring.isFullSet())
4587           ConservativeResult =
4588               ConservativeResult.intersectWith(RangeFromFactoring);
4589       }
4590     }
4591 
4592     return setRange(AddRec, SignHint, ConservativeResult);
4593   }
4594 
4595   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4596     // Check if the IR explicitly contains !range metadata.
4597     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4598     if (MDRange.hasValue())
4599       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4600 
4601     // Split here to avoid paying the compile-time cost of calling both
4602     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4603     // if needed.
4604     const DataLayout &DL = getDataLayout();
4605     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4606       // For a SCEVUnknown, ask ValueTracking.
4607       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4608       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4609       if (Ones != ~Zeros + 1)
4610         ConservativeResult =
4611             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4612     } else {
4613       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4614              "generalize as needed!");
4615       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4616       if (NS > 1)
4617         ConservativeResult = ConservativeResult.intersectWith(
4618             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4619                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4620     }
4621 
4622     return setRange(U, SignHint, ConservativeResult);
4623   }
4624 
4625   return setRange(S, SignHint, ConservativeResult);
4626 }
4627 
4628 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4629                                                    const SCEV *Step,
4630                                                    const SCEV *MaxBECount,
4631                                                    unsigned BitWidth) {
4632   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4633          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4634          "Precondition!");
4635 
4636   ConstantRange Result(BitWidth, /* isFullSet = */ true);
4637 
4638   // Check for overflow.  This must be done with ConstantRange arithmetic
4639   // because we could be called from within the ScalarEvolution overflow
4640   // checking code.
4641 
4642   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4643   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4644   ConstantRange ZExtMaxBECountRange =
4645       MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4646 
4647   ConstantRange StepSRange = getSignedRange(Step);
4648   ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4649 
4650   ConstantRange StartURange = getUnsignedRange(Start);
4651   ConstantRange EndURange =
4652       StartURange.add(MaxBECountRange.multiply(StepSRange));
4653 
4654   // Check for unsigned overflow.
4655   ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4656   ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4657   if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4658       ZExtEndURange) {
4659     APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4660                                EndURange.getUnsignedMin());
4661     APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4662                                EndURange.getUnsignedMax());
4663     bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4664     if (!IsFullRange)
4665       Result =
4666           Result.intersectWith(ConstantRange(Min, Max + 1));
4667   }
4668 
4669   ConstantRange StartSRange = getSignedRange(Start);
4670   ConstantRange EndSRange =
4671       StartSRange.add(MaxBECountRange.multiply(StepSRange));
4672 
4673   // Check for signed overflow. This must be done with ConstantRange
4674   // arithmetic because we could be called from within the ScalarEvolution
4675   // overflow checking code.
4676   ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4677   ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4678   if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4679       SExtEndSRange) {
4680     APInt Min =
4681         APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4682     APInt Max =
4683         APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4684     bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4685     if (!IsFullRange)
4686       Result =
4687           Result.intersectWith(ConstantRange(Min, Max + 1));
4688   }
4689 
4690   return Result;
4691 }
4692 
4693 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4694                                                     const SCEV *Step,
4695                                                     const SCEV *MaxBECount,
4696                                                     unsigned BitWidth) {
4697   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4698   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4699 
4700   struct SelectPattern {
4701     Value *Condition = nullptr;
4702     APInt TrueValue;
4703     APInt FalseValue;
4704 
4705     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4706                            const SCEV *S) {
4707       Optional<unsigned> CastOp;
4708       APInt Offset(BitWidth, 0);
4709 
4710       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4711              "Should be!");
4712 
4713       // Peel off a constant offset:
4714       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4715         // In the future we could consider being smarter here and handle
4716         // {Start+Step,+,Step} too.
4717         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4718           return;
4719 
4720         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4721         S = SA->getOperand(1);
4722       }
4723 
4724       // Peel off a cast operation
4725       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4726         CastOp = SCast->getSCEVType();
4727         S = SCast->getOperand();
4728       }
4729 
4730       using namespace llvm::PatternMatch;
4731 
4732       auto *SU = dyn_cast<SCEVUnknown>(S);
4733       const APInt *TrueVal, *FalseVal;
4734       if (!SU ||
4735           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4736                                           m_APInt(FalseVal)))) {
4737         Condition = nullptr;
4738         return;
4739       }
4740 
4741       TrueValue = *TrueVal;
4742       FalseValue = *FalseVal;
4743 
4744       // Re-apply the cast we peeled off earlier
4745       if (CastOp.hasValue())
4746         switch (*CastOp) {
4747         default:
4748           llvm_unreachable("Unknown SCEV cast type!");
4749 
4750         case scTruncate:
4751           TrueValue = TrueValue.trunc(BitWidth);
4752           FalseValue = FalseValue.trunc(BitWidth);
4753           break;
4754         case scZeroExtend:
4755           TrueValue = TrueValue.zext(BitWidth);
4756           FalseValue = FalseValue.zext(BitWidth);
4757           break;
4758         case scSignExtend:
4759           TrueValue = TrueValue.sext(BitWidth);
4760           FalseValue = FalseValue.sext(BitWidth);
4761           break;
4762         }
4763 
4764       // Re-apply the constant offset we peeled off earlier
4765       TrueValue += Offset;
4766       FalseValue += Offset;
4767     }
4768 
4769     bool isRecognized() { return Condition != nullptr; }
4770   };
4771 
4772   SelectPattern StartPattern(*this, BitWidth, Start);
4773   if (!StartPattern.isRecognized())
4774     return ConstantRange(BitWidth, /* isFullSet = */ true);
4775 
4776   SelectPattern StepPattern(*this, BitWidth, Step);
4777   if (!StepPattern.isRecognized())
4778     return ConstantRange(BitWidth, /* isFullSet = */ true);
4779 
4780   if (StartPattern.Condition != StepPattern.Condition) {
4781     // We don't handle this case today; but we could, by considering four
4782     // possibilities below instead of two. I'm not sure if there are cases where
4783     // that will help over what getRange already does, though.
4784     return ConstantRange(BitWidth, /* isFullSet = */ true);
4785   }
4786 
4787   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4788   // construct arbitrary general SCEV expressions here.  This function is called
4789   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4790   // say) can end up caching a suboptimal value.
4791 
4792   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4793   // C2352 and C2512 (otherwise it isn't needed).
4794 
4795   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4796   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4797   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4798   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4799 
4800   ConstantRange TrueRange =
4801       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4802   ConstantRange FalseRange =
4803       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4804 
4805   return TrueRange.unionWith(FalseRange);
4806 }
4807 
4808 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
4809   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
4810   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4811 
4812   // Return early if there are no flags to propagate to the SCEV.
4813   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4814   if (BinOp->hasNoUnsignedWrap())
4815     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4816   if (BinOp->hasNoSignedWrap())
4817     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4818   if (Flags == SCEV::FlagAnyWrap)
4819     return SCEV::FlagAnyWrap;
4820 
4821   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4822 }
4823 
4824 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4825   // Here we check that I is in the header of the innermost loop containing I,
4826   // since we only deal with instructions in the loop header. The actual loop we
4827   // need to check later will come from an add recurrence, but getting that
4828   // requires computing the SCEV of the operands, which can be expensive. This
4829   // check we can do cheaply to rule out some cases early.
4830   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
4831   if (InnermostContainingLoop == nullptr ||
4832       InnermostContainingLoop->getHeader() != I->getParent())
4833     return false;
4834 
4835   // Only proceed if we can prove that I does not yield poison.
4836   if (!isKnownNotFullPoison(I)) return false;
4837 
4838   // At this point we know that if I is executed, then it does not wrap
4839   // according to at least one of NSW or NUW. If I is not executed, then we do
4840   // not know if the calculation that I represents would wrap. Multiple
4841   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
4842   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4843   // derived from other instructions that map to the same SCEV. We cannot make
4844   // that guarantee for cases where I is not executed. So we need to find the
4845   // loop that I is considered in relation to and prove that I is executed for
4846   // every iteration of that loop. That implies that the value that I
4847   // calculates does not wrap anywhere in the loop, so then we can apply the
4848   // flags to the SCEV.
4849   //
4850   // We check isLoopInvariant to disambiguate in case we are adding recurrences
4851   // from different loops, so that we know which loop to prove that I is
4852   // executed in.
4853   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
4854     // I could be an extractvalue from a call to an overflow intrinsic.
4855     // TODO: We can do better here in some cases.
4856     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4857       return false;
4858     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
4859     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4860       bool AllOtherOpsLoopInvariant = true;
4861       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4862            ++OtherOpIndex) {
4863         if (OtherOpIndex != OpIndex) {
4864           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4865           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4866             AllOtherOpsLoopInvariant = false;
4867             break;
4868           }
4869         }
4870       }
4871       if (AllOtherOpsLoopInvariant &&
4872           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4873         return true;
4874     }
4875   }
4876   return false;
4877 }
4878 
4879 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4880   // If we know that \c I can never be poison period, then that's enough.
4881   if (isSCEVExprNeverPoison(I))
4882     return true;
4883 
4884   // For an add recurrence specifically, we assume that infinite loops without
4885   // side effects are undefined behavior, and then reason as follows:
4886   //
4887   // If the add recurrence is poison in any iteration, it is poison on all
4888   // future iterations (since incrementing poison yields poison). If the result
4889   // of the add recurrence is fed into the loop latch condition and the loop
4890   // does not contain any throws or exiting blocks other than the latch, we now
4891   // have the ability to "choose" whether the backedge is taken or not (by
4892   // choosing a sufficiently evil value for the poison feeding into the branch)
4893   // for every iteration including and after the one in which \p I first became
4894   // poison.  There are two possibilities (let's call the iteration in which \p
4895   // I first became poison as K):
4896   //
4897   //  1. In the set of iterations including and after K, the loop body executes
4898   //     no side effects.  In this case executing the backege an infinte number
4899   //     of times will yield undefined behavior.
4900   //
4901   //  2. In the set of iterations including and after K, the loop body executes
4902   //     at least one side effect.  In this case, that specific instance of side
4903   //     effect is control dependent on poison, which also yields undefined
4904   //     behavior.
4905 
4906   auto *ExitingBB = L->getExitingBlock();
4907   auto *LatchBB = L->getLoopLatch();
4908   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4909     return false;
4910 
4911   SmallPtrSet<const Instruction *, 16> Pushed;
4912   SmallVector<const Instruction *, 8> PoisonStack;
4913 
4914   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
4915   // things that are known to be fully poison under that assumption go on the
4916   // PoisonStack.
4917   Pushed.insert(I);
4918   PoisonStack.push_back(I);
4919 
4920   bool LatchControlDependentOnPoison = false;
4921   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
4922     const Instruction *Poison = PoisonStack.pop_back_val();
4923 
4924     for (auto *PoisonUser : Poison->users()) {
4925       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4926         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4927           PoisonStack.push_back(cast<Instruction>(PoisonUser));
4928       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
4929         assert(BI->isConditional() && "Only possibility!");
4930         if (BI->getParent() == LatchBB) {
4931           LatchControlDependentOnPoison = true;
4932           break;
4933         }
4934       }
4935     }
4936   }
4937 
4938   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4939 }
4940 
4941 ScalarEvolution::LoopProperties
4942 ScalarEvolution::getLoopProperties(const Loop *L) {
4943   typedef ScalarEvolution::LoopProperties LoopProperties;
4944 
4945   auto Itr = LoopPropertiesCache.find(L);
4946   if (Itr == LoopPropertiesCache.end()) {
4947     auto HasSideEffects = [](Instruction *I) {
4948       if (auto *SI = dyn_cast<StoreInst>(I))
4949         return !SI->isSimple();
4950 
4951       return I->mayHaveSideEffects();
4952     };
4953 
4954     LoopProperties LP = {/* HasNoAbnormalExits */ true,
4955                          /*HasNoSideEffects*/ true};
4956 
4957     for (auto *BB : L->getBlocks())
4958       for (auto &I : *BB) {
4959         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4960           LP.HasNoAbnormalExits = false;
4961         if (HasSideEffects(&I))
4962           LP.HasNoSideEffects = false;
4963         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
4964           break; // We're already as pessimistic as we can get.
4965       }
4966 
4967     auto InsertPair = LoopPropertiesCache.insert({L, LP});
4968     assert(InsertPair.second && "We just checked!");
4969     Itr = InsertPair.first;
4970   }
4971 
4972   return Itr->second;
4973 }
4974 
4975 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4976   if (!isSCEVable(V->getType()))
4977     return getUnknown(V);
4978 
4979   if (Instruction *I = dyn_cast<Instruction>(V)) {
4980     // Don't attempt to analyze instructions in blocks that aren't
4981     // reachable. Such instructions don't matter, and they aren't required
4982     // to obey basic rules for definitions dominating uses which this
4983     // analysis depends on.
4984     if (!DT.isReachableFromEntry(I->getParent()))
4985       return getUnknown(V);
4986   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4987     return getConstant(CI);
4988   else if (isa<ConstantPointerNull>(V))
4989     return getZero(V->getType());
4990   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4991     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
4992   else if (!isa<ConstantExpr>(V))
4993     return getUnknown(V);
4994 
4995   Operator *U = cast<Operator>(V);
4996   if (auto BO = MatchBinaryOp(U, DT)) {
4997     switch (BO->Opcode) {
4998     case Instruction::Add: {
4999       // The simple thing to do would be to just call getSCEV on both operands
5000       // and call getAddExpr with the result. However if we're looking at a
5001       // bunch of things all added together, this can be quite inefficient,
5002       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5003       // Instead, gather up all the operands and make a single getAddExpr call.
5004       // LLVM IR canonical form means we need only traverse the left operands.
5005       SmallVector<const SCEV *, 4> AddOps;
5006       do {
5007         if (BO->Op) {
5008           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5009             AddOps.push_back(OpSCEV);
5010             break;
5011           }
5012 
5013           // If a NUW or NSW flag can be applied to the SCEV for this
5014           // addition, then compute the SCEV for this addition by itself
5015           // with a separate call to getAddExpr. We need to do that
5016           // instead of pushing the operands of the addition onto AddOps,
5017           // since the flags are only known to apply to this particular
5018           // addition - they may not apply to other additions that can be
5019           // formed with operands from AddOps.
5020           const SCEV *RHS = getSCEV(BO->RHS);
5021           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5022           if (Flags != SCEV::FlagAnyWrap) {
5023             const SCEV *LHS = getSCEV(BO->LHS);
5024             if (BO->Opcode == Instruction::Sub)
5025               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5026             else
5027               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5028             break;
5029           }
5030         }
5031 
5032         if (BO->Opcode == Instruction::Sub)
5033           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5034         else
5035           AddOps.push_back(getSCEV(BO->RHS));
5036 
5037         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5038         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5039                        NewBO->Opcode != Instruction::Sub)) {
5040           AddOps.push_back(getSCEV(BO->LHS));
5041           break;
5042         }
5043         BO = NewBO;
5044       } while (true);
5045 
5046       return getAddExpr(AddOps);
5047     }
5048 
5049     case Instruction::Mul: {
5050       SmallVector<const SCEV *, 4> MulOps;
5051       do {
5052         if (BO->Op) {
5053           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5054             MulOps.push_back(OpSCEV);
5055             break;
5056           }
5057 
5058           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5059           if (Flags != SCEV::FlagAnyWrap) {
5060             MulOps.push_back(
5061                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5062             break;
5063           }
5064         }
5065 
5066         MulOps.push_back(getSCEV(BO->RHS));
5067         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5068         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5069           MulOps.push_back(getSCEV(BO->LHS));
5070           break;
5071         }
5072         BO = NewBO;
5073       } while (true);
5074 
5075       return getMulExpr(MulOps);
5076     }
5077     case Instruction::UDiv:
5078       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5079     case Instruction::Sub: {
5080       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5081       if (BO->Op)
5082         Flags = getNoWrapFlagsFromUB(BO->Op);
5083       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5084     }
5085     case Instruction::And:
5086       // For an expression like x&255 that merely masks off the high bits,
5087       // use zext(trunc(x)) as the SCEV expression.
5088       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5089         if (CI->isNullValue())
5090           return getSCEV(BO->RHS);
5091         if (CI->isAllOnesValue())
5092           return getSCEV(BO->LHS);
5093         const APInt &A = CI->getValue();
5094 
5095         // Instcombine's ShrinkDemandedConstant may strip bits out of
5096         // constants, obscuring what would otherwise be a low-bits mask.
5097         // Use computeKnownBits to compute what ShrinkDemandedConstant
5098         // knew about to reconstruct a low-bits mask value.
5099         unsigned LZ = A.countLeadingZeros();
5100         unsigned TZ = A.countTrailingZeros();
5101         unsigned BitWidth = A.getBitWidth();
5102         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5103         computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5104                          0, &AC, nullptr, &DT);
5105 
5106         APInt EffectiveMask =
5107             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5108         if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5109           const SCEV *MulCount = getConstant(ConstantInt::get(
5110               getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5111           return getMulExpr(
5112               getZeroExtendExpr(
5113                   getTruncateExpr(
5114                       getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5115                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5116                   BO->LHS->getType()),
5117               MulCount);
5118         }
5119       }
5120       break;
5121 
5122     case Instruction::Or:
5123       // If the RHS of the Or is a constant, we may have something like:
5124       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5125       // optimizations will transparently handle this case.
5126       //
5127       // In order for this transformation to be safe, the LHS must be of the
5128       // form X*(2^n) and the Or constant must be less than 2^n.
5129       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5130         const SCEV *LHS = getSCEV(BO->LHS);
5131         const APInt &CIVal = CI->getValue();
5132         if (GetMinTrailingZeros(LHS) >=
5133             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5134           // Build a plain add SCEV.
5135           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5136           // If the LHS of the add was an addrec and it has no-wrap flags,
5137           // transfer the no-wrap flags, since an or won't introduce a wrap.
5138           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5139             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5140             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5141                 OldAR->getNoWrapFlags());
5142           }
5143           return S;
5144         }
5145       }
5146       break;
5147 
5148     case Instruction::Xor:
5149       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5150         // If the RHS of xor is -1, then this is a not operation.
5151         if (CI->isAllOnesValue())
5152           return getNotSCEV(getSCEV(BO->LHS));
5153 
5154         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5155         // This is a variant of the check for xor with -1, and it handles
5156         // the case where instcombine has trimmed non-demanded bits out
5157         // of an xor with -1.
5158         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5159           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5160             if (LBO->getOpcode() == Instruction::And &&
5161                 LCI->getValue() == CI->getValue())
5162               if (const SCEVZeroExtendExpr *Z =
5163                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5164                 Type *UTy = BO->LHS->getType();
5165                 const SCEV *Z0 = Z->getOperand();
5166                 Type *Z0Ty = Z0->getType();
5167                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5168 
5169                 // If C is a low-bits mask, the zero extend is serving to
5170                 // mask off the high bits. Complement the operand and
5171                 // re-apply the zext.
5172                 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5173                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5174 
5175                 // If C is a single bit, it may be in the sign-bit position
5176                 // before the zero-extend. In this case, represent the xor
5177                 // using an add, which is equivalent, and re-apply the zext.
5178                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5179                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5180                     Trunc.isSignBit())
5181                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5182                                            UTy);
5183               }
5184       }
5185       break;
5186 
5187   case Instruction::Shl:
5188     // Turn shift left of a constant amount into a multiply.
5189     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5190       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5191 
5192       // If the shift count is not less than the bitwidth, the result of
5193       // the shift is undefined. Don't try to analyze it, because the
5194       // resolution chosen here may differ from the resolution chosen in
5195       // other parts of the compiler.
5196       if (SA->getValue().uge(BitWidth))
5197         break;
5198 
5199       // It is currently not resolved how to interpret NSW for left
5200       // shift by BitWidth - 1, so we avoid applying flags in that
5201       // case. Remove this check (or this comment) once the situation
5202       // is resolved. See
5203       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5204       // and http://reviews.llvm.org/D8890 .
5205       auto Flags = SCEV::FlagAnyWrap;
5206       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5207         Flags = getNoWrapFlagsFromUB(BO->Op);
5208 
5209       Constant *X = ConstantInt::get(getContext(),
5210         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5211       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5212     }
5213     break;
5214 
5215     case Instruction::AShr:
5216       // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5217       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5218         if (Operator *L = dyn_cast<Operator>(BO->LHS))
5219           if (L->getOpcode() == Instruction::Shl &&
5220               L->getOperand(1) == BO->RHS) {
5221             uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
5222 
5223             // If the shift count is not less than the bitwidth, the result of
5224             // the shift is undefined. Don't try to analyze it, because the
5225             // resolution chosen here may differ from the resolution chosen in
5226             // other parts of the compiler.
5227             if (CI->getValue().uge(BitWidth))
5228               break;
5229 
5230             uint64_t Amt = BitWidth - CI->getZExtValue();
5231             if (Amt == BitWidth)
5232               return getSCEV(L->getOperand(0)); // shift by zero --> noop
5233             return getSignExtendExpr(
5234                 getTruncateExpr(getSCEV(L->getOperand(0)),
5235                                 IntegerType::get(getContext(), Amt)),
5236                 BO->LHS->getType());
5237           }
5238       break;
5239     }
5240   }
5241 
5242   switch (U->getOpcode()) {
5243   case Instruction::Trunc:
5244     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5245 
5246   case Instruction::ZExt:
5247     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5248 
5249   case Instruction::SExt:
5250     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5251 
5252   case Instruction::BitCast:
5253     // BitCasts are no-op casts so we just eliminate the cast.
5254     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5255       return getSCEV(U->getOperand(0));
5256     break;
5257 
5258   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5259   // lead to pointer expressions which cannot safely be expanded to GEPs,
5260   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5261   // simplifying integer expressions.
5262 
5263   case Instruction::GetElementPtr:
5264     return createNodeForGEP(cast<GEPOperator>(U));
5265 
5266   case Instruction::PHI:
5267     return createNodeForPHI(cast<PHINode>(U));
5268 
5269   case Instruction::Select:
5270     // U can also be a select constant expr, which let fall through.  Since
5271     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5272     // constant expressions cannot have instructions as operands, we'd have
5273     // returned getUnknown for a select constant expressions anyway.
5274     if (isa<Instruction>(U))
5275       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5276                                       U->getOperand(1), U->getOperand(2));
5277     break;
5278 
5279   case Instruction::Call:
5280   case Instruction::Invoke:
5281     if (Value *RV = CallSite(U).getReturnedArgOperand())
5282       return getSCEV(RV);
5283     break;
5284   }
5285 
5286   return getUnknown(V);
5287 }
5288 
5289 
5290 
5291 //===----------------------------------------------------------------------===//
5292 //                   Iteration Count Computation Code
5293 //
5294 
5295 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5296   if (BasicBlock *ExitingBB = L->getExitingBlock())
5297     return getSmallConstantTripCount(L, ExitingBB);
5298 
5299   // No trip count information for multiple exits.
5300   return 0;
5301 }
5302 
5303 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5304                                                     BasicBlock *ExitingBlock) {
5305   assert(ExitingBlock && "Must pass a non-null exiting block!");
5306   assert(L->isLoopExiting(ExitingBlock) &&
5307          "Exiting block must actually branch out of the loop!");
5308   const SCEVConstant *ExitCount =
5309       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5310   if (!ExitCount)
5311     return 0;
5312 
5313   ConstantInt *ExitConst = ExitCount->getValue();
5314 
5315   // Guard against huge trip counts.
5316   if (ExitConst->getValue().getActiveBits() > 32)
5317     return 0;
5318 
5319   // In case of integer overflow, this returns 0, which is correct.
5320   return ((unsigned)ExitConst->getZExtValue()) + 1;
5321 }
5322 
5323 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5324   if (BasicBlock *ExitingBB = L->getExitingBlock())
5325     return getSmallConstantTripMultiple(L, ExitingBB);
5326 
5327   // No trip multiple information for multiple exits.
5328   return 0;
5329 }
5330 
5331 /// Returns the largest constant divisor of the trip count of this loop as a
5332 /// normal unsigned value, if possible. This means that the actual trip count is
5333 /// always a multiple of the returned value (don't forget the trip count could
5334 /// very well be zero as well!).
5335 ///
5336 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5337 /// multiple of a constant (which is also the case if the trip count is simply
5338 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5339 /// if the trip count is very large (>= 2^32).
5340 ///
5341 /// As explained in the comments for getSmallConstantTripCount, this assumes
5342 /// that control exits the loop via ExitingBlock.
5343 unsigned
5344 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5345                                               BasicBlock *ExitingBlock) {
5346   assert(ExitingBlock && "Must pass a non-null exiting block!");
5347   assert(L->isLoopExiting(ExitingBlock) &&
5348          "Exiting block must actually branch out of the loop!");
5349   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5350   if (ExitCount == getCouldNotCompute())
5351     return 1;
5352 
5353   // Get the trip count from the BE count by adding 1.
5354   const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5355   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5356   // to factor simple cases.
5357   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5358     TCMul = Mul->getOperand(0);
5359 
5360   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5361   if (!MulC)
5362     return 1;
5363 
5364   ConstantInt *Result = MulC->getValue();
5365 
5366   // Guard against huge trip counts (this requires checking
5367   // for zero to handle the case where the trip count == -1 and the
5368   // addition wraps).
5369   if (!Result || Result->getValue().getActiveBits() > 32 ||
5370       Result->getValue().getActiveBits() == 0)
5371     return 1;
5372 
5373   return (unsigned)Result->getZExtValue();
5374 }
5375 
5376 /// Get the expression for the number of loop iterations for which this loop is
5377 /// guaranteed not to exit via ExitingBlock. Otherwise return
5378 /// SCEVCouldNotCompute.
5379 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5380   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5381 }
5382 
5383 const SCEV *
5384 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5385                                                  SCEVUnionPredicate &Preds) {
5386   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5387 }
5388 
5389 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5390   return getBackedgeTakenInfo(L).getExact(this);
5391 }
5392 
5393 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5394 /// known never to be less than the actual backedge taken count.
5395 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5396   return getBackedgeTakenInfo(L).getMax(this);
5397 }
5398 
5399 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5400 static void
5401 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5402   BasicBlock *Header = L->getHeader();
5403 
5404   // Push all Loop-header PHIs onto the Worklist stack.
5405   for (BasicBlock::iterator I = Header->begin();
5406        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5407     Worklist.push_back(PN);
5408 }
5409 
5410 const ScalarEvolution::BackedgeTakenInfo &
5411 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5412   auto &BTI = getBackedgeTakenInfo(L);
5413   if (BTI.hasFullInfo())
5414     return BTI;
5415 
5416   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5417 
5418   if (!Pair.second)
5419     return Pair.first->second;
5420 
5421   BackedgeTakenInfo Result =
5422       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5423 
5424   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5425 }
5426 
5427 const ScalarEvolution::BackedgeTakenInfo &
5428 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5429   // Initially insert an invalid entry for this loop. If the insertion
5430   // succeeds, proceed to actually compute a backedge-taken count and
5431   // update the value. The temporary CouldNotCompute value tells SCEV
5432   // code elsewhere that it shouldn't attempt to request a new
5433   // backedge-taken count, which could result in infinite recursion.
5434   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5435       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5436   if (!Pair.second)
5437     return Pair.first->second;
5438 
5439   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5440   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5441   // must be cleared in this scope.
5442   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5443 
5444   if (Result.getExact(this) != getCouldNotCompute()) {
5445     assert(isLoopInvariant(Result.getExact(this), L) &&
5446            isLoopInvariant(Result.getMax(this), L) &&
5447            "Computed backedge-taken count isn't loop invariant for loop!");
5448     ++NumTripCountsComputed;
5449   }
5450   else if (Result.getMax(this) == getCouldNotCompute() &&
5451            isa<PHINode>(L->getHeader()->begin())) {
5452     // Only count loops that have phi nodes as not being computable.
5453     ++NumTripCountsNotComputed;
5454   }
5455 
5456   // Now that we know more about the trip count for this loop, forget any
5457   // existing SCEV values for PHI nodes in this loop since they are only
5458   // conservative estimates made without the benefit of trip count
5459   // information. This is similar to the code in forgetLoop, except that
5460   // it handles SCEVUnknown PHI nodes specially.
5461   if (Result.hasAnyInfo()) {
5462     SmallVector<Instruction *, 16> Worklist;
5463     PushLoopPHIs(L, Worklist);
5464 
5465     SmallPtrSet<Instruction *, 8> Visited;
5466     while (!Worklist.empty()) {
5467       Instruction *I = Worklist.pop_back_val();
5468       if (!Visited.insert(I).second)
5469         continue;
5470 
5471       ValueExprMapType::iterator It =
5472         ValueExprMap.find_as(static_cast<Value *>(I));
5473       if (It != ValueExprMap.end()) {
5474         const SCEV *Old = It->second;
5475 
5476         // SCEVUnknown for a PHI either means that it has an unrecognized
5477         // structure, or it's a PHI that's in the progress of being computed
5478         // by createNodeForPHI.  In the former case, additional loop trip
5479         // count information isn't going to change anything. In the later
5480         // case, createNodeForPHI will perform the necessary updates on its
5481         // own when it gets to that point.
5482         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5483           eraseValueFromMap(It->first);
5484           forgetMemoizedResults(Old);
5485         }
5486         if (PHINode *PN = dyn_cast<PHINode>(I))
5487           ConstantEvolutionLoopExitValue.erase(PN);
5488       }
5489 
5490       PushDefUseChildren(I, Worklist);
5491     }
5492   }
5493 
5494   // Re-lookup the insert position, since the call to
5495   // computeBackedgeTakenCount above could result in a
5496   // recusive call to getBackedgeTakenInfo (on a different
5497   // loop), which would invalidate the iterator computed
5498   // earlier.
5499   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5500 }
5501 
5502 void ScalarEvolution::forgetLoop(const Loop *L) {
5503   // Drop any stored trip count value.
5504   auto RemoveLoopFromBackedgeMap =
5505       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5506         auto BTCPos = Map.find(L);
5507         if (BTCPos != Map.end()) {
5508           BTCPos->second.clear();
5509           Map.erase(BTCPos);
5510         }
5511       };
5512 
5513   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5514   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5515 
5516   // Drop information about expressions based on loop-header PHIs.
5517   SmallVector<Instruction *, 16> Worklist;
5518   PushLoopPHIs(L, Worklist);
5519 
5520   SmallPtrSet<Instruction *, 8> Visited;
5521   while (!Worklist.empty()) {
5522     Instruction *I = Worklist.pop_back_val();
5523     if (!Visited.insert(I).second)
5524       continue;
5525 
5526     ValueExprMapType::iterator It =
5527       ValueExprMap.find_as(static_cast<Value *>(I));
5528     if (It != ValueExprMap.end()) {
5529       eraseValueFromMap(It->first);
5530       forgetMemoizedResults(It->second);
5531       if (PHINode *PN = dyn_cast<PHINode>(I))
5532         ConstantEvolutionLoopExitValue.erase(PN);
5533     }
5534 
5535     PushDefUseChildren(I, Worklist);
5536   }
5537 
5538   // Forget all contained loops too, to avoid dangling entries in the
5539   // ValuesAtScopes map.
5540   for (Loop *I : *L)
5541     forgetLoop(I);
5542 
5543   LoopPropertiesCache.erase(L);
5544 }
5545 
5546 void ScalarEvolution::forgetValue(Value *V) {
5547   Instruction *I = dyn_cast<Instruction>(V);
5548   if (!I) return;
5549 
5550   // Drop information about expressions based on loop-header PHIs.
5551   SmallVector<Instruction *, 16> Worklist;
5552   Worklist.push_back(I);
5553 
5554   SmallPtrSet<Instruction *, 8> Visited;
5555   while (!Worklist.empty()) {
5556     I = Worklist.pop_back_val();
5557     if (!Visited.insert(I).second)
5558       continue;
5559 
5560     ValueExprMapType::iterator It =
5561       ValueExprMap.find_as(static_cast<Value *>(I));
5562     if (It != ValueExprMap.end()) {
5563       eraseValueFromMap(It->first);
5564       forgetMemoizedResults(It->second);
5565       if (PHINode *PN = dyn_cast<PHINode>(I))
5566         ConstantEvolutionLoopExitValue.erase(PN);
5567     }
5568 
5569     PushDefUseChildren(I, Worklist);
5570   }
5571 }
5572 
5573 /// Get the exact loop backedge taken count considering all loop exits. A
5574 /// computable result can only be returned for loops with a single exit.
5575 /// Returning the minimum taken count among all exits is incorrect because one
5576 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5577 /// the limit of each loop test is never skipped. This is a valid assumption as
5578 /// long as the loop exits via that test. For precise results, it is the
5579 /// caller's responsibility to specify the relevant loop exit using
5580 /// getExact(ExitingBlock, SE).
5581 const SCEV *
5582 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5583                                              SCEVUnionPredicate *Preds) const {
5584   // If any exits were not computable, the loop is not computable.
5585   if (!isComplete() || ExitNotTaken.empty())
5586     return SE->getCouldNotCompute();
5587 
5588   const SCEV *BECount = nullptr;
5589   for (auto &ENT : ExitNotTaken) {
5590     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5591 
5592     if (!BECount)
5593       BECount = ENT.ExactNotTaken;
5594     else if (BECount != ENT.ExactNotTaken)
5595       return SE->getCouldNotCompute();
5596     if (Preds && !ENT.hasAlwaysTruePredicate())
5597       Preds->add(ENT.Predicate.get());
5598 
5599     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5600            "Predicate should be always true!");
5601   }
5602 
5603   assert(BECount && "Invalid not taken count for loop exit");
5604   return BECount;
5605 }
5606 
5607 /// Get the exact not taken count for this loop exit.
5608 const SCEV *
5609 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5610                                              ScalarEvolution *SE) const {
5611   for (auto &ENT : ExitNotTaken)
5612     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5613       return ENT.ExactNotTaken;
5614 
5615   return SE->getCouldNotCompute();
5616 }
5617 
5618 /// getMax - Get the max backedge taken count for the loop.
5619 const SCEV *
5620 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5621   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5622     return !ENT.hasAlwaysTruePredicate();
5623   };
5624 
5625   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5626     return SE->getCouldNotCompute();
5627 
5628   return getMax();
5629 }
5630 
5631 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5632                                                     ScalarEvolution *SE) const {
5633   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5634       SE->hasOperand(getMax(), S))
5635     return true;
5636 
5637   for (auto &ENT : ExitNotTaken)
5638     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5639         SE->hasOperand(ENT.ExactNotTaken, S))
5640       return true;
5641 
5642   return false;
5643 }
5644 
5645 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5646 /// computable exit into a persistent ExitNotTakenInfo array.
5647 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5648     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5649         &&ExitCounts,
5650     bool Complete, const SCEV *MaxCount)
5651     : MaxAndComplete(MaxCount, Complete) {
5652   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5653   ExitNotTaken.reserve(ExitCounts.size());
5654   std::transform(
5655       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5656       [&](const EdgeExitInfo &EEI) {
5657         BasicBlock *ExitBB = EEI.first;
5658         const ExitLimit &EL = EEI.second;
5659         if (EL.Predicates.empty())
5660           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5661 
5662         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5663         for (auto *Pred : EL.Predicates)
5664           Predicate->add(Pred);
5665 
5666         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5667       });
5668 }
5669 
5670 /// Invalidate this result and free the ExitNotTakenInfo array.
5671 void ScalarEvolution::BackedgeTakenInfo::clear() {
5672   ExitNotTaken.clear();
5673 }
5674 
5675 /// Compute the number of times the backedge of the specified loop will execute.
5676 ScalarEvolution::BackedgeTakenInfo
5677 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5678                                            bool AllowPredicates) {
5679   SmallVector<BasicBlock *, 8> ExitingBlocks;
5680   L->getExitingBlocks(ExitingBlocks);
5681 
5682   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5683 
5684   SmallVector<EdgeExitInfo, 4> ExitCounts;
5685   bool CouldComputeBECount = true;
5686   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5687   const SCEV *MustExitMaxBECount = nullptr;
5688   const SCEV *MayExitMaxBECount = nullptr;
5689 
5690   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5691   // and compute maxBECount.
5692   // Do a union of all the predicates here.
5693   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5694     BasicBlock *ExitBB = ExitingBlocks[i];
5695     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5696 
5697     assert((AllowPredicates || EL.Predicates.empty()) &&
5698            "Predicated exit limit when predicates are not allowed!");
5699 
5700     // 1. For each exit that can be computed, add an entry to ExitCounts.
5701     // CouldComputeBECount is true only if all exits can be computed.
5702     if (EL.ExactNotTaken == getCouldNotCompute())
5703       // We couldn't compute an exact value for this exit, so
5704       // we won't be able to compute an exact value for the loop.
5705       CouldComputeBECount = false;
5706     else
5707       ExitCounts.emplace_back(ExitBB, EL);
5708 
5709     // 2. Derive the loop's MaxBECount from each exit's max number of
5710     // non-exiting iterations. Partition the loop exits into two kinds:
5711     // LoopMustExits and LoopMayExits.
5712     //
5713     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5714     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5715     // MaxBECount is the minimum EL.MaxNotTaken of computable
5716     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5717     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5718     // computable EL.MaxNotTaken.
5719     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5720         DT.dominates(ExitBB, Latch)) {
5721       if (!MustExitMaxBECount)
5722         MustExitMaxBECount = EL.MaxNotTaken;
5723       else {
5724         MustExitMaxBECount =
5725             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5726       }
5727     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5728       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5729         MayExitMaxBECount = EL.MaxNotTaken;
5730       else {
5731         MayExitMaxBECount =
5732             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5733       }
5734     }
5735   }
5736   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5737     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5738   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
5739                            MaxBECount);
5740 }
5741 
5742 ScalarEvolution::ExitLimit
5743 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5744                                   bool AllowPredicates) {
5745 
5746   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5747   // at this block and remember the exit block and whether all other targets
5748   // lead to the loop header.
5749   bool MustExecuteLoopHeader = true;
5750   BasicBlock *Exit = nullptr;
5751   for (auto *SBB : successors(ExitingBlock))
5752     if (!L->contains(SBB)) {
5753       if (Exit) // Multiple exit successors.
5754         return getCouldNotCompute();
5755       Exit = SBB;
5756     } else if (SBB != L->getHeader()) {
5757       MustExecuteLoopHeader = false;
5758     }
5759 
5760   // At this point, we know we have a conditional branch that determines whether
5761   // the loop is exited.  However, we don't know if the branch is executed each
5762   // time through the loop.  If not, then the execution count of the branch will
5763   // not be equal to the trip count of the loop.
5764   //
5765   // Currently we check for this by checking to see if the Exit branch goes to
5766   // the loop header.  If so, we know it will always execute the same number of
5767   // times as the loop.  We also handle the case where the exit block *is* the
5768   // loop header.  This is common for un-rotated loops.
5769   //
5770   // If both of those tests fail, walk up the unique predecessor chain to the
5771   // header, stopping if there is an edge that doesn't exit the loop. If the
5772   // header is reached, the execution count of the branch will be equal to the
5773   // trip count of the loop.
5774   //
5775   //  More extensive analysis could be done to handle more cases here.
5776   //
5777   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
5778     // The simple checks failed, try climbing the unique predecessor chain
5779     // up to the header.
5780     bool Ok = false;
5781     for (BasicBlock *BB = ExitingBlock; BB; ) {
5782       BasicBlock *Pred = BB->getUniquePredecessor();
5783       if (!Pred)
5784         return getCouldNotCompute();
5785       TerminatorInst *PredTerm = Pred->getTerminator();
5786       for (const BasicBlock *PredSucc : PredTerm->successors()) {
5787         if (PredSucc == BB)
5788           continue;
5789         // If the predecessor has a successor that isn't BB and isn't
5790         // outside the loop, assume the worst.
5791         if (L->contains(PredSucc))
5792           return getCouldNotCompute();
5793       }
5794       if (Pred == L->getHeader()) {
5795         Ok = true;
5796         break;
5797       }
5798       BB = Pred;
5799     }
5800     if (!Ok)
5801       return getCouldNotCompute();
5802   }
5803 
5804   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
5805   TerminatorInst *Term = ExitingBlock->getTerminator();
5806   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5807     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5808     // Proceed to the next level to examine the exit condition expression.
5809     return computeExitLimitFromCond(
5810         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5811         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
5812   }
5813 
5814   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
5815     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
5816                                                 /*ControlsExit=*/IsOnlyExit);
5817 
5818   return getCouldNotCompute();
5819 }
5820 
5821 ScalarEvolution::ExitLimit
5822 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
5823                                           Value *ExitCond,
5824                                           BasicBlock *TBB,
5825                                           BasicBlock *FBB,
5826                                           bool ControlsExit,
5827                                           bool AllowPredicates) {
5828   // Check if the controlling expression for this loop is an And or Or.
5829   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5830     if (BO->getOpcode() == Instruction::And) {
5831       // Recurse on the operands of the and.
5832       bool EitherMayExit = L->contains(TBB);
5833       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5834                                                ControlsExit && !EitherMayExit,
5835                                                AllowPredicates);
5836       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5837                                                ControlsExit && !EitherMayExit,
5838                                                AllowPredicates);
5839       const SCEV *BECount = getCouldNotCompute();
5840       const SCEV *MaxBECount = getCouldNotCompute();
5841       if (EitherMayExit) {
5842         // Both conditions must be true for the loop to continue executing.
5843         // Choose the less conservative count.
5844         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5845             EL1.ExactNotTaken == getCouldNotCompute())
5846           BECount = getCouldNotCompute();
5847         else
5848           BECount =
5849               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5850         if (EL0.MaxNotTaken == getCouldNotCompute())
5851           MaxBECount = EL1.MaxNotTaken;
5852         else if (EL1.MaxNotTaken == getCouldNotCompute())
5853           MaxBECount = EL0.MaxNotTaken;
5854         else
5855           MaxBECount =
5856               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5857       } else {
5858         // Both conditions must be true at the same time for the loop to exit.
5859         // For now, be conservative.
5860         assert(L->contains(FBB) && "Loop block has no successor in loop!");
5861         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5862           MaxBECount = EL0.MaxNotTaken;
5863         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5864           BECount = EL0.ExactNotTaken;
5865       }
5866 
5867       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5868       // to be more aggressive when computing BECount than when computing
5869       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
5870       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5871       // to not.
5872       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5873           !isa<SCEVCouldNotCompute>(BECount))
5874         MaxBECount = BECount;
5875 
5876       return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates});
5877     }
5878     if (BO->getOpcode() == Instruction::Or) {
5879       // Recurse on the operands of the or.
5880       bool EitherMayExit = L->contains(FBB);
5881       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5882                                                ControlsExit && !EitherMayExit,
5883                                                AllowPredicates);
5884       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5885                                                ControlsExit && !EitherMayExit,
5886                                                AllowPredicates);
5887       const SCEV *BECount = getCouldNotCompute();
5888       const SCEV *MaxBECount = getCouldNotCompute();
5889       if (EitherMayExit) {
5890         // Both conditions must be false for the loop to continue executing.
5891         // Choose the less conservative count.
5892         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5893             EL1.ExactNotTaken == getCouldNotCompute())
5894           BECount = getCouldNotCompute();
5895         else
5896           BECount =
5897               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5898         if (EL0.MaxNotTaken == getCouldNotCompute())
5899           MaxBECount = EL1.MaxNotTaken;
5900         else if (EL1.MaxNotTaken == getCouldNotCompute())
5901           MaxBECount = EL0.MaxNotTaken;
5902         else
5903           MaxBECount =
5904               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5905       } else {
5906         // Both conditions must be false at the same time for the loop to exit.
5907         // For now, be conservative.
5908         assert(L->contains(TBB) && "Loop block has no successor in loop!");
5909         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5910           MaxBECount = EL0.MaxNotTaken;
5911         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5912           BECount = EL0.ExactNotTaken;
5913       }
5914 
5915       return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates});
5916     }
5917   }
5918 
5919   // With an icmp, it may be feasible to compute an exact backedge-taken count.
5920   // Proceed to the next level to examine the icmp.
5921   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5922     ExitLimit EL =
5923         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5924     if (EL.hasFullInfo() || !AllowPredicates)
5925       return EL;
5926 
5927     // Try again, but use SCEV predicates this time.
5928     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5929                                     /*AllowPredicates=*/true);
5930   }
5931 
5932   // Check for a constant condition. These are normally stripped out by
5933   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5934   // preserve the CFG and is temporarily leaving constant conditions
5935   // in place.
5936   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5937     if (L->contains(FBB) == !CI->getZExtValue())
5938       // The backedge is always taken.
5939       return getCouldNotCompute();
5940     else
5941       // The backedge is never taken.
5942       return getZero(CI->getType());
5943   }
5944 
5945   // If it's not an integer or pointer comparison then compute it the hard way.
5946   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5947 }
5948 
5949 ScalarEvolution::ExitLimit
5950 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
5951                                           ICmpInst *ExitCond,
5952                                           BasicBlock *TBB,
5953                                           BasicBlock *FBB,
5954                                           bool ControlsExit,
5955                                           bool AllowPredicates) {
5956 
5957   // If the condition was exit on true, convert the condition to exit on false
5958   ICmpInst::Predicate Cond;
5959   if (!L->contains(FBB))
5960     Cond = ExitCond->getPredicate();
5961   else
5962     Cond = ExitCond->getInversePredicate();
5963 
5964   // Handle common loops like: for (X = "string"; *X; ++X)
5965   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5966     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5967       ExitLimit ItCnt =
5968         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5969       if (ItCnt.hasAnyInfo())
5970         return ItCnt;
5971     }
5972 
5973   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5974   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
5975 
5976   // Try to evaluate any dependencies out of the loop.
5977   LHS = getSCEVAtScope(LHS, L);
5978   RHS = getSCEVAtScope(RHS, L);
5979 
5980   // At this point, we would like to compute how many iterations of the
5981   // loop the predicate will return true for these inputs.
5982   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
5983     // If there is a loop-invariant, force it into the RHS.
5984     std::swap(LHS, RHS);
5985     Cond = ICmpInst::getSwappedPredicate(Cond);
5986   }
5987 
5988   // Simplify the operands before analyzing them.
5989   (void)SimplifyICmpOperands(Cond, LHS, RHS);
5990 
5991   // If we have a comparison of a chrec against a constant, try to use value
5992   // ranges to answer this query.
5993   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5994     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
5995       if (AddRec->getLoop() == L) {
5996         // Form the constant range.
5997         ConstantRange CompRange =
5998             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
5999 
6000         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6001         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6002       }
6003 
6004   switch (Cond) {
6005   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6006     // Convert to: while (X-Y != 0)
6007     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6008                                 AllowPredicates);
6009     if (EL.hasAnyInfo()) return EL;
6010     break;
6011   }
6012   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6013     // Convert to: while (X-Y == 0)
6014     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6015     if (EL.hasAnyInfo()) return EL;
6016     break;
6017   }
6018   case ICmpInst::ICMP_SLT:
6019   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6020     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6021     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6022                                     AllowPredicates);
6023     if (EL.hasAnyInfo()) return EL;
6024     break;
6025   }
6026   case ICmpInst::ICMP_SGT:
6027   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6028     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6029     ExitLimit EL =
6030         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6031                             AllowPredicates);
6032     if (EL.hasAnyInfo()) return EL;
6033     break;
6034   }
6035   default:
6036     break;
6037   }
6038 
6039   auto *ExhaustiveCount =
6040       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6041 
6042   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6043     return ExhaustiveCount;
6044 
6045   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6046                                       ExitCond->getOperand(1), L, Cond);
6047 }
6048 
6049 ScalarEvolution::ExitLimit
6050 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6051                                                       SwitchInst *Switch,
6052                                                       BasicBlock *ExitingBlock,
6053                                                       bool ControlsExit) {
6054   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6055 
6056   // Give up if the exit is the default dest of a switch.
6057   if (Switch->getDefaultDest() == ExitingBlock)
6058     return getCouldNotCompute();
6059 
6060   assert(L->contains(Switch->getDefaultDest()) &&
6061          "Default case must not exit the loop!");
6062   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6063   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6064 
6065   // while (X != Y) --> while (X-Y != 0)
6066   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6067   if (EL.hasAnyInfo())
6068     return EL;
6069 
6070   return getCouldNotCompute();
6071 }
6072 
6073 static ConstantInt *
6074 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6075                                 ScalarEvolution &SE) {
6076   const SCEV *InVal = SE.getConstant(C);
6077   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6078   assert(isa<SCEVConstant>(Val) &&
6079          "Evaluation of SCEV at constant didn't fold correctly?");
6080   return cast<SCEVConstant>(Val)->getValue();
6081 }
6082 
6083 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6084 /// compute the backedge execution count.
6085 ScalarEvolution::ExitLimit
6086 ScalarEvolution::computeLoadConstantCompareExitLimit(
6087   LoadInst *LI,
6088   Constant *RHS,
6089   const Loop *L,
6090   ICmpInst::Predicate predicate) {
6091 
6092   if (LI->isVolatile()) return getCouldNotCompute();
6093 
6094   // Check to see if the loaded pointer is a getelementptr of a global.
6095   // TODO: Use SCEV instead of manually grubbing with GEPs.
6096   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6097   if (!GEP) return getCouldNotCompute();
6098 
6099   // Make sure that it is really a constant global we are gepping, with an
6100   // initializer, and make sure the first IDX is really 0.
6101   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6102   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6103       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6104       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6105     return getCouldNotCompute();
6106 
6107   // Okay, we allow one non-constant index into the GEP instruction.
6108   Value *VarIdx = nullptr;
6109   std::vector<Constant*> Indexes;
6110   unsigned VarIdxNum = 0;
6111   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6112     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6113       Indexes.push_back(CI);
6114     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6115       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6116       VarIdx = GEP->getOperand(i);
6117       VarIdxNum = i-2;
6118       Indexes.push_back(nullptr);
6119     }
6120 
6121   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6122   if (!VarIdx)
6123     return getCouldNotCompute();
6124 
6125   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6126   // Check to see if X is a loop variant variable value now.
6127   const SCEV *Idx = getSCEV(VarIdx);
6128   Idx = getSCEVAtScope(Idx, L);
6129 
6130   // We can only recognize very limited forms of loop index expressions, in
6131   // particular, only affine AddRec's like {C1,+,C2}.
6132   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6133   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6134       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6135       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6136     return getCouldNotCompute();
6137 
6138   unsigned MaxSteps = MaxBruteForceIterations;
6139   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6140     ConstantInt *ItCst = ConstantInt::get(
6141                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6142     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6143 
6144     // Form the GEP offset.
6145     Indexes[VarIdxNum] = Val;
6146 
6147     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6148                                                          Indexes);
6149     if (!Result) break;  // Cannot compute!
6150 
6151     // Evaluate the condition for this iteration.
6152     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6153     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6154     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6155       ++NumArrayLenItCounts;
6156       return getConstant(ItCst);   // Found terminating iteration!
6157     }
6158   }
6159   return getCouldNotCompute();
6160 }
6161 
6162 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6163     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6164   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6165   if (!RHS)
6166     return getCouldNotCompute();
6167 
6168   const BasicBlock *Latch = L->getLoopLatch();
6169   if (!Latch)
6170     return getCouldNotCompute();
6171 
6172   const BasicBlock *Predecessor = L->getLoopPredecessor();
6173   if (!Predecessor)
6174     return getCouldNotCompute();
6175 
6176   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6177   // Return LHS in OutLHS and shift_opt in OutOpCode.
6178   auto MatchPositiveShift =
6179       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6180 
6181     using namespace PatternMatch;
6182 
6183     ConstantInt *ShiftAmt;
6184     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6185       OutOpCode = Instruction::LShr;
6186     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6187       OutOpCode = Instruction::AShr;
6188     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6189       OutOpCode = Instruction::Shl;
6190     else
6191       return false;
6192 
6193     return ShiftAmt->getValue().isStrictlyPositive();
6194   };
6195 
6196   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6197   //
6198   // loop:
6199   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6200   //   %iv.shifted = lshr i32 %iv, <positive constant>
6201   //
6202   // Return true on a succesful match.  Return the corresponding PHI node (%iv
6203   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6204   auto MatchShiftRecurrence =
6205       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6206     Optional<Instruction::BinaryOps> PostShiftOpCode;
6207 
6208     {
6209       Instruction::BinaryOps OpC;
6210       Value *V;
6211 
6212       // If we encounter a shift instruction, "peel off" the shift operation,
6213       // and remember that we did so.  Later when we inspect %iv's backedge
6214       // value, we will make sure that the backedge value uses the same
6215       // operation.
6216       //
6217       // Note: the peeled shift operation does not have to be the same
6218       // instruction as the one feeding into the PHI's backedge value.  We only
6219       // really care about it being the same *kind* of shift instruction --
6220       // that's all that is required for our later inferences to hold.
6221       if (MatchPositiveShift(LHS, V, OpC)) {
6222         PostShiftOpCode = OpC;
6223         LHS = V;
6224       }
6225     }
6226 
6227     PNOut = dyn_cast<PHINode>(LHS);
6228     if (!PNOut || PNOut->getParent() != L->getHeader())
6229       return false;
6230 
6231     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6232     Value *OpLHS;
6233 
6234     return
6235         // The backedge value for the PHI node must be a shift by a positive
6236         // amount
6237         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6238 
6239         // of the PHI node itself
6240         OpLHS == PNOut &&
6241 
6242         // and the kind of shift should be match the kind of shift we peeled
6243         // off, if any.
6244         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6245   };
6246 
6247   PHINode *PN;
6248   Instruction::BinaryOps OpCode;
6249   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6250     return getCouldNotCompute();
6251 
6252   const DataLayout &DL = getDataLayout();
6253 
6254   // The key rationale for this optimization is that for some kinds of shift
6255   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6256   // within a finite number of iterations.  If the condition guarding the
6257   // backedge (in the sense that the backedge is taken if the condition is true)
6258   // is false for the value the shift recurrence stabilizes to, then we know
6259   // that the backedge is taken only a finite number of times.
6260 
6261   ConstantInt *StableValue = nullptr;
6262   switch (OpCode) {
6263   default:
6264     llvm_unreachable("Impossible case!");
6265 
6266   case Instruction::AShr: {
6267     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6268     // bitwidth(K) iterations.
6269     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6270     bool KnownZero, KnownOne;
6271     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6272                    Predecessor->getTerminator(), &DT);
6273     auto *Ty = cast<IntegerType>(RHS->getType());
6274     if (KnownZero)
6275       StableValue = ConstantInt::get(Ty, 0);
6276     else if (KnownOne)
6277       StableValue = ConstantInt::get(Ty, -1, true);
6278     else
6279       return getCouldNotCompute();
6280 
6281     break;
6282   }
6283   case Instruction::LShr:
6284   case Instruction::Shl:
6285     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6286     // stabilize to 0 in at most bitwidth(K) iterations.
6287     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6288     break;
6289   }
6290 
6291   auto *Result =
6292       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6293   assert(Result->getType()->isIntegerTy(1) &&
6294          "Otherwise cannot be an operand to a branch instruction");
6295 
6296   if (Result->isZeroValue()) {
6297     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6298     const SCEV *UpperBound =
6299         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6300     return ExitLimit(getCouldNotCompute(), UpperBound);
6301   }
6302 
6303   return getCouldNotCompute();
6304 }
6305 
6306 /// Return true if we can constant fold an instruction of the specified type,
6307 /// assuming that all operands were constants.
6308 static bool CanConstantFold(const Instruction *I) {
6309   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6310       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6311       isa<LoadInst>(I))
6312     return true;
6313 
6314   if (const CallInst *CI = dyn_cast<CallInst>(I))
6315     if (const Function *F = CI->getCalledFunction())
6316       return canConstantFoldCallTo(F);
6317   return false;
6318 }
6319 
6320 /// Determine whether this instruction can constant evolve within this loop
6321 /// assuming its operands can all constant evolve.
6322 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6323   // An instruction outside of the loop can't be derived from a loop PHI.
6324   if (!L->contains(I)) return false;
6325 
6326   if (isa<PHINode>(I)) {
6327     // We don't currently keep track of the control flow needed to evaluate
6328     // PHIs, so we cannot handle PHIs inside of loops.
6329     return L->getHeader() == I->getParent();
6330   }
6331 
6332   // If we won't be able to constant fold this expression even if the operands
6333   // are constants, bail early.
6334   return CanConstantFold(I);
6335 }
6336 
6337 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6338 /// recursing through each instruction operand until reaching a loop header phi.
6339 static PHINode *
6340 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6341                                DenseMap<Instruction *, PHINode *> &PHIMap) {
6342 
6343   // Otherwise, we can evaluate this instruction if all of its operands are
6344   // constant or derived from a PHI node themselves.
6345   PHINode *PHI = nullptr;
6346   for (Value *Op : UseInst->operands()) {
6347     if (isa<Constant>(Op)) continue;
6348 
6349     Instruction *OpInst = dyn_cast<Instruction>(Op);
6350     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6351 
6352     PHINode *P = dyn_cast<PHINode>(OpInst);
6353     if (!P)
6354       // If this operand is already visited, reuse the prior result.
6355       // We may have P != PHI if this is the deepest point at which the
6356       // inconsistent paths meet.
6357       P = PHIMap.lookup(OpInst);
6358     if (!P) {
6359       // Recurse and memoize the results, whether a phi is found or not.
6360       // This recursive call invalidates pointers into PHIMap.
6361       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6362       PHIMap[OpInst] = P;
6363     }
6364     if (!P)
6365       return nullptr;  // Not evolving from PHI
6366     if (PHI && PHI != P)
6367       return nullptr;  // Evolving from multiple different PHIs.
6368     PHI = P;
6369   }
6370   // This is a expression evolving from a constant PHI!
6371   return PHI;
6372 }
6373 
6374 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6375 /// in the loop that V is derived from.  We allow arbitrary operations along the
6376 /// way, but the operands of an operation must either be constants or a value
6377 /// derived from a constant PHI.  If this expression does not fit with these
6378 /// constraints, return null.
6379 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6380   Instruction *I = dyn_cast<Instruction>(V);
6381   if (!I || !canConstantEvolve(I, L)) return nullptr;
6382 
6383   if (PHINode *PN = dyn_cast<PHINode>(I))
6384     return PN;
6385 
6386   // Record non-constant instructions contained by the loop.
6387   DenseMap<Instruction *, PHINode *> PHIMap;
6388   return getConstantEvolvingPHIOperands(I, L, PHIMap);
6389 }
6390 
6391 /// EvaluateExpression - Given an expression that passes the
6392 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6393 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6394 /// reason, return null.
6395 static Constant *EvaluateExpression(Value *V, const Loop *L,
6396                                     DenseMap<Instruction *, Constant *> &Vals,
6397                                     const DataLayout &DL,
6398                                     const TargetLibraryInfo *TLI) {
6399   // Convenient constant check, but redundant for recursive calls.
6400   if (Constant *C = dyn_cast<Constant>(V)) return C;
6401   Instruction *I = dyn_cast<Instruction>(V);
6402   if (!I) return nullptr;
6403 
6404   if (Constant *C = Vals.lookup(I)) return C;
6405 
6406   // An instruction inside the loop depends on a value outside the loop that we
6407   // weren't given a mapping for, or a value such as a call inside the loop.
6408   if (!canConstantEvolve(I, L)) return nullptr;
6409 
6410   // An unmapped PHI can be due to a branch or another loop inside this loop,
6411   // or due to this not being the initial iteration through a loop where we
6412   // couldn't compute the evolution of this particular PHI last time.
6413   if (isa<PHINode>(I)) return nullptr;
6414 
6415   std::vector<Constant*> Operands(I->getNumOperands());
6416 
6417   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6418     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6419     if (!Operand) {
6420       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6421       if (!Operands[i]) return nullptr;
6422       continue;
6423     }
6424     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6425     Vals[Operand] = C;
6426     if (!C) return nullptr;
6427     Operands[i] = C;
6428   }
6429 
6430   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6431     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6432                                            Operands[1], DL, TLI);
6433   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6434     if (!LI->isVolatile())
6435       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6436   }
6437   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6438 }
6439 
6440 
6441 // If every incoming value to PN except the one for BB is a specific Constant,
6442 // return that, else return nullptr.
6443 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6444   Constant *IncomingVal = nullptr;
6445 
6446   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6447     if (PN->getIncomingBlock(i) == BB)
6448       continue;
6449 
6450     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6451     if (!CurrentVal)
6452       return nullptr;
6453 
6454     if (IncomingVal != CurrentVal) {
6455       if (IncomingVal)
6456         return nullptr;
6457       IncomingVal = CurrentVal;
6458     }
6459   }
6460 
6461   return IncomingVal;
6462 }
6463 
6464 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6465 /// in the header of its containing loop, we know the loop executes a
6466 /// constant number of times, and the PHI node is just a recurrence
6467 /// involving constants, fold it.
6468 Constant *
6469 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6470                                                    const APInt &BEs,
6471                                                    const Loop *L) {
6472   auto I = ConstantEvolutionLoopExitValue.find(PN);
6473   if (I != ConstantEvolutionLoopExitValue.end())
6474     return I->second;
6475 
6476   if (BEs.ugt(MaxBruteForceIterations))
6477     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6478 
6479   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6480 
6481   DenseMap<Instruction *, Constant *> CurrentIterVals;
6482   BasicBlock *Header = L->getHeader();
6483   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6484 
6485   BasicBlock *Latch = L->getLoopLatch();
6486   if (!Latch)
6487     return nullptr;
6488 
6489   for (auto &I : *Header) {
6490     PHINode *PHI = dyn_cast<PHINode>(&I);
6491     if (!PHI) break;
6492     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6493     if (!StartCST) continue;
6494     CurrentIterVals[PHI] = StartCST;
6495   }
6496   if (!CurrentIterVals.count(PN))
6497     return RetVal = nullptr;
6498 
6499   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6500 
6501   // Execute the loop symbolically to determine the exit value.
6502   if (BEs.getActiveBits() >= 32)
6503     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6504 
6505   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6506   unsigned IterationNum = 0;
6507   const DataLayout &DL = getDataLayout();
6508   for (; ; ++IterationNum) {
6509     if (IterationNum == NumIterations)
6510       return RetVal = CurrentIterVals[PN];  // Got exit value!
6511 
6512     // Compute the value of the PHIs for the next iteration.
6513     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6514     DenseMap<Instruction *, Constant *> NextIterVals;
6515     Constant *NextPHI =
6516         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6517     if (!NextPHI)
6518       return nullptr;        // Couldn't evaluate!
6519     NextIterVals[PN] = NextPHI;
6520 
6521     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6522 
6523     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6524     // cease to be able to evaluate one of them or if they stop evolving,
6525     // because that doesn't necessarily prevent us from computing PN.
6526     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6527     for (const auto &I : CurrentIterVals) {
6528       PHINode *PHI = dyn_cast<PHINode>(I.first);
6529       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6530       PHIsToCompute.emplace_back(PHI, I.second);
6531     }
6532     // We use two distinct loops because EvaluateExpression may invalidate any
6533     // iterators into CurrentIterVals.
6534     for (const auto &I : PHIsToCompute) {
6535       PHINode *PHI = I.first;
6536       Constant *&NextPHI = NextIterVals[PHI];
6537       if (!NextPHI) {   // Not already computed.
6538         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6539         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6540       }
6541       if (NextPHI != I.second)
6542         StoppedEvolving = false;
6543     }
6544 
6545     // If all entries in CurrentIterVals == NextIterVals then we can stop
6546     // iterating, the loop can't continue to change.
6547     if (StoppedEvolving)
6548       return RetVal = CurrentIterVals[PN];
6549 
6550     CurrentIterVals.swap(NextIterVals);
6551   }
6552 }
6553 
6554 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6555                                                           Value *Cond,
6556                                                           bool ExitWhen) {
6557   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6558   if (!PN) return getCouldNotCompute();
6559 
6560   // If the loop is canonicalized, the PHI will have exactly two entries.
6561   // That's the only form we support here.
6562   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6563 
6564   DenseMap<Instruction *, Constant *> CurrentIterVals;
6565   BasicBlock *Header = L->getHeader();
6566   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6567 
6568   BasicBlock *Latch = L->getLoopLatch();
6569   assert(Latch && "Should follow from NumIncomingValues == 2!");
6570 
6571   for (auto &I : *Header) {
6572     PHINode *PHI = dyn_cast<PHINode>(&I);
6573     if (!PHI)
6574       break;
6575     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6576     if (!StartCST) continue;
6577     CurrentIterVals[PHI] = StartCST;
6578   }
6579   if (!CurrentIterVals.count(PN))
6580     return getCouldNotCompute();
6581 
6582   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6583   // the loop symbolically to determine when the condition gets a value of
6584   // "ExitWhen".
6585   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6586   const DataLayout &DL = getDataLayout();
6587   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6588     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6589         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6590 
6591     // Couldn't symbolically evaluate.
6592     if (!CondVal) return getCouldNotCompute();
6593 
6594     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6595       ++NumBruteForceTripCountsComputed;
6596       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6597     }
6598 
6599     // Update all the PHI nodes for the next iteration.
6600     DenseMap<Instruction *, Constant *> NextIterVals;
6601 
6602     // Create a list of which PHIs we need to compute. We want to do this before
6603     // calling EvaluateExpression on them because that may invalidate iterators
6604     // into CurrentIterVals.
6605     SmallVector<PHINode *, 8> PHIsToCompute;
6606     for (const auto &I : CurrentIterVals) {
6607       PHINode *PHI = dyn_cast<PHINode>(I.first);
6608       if (!PHI || PHI->getParent() != Header) continue;
6609       PHIsToCompute.push_back(PHI);
6610     }
6611     for (PHINode *PHI : PHIsToCompute) {
6612       Constant *&NextPHI = NextIterVals[PHI];
6613       if (NextPHI) continue;    // Already computed!
6614 
6615       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6616       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6617     }
6618     CurrentIterVals.swap(NextIterVals);
6619   }
6620 
6621   // Too many iterations were needed to evaluate.
6622   return getCouldNotCompute();
6623 }
6624 
6625 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6626   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6627       ValuesAtScopes[V];
6628   // Check to see if we've folded this expression at this loop before.
6629   for (auto &LS : Values)
6630     if (LS.first == L)
6631       return LS.second ? LS.second : V;
6632 
6633   Values.emplace_back(L, nullptr);
6634 
6635   // Otherwise compute it.
6636   const SCEV *C = computeSCEVAtScope(V, L);
6637   for (auto &LS : reverse(ValuesAtScopes[V]))
6638     if (LS.first == L) {
6639       LS.second = C;
6640       break;
6641     }
6642   return C;
6643 }
6644 
6645 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6646 /// will return Constants for objects which aren't represented by a
6647 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6648 /// Returns NULL if the SCEV isn't representable as a Constant.
6649 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6650   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6651     case scCouldNotCompute:
6652     case scAddRecExpr:
6653       break;
6654     case scConstant:
6655       return cast<SCEVConstant>(V)->getValue();
6656     case scUnknown:
6657       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6658     case scSignExtend: {
6659       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6660       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6661         return ConstantExpr::getSExt(CastOp, SS->getType());
6662       break;
6663     }
6664     case scZeroExtend: {
6665       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6666       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6667         return ConstantExpr::getZExt(CastOp, SZ->getType());
6668       break;
6669     }
6670     case scTruncate: {
6671       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6672       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6673         return ConstantExpr::getTrunc(CastOp, ST->getType());
6674       break;
6675     }
6676     case scAddExpr: {
6677       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6678       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6679         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6680           unsigned AS = PTy->getAddressSpace();
6681           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6682           C = ConstantExpr::getBitCast(C, DestPtrTy);
6683         }
6684         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6685           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6686           if (!C2) return nullptr;
6687 
6688           // First pointer!
6689           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6690             unsigned AS = C2->getType()->getPointerAddressSpace();
6691             std::swap(C, C2);
6692             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6693             // The offsets have been converted to bytes.  We can add bytes to an
6694             // i8* by GEP with the byte count in the first index.
6695             C = ConstantExpr::getBitCast(C, DestPtrTy);
6696           }
6697 
6698           // Don't bother trying to sum two pointers. We probably can't
6699           // statically compute a load that results from it anyway.
6700           if (C2->getType()->isPointerTy())
6701             return nullptr;
6702 
6703           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6704             if (PTy->getElementType()->isStructTy())
6705               C2 = ConstantExpr::getIntegerCast(
6706                   C2, Type::getInt32Ty(C->getContext()), true);
6707             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6708           } else
6709             C = ConstantExpr::getAdd(C, C2);
6710         }
6711         return C;
6712       }
6713       break;
6714     }
6715     case scMulExpr: {
6716       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6717       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6718         // Don't bother with pointers at all.
6719         if (C->getType()->isPointerTy()) return nullptr;
6720         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6721           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6722           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6723           C = ConstantExpr::getMul(C, C2);
6724         }
6725         return C;
6726       }
6727       break;
6728     }
6729     case scUDivExpr: {
6730       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6731       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6732         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6733           if (LHS->getType() == RHS->getType())
6734             return ConstantExpr::getUDiv(LHS, RHS);
6735       break;
6736     }
6737     case scSMaxExpr:
6738     case scUMaxExpr:
6739       break; // TODO: smax, umax.
6740   }
6741   return nullptr;
6742 }
6743 
6744 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6745   if (isa<SCEVConstant>(V)) return V;
6746 
6747   // If this instruction is evolved from a constant-evolving PHI, compute the
6748   // exit value from the loop without using SCEVs.
6749   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
6750     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
6751       const Loop *LI = this->LI[I->getParent()];
6752       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
6753         if (PHINode *PN = dyn_cast<PHINode>(I))
6754           if (PN->getParent() == LI->getHeader()) {
6755             // Okay, there is no closed form solution for the PHI node.  Check
6756             // to see if the loop that contains it has a known backedge-taken
6757             // count.  If so, we may be able to force computation of the exit
6758             // value.
6759             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
6760             if (const SCEVConstant *BTCC =
6761                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
6762               // Okay, we know how many times the containing loop executes.  If
6763               // this is a constant evolving PHI node, get the final value at
6764               // the specified iteration number.
6765               Constant *RV =
6766                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
6767               if (RV) return getSCEV(RV);
6768             }
6769           }
6770 
6771       // Okay, this is an expression that we cannot symbolically evaluate
6772       // into a SCEV.  Check to see if it's possible to symbolically evaluate
6773       // the arguments into constants, and if so, try to constant propagate the
6774       // result.  This is particularly useful for computing loop exit values.
6775       if (CanConstantFold(I)) {
6776         SmallVector<Constant *, 4> Operands;
6777         bool MadeImprovement = false;
6778         for (Value *Op : I->operands()) {
6779           if (Constant *C = dyn_cast<Constant>(Op)) {
6780             Operands.push_back(C);
6781             continue;
6782           }
6783 
6784           // If any of the operands is non-constant and if they are
6785           // non-integer and non-pointer, don't even try to analyze them
6786           // with scev techniques.
6787           if (!isSCEVable(Op->getType()))
6788             return V;
6789 
6790           const SCEV *OrigV = getSCEV(Op);
6791           const SCEV *OpV = getSCEVAtScope(OrigV, L);
6792           MadeImprovement |= OrigV != OpV;
6793 
6794           Constant *C = BuildConstantFromSCEV(OpV);
6795           if (!C) return V;
6796           if (C->getType() != Op->getType())
6797             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6798                                                               Op->getType(),
6799                                                               false),
6800                                       C, Op->getType());
6801           Operands.push_back(C);
6802         }
6803 
6804         // Check to see if getSCEVAtScope actually made an improvement.
6805         if (MadeImprovement) {
6806           Constant *C = nullptr;
6807           const DataLayout &DL = getDataLayout();
6808           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
6809             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6810                                                 Operands[1], DL, &TLI);
6811           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6812             if (!LI->isVolatile())
6813               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6814           } else
6815             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
6816           if (!C) return V;
6817           return getSCEV(C);
6818         }
6819       }
6820     }
6821 
6822     // This is some other type of SCEVUnknown, just return it.
6823     return V;
6824   }
6825 
6826   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
6827     // Avoid performing the look-up in the common case where the specified
6828     // expression has no loop-variant portions.
6829     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
6830       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6831       if (OpAtScope != Comm->getOperand(i)) {
6832         // Okay, at least one of these operands is loop variant but might be
6833         // foldable.  Build a new instance of the folded commutative expression.
6834         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6835                                             Comm->op_begin()+i);
6836         NewOps.push_back(OpAtScope);
6837 
6838         for (++i; i != e; ++i) {
6839           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6840           NewOps.push_back(OpAtScope);
6841         }
6842         if (isa<SCEVAddExpr>(Comm))
6843           return getAddExpr(NewOps);
6844         if (isa<SCEVMulExpr>(Comm))
6845           return getMulExpr(NewOps);
6846         if (isa<SCEVSMaxExpr>(Comm))
6847           return getSMaxExpr(NewOps);
6848         if (isa<SCEVUMaxExpr>(Comm))
6849           return getUMaxExpr(NewOps);
6850         llvm_unreachable("Unknown commutative SCEV type!");
6851       }
6852     }
6853     // If we got here, all operands are loop invariant.
6854     return Comm;
6855   }
6856 
6857   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
6858     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6859     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
6860     if (LHS == Div->getLHS() && RHS == Div->getRHS())
6861       return Div;   // must be loop invariant
6862     return getUDivExpr(LHS, RHS);
6863   }
6864 
6865   // If this is a loop recurrence for a loop that does not contain L, then we
6866   // are dealing with the final value computed by the loop.
6867   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
6868     // First, attempt to evaluate each operand.
6869     // Avoid performing the look-up in the common case where the specified
6870     // expression has no loop-variant portions.
6871     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6872       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6873       if (OpAtScope == AddRec->getOperand(i))
6874         continue;
6875 
6876       // Okay, at least one of these operands is loop variant but might be
6877       // foldable.  Build a new instance of the folded commutative expression.
6878       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6879                                           AddRec->op_begin()+i);
6880       NewOps.push_back(OpAtScope);
6881       for (++i; i != e; ++i)
6882         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6883 
6884       const SCEV *FoldedRec =
6885         getAddRecExpr(NewOps, AddRec->getLoop(),
6886                       AddRec->getNoWrapFlags(SCEV::FlagNW));
6887       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
6888       // The addrec may be folded to a nonrecurrence, for example, if the
6889       // induction variable is multiplied by zero after constant folding. Go
6890       // ahead and return the folded value.
6891       if (!AddRec)
6892         return FoldedRec;
6893       break;
6894     }
6895 
6896     // If the scope is outside the addrec's loop, evaluate it by using the
6897     // loop exit value of the addrec.
6898     if (!AddRec->getLoop()->contains(L)) {
6899       // To evaluate this recurrence, we need to know how many times the AddRec
6900       // loop iterates.  Compute this now.
6901       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
6902       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
6903 
6904       // Then, evaluate the AddRec.
6905       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
6906     }
6907 
6908     return AddRec;
6909   }
6910 
6911   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
6912     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6913     if (Op == Cast->getOperand())
6914       return Cast;  // must be loop invariant
6915     return getZeroExtendExpr(Op, Cast->getType());
6916   }
6917 
6918   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
6919     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6920     if (Op == Cast->getOperand())
6921       return Cast;  // must be loop invariant
6922     return getSignExtendExpr(Op, Cast->getType());
6923   }
6924 
6925   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
6926     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6927     if (Op == Cast->getOperand())
6928       return Cast;  // must be loop invariant
6929     return getTruncateExpr(Op, Cast->getType());
6930   }
6931 
6932   llvm_unreachable("Unknown SCEV type!");
6933 }
6934 
6935 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
6936   return getSCEVAtScope(getSCEV(V), L);
6937 }
6938 
6939 /// Finds the minimum unsigned root of the following equation:
6940 ///
6941 ///     A * X = B (mod N)
6942 ///
6943 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6944 /// A and B isn't important.
6945 ///
6946 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
6947 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
6948                                                ScalarEvolution &SE) {
6949   uint32_t BW = A.getBitWidth();
6950   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6951   assert(A != 0 && "A must be non-zero.");
6952 
6953   // 1. D = gcd(A, N)
6954   //
6955   // The gcd of A and N may have only one prime factor: 2. The number of
6956   // trailing zeros in A is its multiplicity
6957   uint32_t Mult2 = A.countTrailingZeros();
6958   // D = 2^Mult2
6959 
6960   // 2. Check if B is divisible by D.
6961   //
6962   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6963   // is not less than multiplicity of this prime factor for D.
6964   if (B.countTrailingZeros() < Mult2)
6965     return SE.getCouldNotCompute();
6966 
6967   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6968   // modulo (N / D).
6969   //
6970   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
6971   // bit width during computations.
6972   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
6973   APInt Mod(BW + 1, 0);
6974   Mod.setBit(BW - Mult2);  // Mod = N / D
6975   APInt I = AD.multiplicativeInverse(Mod);
6976 
6977   // 4. Compute the minimum unsigned root of the equation:
6978   // I * (B / D) mod (N / D)
6979   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6980 
6981   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6982   // bits.
6983   return SE.getConstant(Result.trunc(BW));
6984 }
6985 
6986 /// Find the roots of the quadratic equation for the given quadratic chrec
6987 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
6988 /// two SCEVCouldNotCompute objects.
6989 ///
6990 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
6991 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
6992   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
6993   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6994   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6995   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
6996 
6997   // We currently can only solve this if the coefficients are constants.
6998   if (!LC || !MC || !NC)
6999     return None;
7000 
7001   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7002   const APInt &L = LC->getAPInt();
7003   const APInt &M = MC->getAPInt();
7004   const APInt &N = NC->getAPInt();
7005   APInt Two(BitWidth, 2);
7006   APInt Four(BitWidth, 4);
7007 
7008   {
7009     using namespace APIntOps;
7010     const APInt& C = L;
7011     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7012     // The B coefficient is M-N/2
7013     APInt B(M);
7014     B -= sdiv(N,Two);
7015 
7016     // The A coefficient is N/2
7017     APInt A(N.sdiv(Two));
7018 
7019     // Compute the B^2-4ac term.
7020     APInt SqrtTerm(B);
7021     SqrtTerm *= B;
7022     SqrtTerm -= Four * (A * C);
7023 
7024     if (SqrtTerm.isNegative()) {
7025       // The loop is provably infinite.
7026       return None;
7027     }
7028 
7029     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7030     // integer value or else APInt::sqrt() will assert.
7031     APInt SqrtVal(SqrtTerm.sqrt());
7032 
7033     // Compute the two solutions for the quadratic formula.
7034     // The divisions must be performed as signed divisions.
7035     APInt NegB(-B);
7036     APInt TwoA(A << 1);
7037     if (TwoA.isMinValue())
7038       return None;
7039 
7040     LLVMContext &Context = SE.getContext();
7041 
7042     ConstantInt *Solution1 =
7043       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7044     ConstantInt *Solution2 =
7045       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7046 
7047     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7048                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7049   } // end APIntOps namespace
7050 }
7051 
7052 ScalarEvolution::ExitLimit
7053 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7054                               bool AllowPredicates) {
7055 
7056   // This is only used for loops with a "x != y" exit test. The exit condition
7057   // is now expressed as a single expression, V = x-y. So the exit test is
7058   // effectively V != 0.  We know and take advantage of the fact that this
7059   // expression only being used in a comparison by zero context.
7060 
7061   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7062   // If the value is a constant
7063   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7064     // If the value is already zero, the branch will execute zero times.
7065     if (C->getValue()->isZero()) return C;
7066     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7067   }
7068 
7069   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7070   if (!AddRec && AllowPredicates)
7071     // Try to make this an AddRec using runtime tests, in the first X
7072     // iterations of this loop, where X is the SCEV expression found by the
7073     // algorithm below.
7074     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7075 
7076   if (!AddRec || AddRec->getLoop() != L)
7077     return getCouldNotCompute();
7078 
7079   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7080   // the quadratic equation to solve it.
7081   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7082     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7083       const SCEVConstant *R1 = Roots->first;
7084       const SCEVConstant *R2 = Roots->second;
7085       // Pick the smallest positive root value.
7086       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7087               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7088         if (!CB->getZExtValue())
7089           std::swap(R1, R2); // R1 is the minimum root now.
7090 
7091         // We can only use this value if the chrec ends up with an exact zero
7092         // value at this index.  When solving for "X*X != 5", for example, we
7093         // should not accept a root of 2.
7094         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7095         if (Val->isZero())
7096           return ExitLimit(R1, R1, Predicates); // We found a quadratic root!
7097       }
7098     }
7099     return getCouldNotCompute();
7100   }
7101 
7102   // Otherwise we can only handle this if it is affine.
7103   if (!AddRec->isAffine())
7104     return getCouldNotCompute();
7105 
7106   // If this is an affine expression, the execution count of this branch is
7107   // the minimum unsigned root of the following equation:
7108   //
7109   //     Start + Step*N = 0 (mod 2^BW)
7110   //
7111   // equivalent to:
7112   //
7113   //             Step*N = -Start (mod 2^BW)
7114   //
7115   // where BW is the common bit width of Start and Step.
7116 
7117   // Get the initial value for the loop.
7118   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7119   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7120 
7121   // For now we handle only constant steps.
7122   //
7123   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7124   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7125   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7126   // We have not yet seen any such cases.
7127   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7128   if (!StepC || StepC->getValue()->equalsInt(0))
7129     return getCouldNotCompute();
7130 
7131   // For positive steps (counting up until unsigned overflow):
7132   //   N = -Start/Step (as unsigned)
7133   // For negative steps (counting down to zero):
7134   //   N = Start/-Step
7135   // First compute the unsigned distance from zero in the direction of Step.
7136   bool CountDown = StepC->getAPInt().isNegative();
7137   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7138 
7139   // Handle unitary steps, which cannot wraparound.
7140   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7141   //   N = Distance (as unsigned)
7142   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7143     ConstantRange CR = getUnsignedRange(Start);
7144     const SCEV *MaxBECount;
7145     if (!CountDown && CR.getUnsignedMin().isMinValue())
7146       // When counting up, the worst starting value is 1, not 0.
7147       MaxBECount = CR.getUnsignedMax().isMinValue()
7148         ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7149         : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7150     else
7151       MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7152                                          : -CR.getUnsignedMin());
7153     return ExitLimit(Distance, MaxBECount, Predicates);
7154   }
7155 
7156   // As a special case, handle the instance where Step is a positive power of
7157   // two. In this case, determining whether Step divides Distance evenly can be
7158   // done by counting and comparing the number of trailing zeros of Step and
7159   // Distance.
7160   if (!CountDown) {
7161     const APInt &StepV = StepC->getAPInt();
7162     // StepV.isPowerOf2() returns true if StepV is an positive power of two.  It
7163     // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7164     // case is not handled as this code is guarded by !CountDown.
7165     if (StepV.isPowerOf2() &&
7166         GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7167       // Here we've constrained the equation to be of the form
7168       //
7169       //   2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W)  ... (0)
7170       //
7171       // where we're operating on a W bit wide integer domain and k is
7172       // non-negative.  The smallest unsigned solution for X is the trip count.
7173       //
7174       // (0) is equivalent to:
7175       //
7176       //      2^(N + k) * Distance' - 2^N * X = L * 2^W
7177       // <=>  2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7178       // <=>  2^k * Distance' - X = L * 2^(W - N)
7179       // <=>  2^k * Distance'     = L * 2^(W - N) + X    ... (1)
7180       //
7181       // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7182       // by 2^(W - N).
7183       //
7184       // <=>  X = 2^k * Distance' URem 2^(W - N)   ... (2)
7185       //
7186       // E.g. say we're solving
7187       //
7188       //   2 * Val = 2 * X  (in i8)   ... (3)
7189       //
7190       // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7191       //
7192       // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7193       // necessarily the smallest unsigned value of X that satisfies (3).
7194       // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7195       // is i8 1, not i8 -127
7196 
7197       const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7198 
7199       // Since SCEV does not have a URem node, we construct one using a truncate
7200       // and a zero extend.
7201 
7202       unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7203       auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7204       auto *WideTy = Distance->getType();
7205 
7206       const SCEV *Limit =
7207           getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7208       return ExitLimit(Limit, Limit, Predicates);
7209     }
7210   }
7211 
7212   // If the condition controls loop exit (the loop exits only if the expression
7213   // is true) and the addition is no-wrap we can use unsigned divide to
7214   // compute the backedge count.  In this case, the step may not divide the
7215   // distance, but we don't care because if the condition is "missed" the loop
7216   // will have undefined behavior due to wrapping.
7217   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7218       loopHasNoAbnormalExits(AddRec->getLoop())) {
7219     const SCEV *Exact =
7220         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7221     return ExitLimit(Exact, Exact, Predicates);
7222   }
7223 
7224   // Then, try to solve the above equation provided that Start is constant.
7225   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7226     const SCEV *E = SolveLinEquationWithOverflow(
7227         StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7228     return ExitLimit(E, E, Predicates);
7229   }
7230   return getCouldNotCompute();
7231 }
7232 
7233 ScalarEvolution::ExitLimit
7234 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7235   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7236   // handle them yet except for the trivial case.  This could be expanded in the
7237   // future as needed.
7238 
7239   // If the value is a constant, check to see if it is known to be non-zero
7240   // already.  If so, the backedge will execute zero times.
7241   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7242     if (!C->getValue()->isNullValue())
7243       return getZero(C->getType());
7244     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7245   }
7246 
7247   // We could implement others, but I really doubt anyone writes loops like
7248   // this, and if they did, they would already be constant folded.
7249   return getCouldNotCompute();
7250 }
7251 
7252 std::pair<BasicBlock *, BasicBlock *>
7253 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7254   // If the block has a unique predecessor, then there is no path from the
7255   // predecessor to the block that does not go through the direct edge
7256   // from the predecessor to the block.
7257   if (BasicBlock *Pred = BB->getSinglePredecessor())
7258     return {Pred, BB};
7259 
7260   // A loop's header is defined to be a block that dominates the loop.
7261   // If the header has a unique predecessor outside the loop, it must be
7262   // a block that has exactly one successor that can reach the loop.
7263   if (Loop *L = LI.getLoopFor(BB))
7264     return {L->getLoopPredecessor(), L->getHeader()};
7265 
7266   return {nullptr, nullptr};
7267 }
7268 
7269 /// SCEV structural equivalence is usually sufficient for testing whether two
7270 /// expressions are equal, however for the purposes of looking for a condition
7271 /// guarding a loop, it can be useful to be a little more general, since a
7272 /// front-end may have replicated the controlling expression.
7273 ///
7274 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7275   // Quick check to see if they are the same SCEV.
7276   if (A == B) return true;
7277 
7278   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7279     // Not all instructions that are "identical" compute the same value.  For
7280     // instance, two distinct alloca instructions allocating the same type are
7281     // identical and do not read memory; but compute distinct values.
7282     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7283   };
7284 
7285   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7286   // two different instructions with the same value. Check for this case.
7287   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7288     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7289       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7290         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7291           if (ComputesEqualValues(AI, BI))
7292             return true;
7293 
7294   // Otherwise assume they may have a different value.
7295   return false;
7296 }
7297 
7298 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7299                                            const SCEV *&LHS, const SCEV *&RHS,
7300                                            unsigned Depth) {
7301   bool Changed = false;
7302 
7303   // If we hit the max recursion limit bail out.
7304   if (Depth >= 3)
7305     return false;
7306 
7307   // Canonicalize a constant to the right side.
7308   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7309     // Check for both operands constant.
7310     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7311       if (ConstantExpr::getICmp(Pred,
7312                                 LHSC->getValue(),
7313                                 RHSC->getValue())->isNullValue())
7314         goto trivially_false;
7315       else
7316         goto trivially_true;
7317     }
7318     // Otherwise swap the operands to put the constant on the right.
7319     std::swap(LHS, RHS);
7320     Pred = ICmpInst::getSwappedPredicate(Pred);
7321     Changed = true;
7322   }
7323 
7324   // If we're comparing an addrec with a value which is loop-invariant in the
7325   // addrec's loop, put the addrec on the left. Also make a dominance check,
7326   // as both operands could be addrecs loop-invariant in each other's loop.
7327   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7328     const Loop *L = AR->getLoop();
7329     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7330       std::swap(LHS, RHS);
7331       Pred = ICmpInst::getSwappedPredicate(Pred);
7332       Changed = true;
7333     }
7334   }
7335 
7336   // If there's a constant operand, canonicalize comparisons with boundary
7337   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7338   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7339     const APInt &RA = RC->getAPInt();
7340     switch (Pred) {
7341     default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7342     case ICmpInst::ICMP_EQ:
7343     case ICmpInst::ICMP_NE:
7344       // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7345       if (!RA)
7346         if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7347           if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7348             if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7349                 ME->getOperand(0)->isAllOnesValue()) {
7350               RHS = AE->getOperand(1);
7351               LHS = ME->getOperand(1);
7352               Changed = true;
7353             }
7354       break;
7355     case ICmpInst::ICMP_UGE:
7356       if ((RA - 1).isMinValue()) {
7357         Pred = ICmpInst::ICMP_NE;
7358         RHS = getConstant(RA - 1);
7359         Changed = true;
7360         break;
7361       }
7362       if (RA.isMaxValue()) {
7363         Pred = ICmpInst::ICMP_EQ;
7364         Changed = true;
7365         break;
7366       }
7367       if (RA.isMinValue()) goto trivially_true;
7368 
7369       Pred = ICmpInst::ICMP_UGT;
7370       RHS = getConstant(RA - 1);
7371       Changed = true;
7372       break;
7373     case ICmpInst::ICMP_ULE:
7374       if ((RA + 1).isMaxValue()) {
7375         Pred = ICmpInst::ICMP_NE;
7376         RHS = getConstant(RA + 1);
7377         Changed = true;
7378         break;
7379       }
7380       if (RA.isMinValue()) {
7381         Pred = ICmpInst::ICMP_EQ;
7382         Changed = true;
7383         break;
7384       }
7385       if (RA.isMaxValue()) goto trivially_true;
7386 
7387       Pred = ICmpInst::ICMP_ULT;
7388       RHS = getConstant(RA + 1);
7389       Changed = true;
7390       break;
7391     case ICmpInst::ICMP_SGE:
7392       if ((RA - 1).isMinSignedValue()) {
7393         Pred = ICmpInst::ICMP_NE;
7394         RHS = getConstant(RA - 1);
7395         Changed = true;
7396         break;
7397       }
7398       if (RA.isMaxSignedValue()) {
7399         Pred = ICmpInst::ICMP_EQ;
7400         Changed = true;
7401         break;
7402       }
7403       if (RA.isMinSignedValue()) goto trivially_true;
7404 
7405       Pred = ICmpInst::ICMP_SGT;
7406       RHS = getConstant(RA - 1);
7407       Changed = true;
7408       break;
7409     case ICmpInst::ICMP_SLE:
7410       if ((RA + 1).isMaxSignedValue()) {
7411         Pred = ICmpInst::ICMP_NE;
7412         RHS = getConstant(RA + 1);
7413         Changed = true;
7414         break;
7415       }
7416       if (RA.isMinSignedValue()) {
7417         Pred = ICmpInst::ICMP_EQ;
7418         Changed = true;
7419         break;
7420       }
7421       if (RA.isMaxSignedValue()) goto trivially_true;
7422 
7423       Pred = ICmpInst::ICMP_SLT;
7424       RHS = getConstant(RA + 1);
7425       Changed = true;
7426       break;
7427     case ICmpInst::ICMP_UGT:
7428       if (RA.isMinValue()) {
7429         Pred = ICmpInst::ICMP_NE;
7430         Changed = true;
7431         break;
7432       }
7433       if ((RA + 1).isMaxValue()) {
7434         Pred = ICmpInst::ICMP_EQ;
7435         RHS = getConstant(RA + 1);
7436         Changed = true;
7437         break;
7438       }
7439       if (RA.isMaxValue()) goto trivially_false;
7440       break;
7441     case ICmpInst::ICMP_ULT:
7442       if (RA.isMaxValue()) {
7443         Pred = ICmpInst::ICMP_NE;
7444         Changed = true;
7445         break;
7446       }
7447       if ((RA - 1).isMinValue()) {
7448         Pred = ICmpInst::ICMP_EQ;
7449         RHS = getConstant(RA - 1);
7450         Changed = true;
7451         break;
7452       }
7453       if (RA.isMinValue()) goto trivially_false;
7454       break;
7455     case ICmpInst::ICMP_SGT:
7456       if (RA.isMinSignedValue()) {
7457         Pred = ICmpInst::ICMP_NE;
7458         Changed = true;
7459         break;
7460       }
7461       if ((RA + 1).isMaxSignedValue()) {
7462         Pred = ICmpInst::ICMP_EQ;
7463         RHS = getConstant(RA + 1);
7464         Changed = true;
7465         break;
7466       }
7467       if (RA.isMaxSignedValue()) goto trivially_false;
7468       break;
7469     case ICmpInst::ICMP_SLT:
7470       if (RA.isMaxSignedValue()) {
7471         Pred = ICmpInst::ICMP_NE;
7472         Changed = true;
7473         break;
7474       }
7475       if ((RA - 1).isMinSignedValue()) {
7476        Pred = ICmpInst::ICMP_EQ;
7477        RHS = getConstant(RA - 1);
7478         Changed = true;
7479        break;
7480       }
7481       if (RA.isMinSignedValue()) goto trivially_false;
7482       break;
7483     }
7484   }
7485 
7486   // Check for obvious equality.
7487   if (HasSameValue(LHS, RHS)) {
7488     if (ICmpInst::isTrueWhenEqual(Pred))
7489       goto trivially_true;
7490     if (ICmpInst::isFalseWhenEqual(Pred))
7491       goto trivially_false;
7492   }
7493 
7494   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7495   // adding or subtracting 1 from one of the operands.
7496   switch (Pred) {
7497   case ICmpInst::ICMP_SLE:
7498     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7499       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7500                        SCEV::FlagNSW);
7501       Pred = ICmpInst::ICMP_SLT;
7502       Changed = true;
7503     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7504       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7505                        SCEV::FlagNSW);
7506       Pred = ICmpInst::ICMP_SLT;
7507       Changed = true;
7508     }
7509     break;
7510   case ICmpInst::ICMP_SGE:
7511     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7512       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7513                        SCEV::FlagNSW);
7514       Pred = ICmpInst::ICMP_SGT;
7515       Changed = true;
7516     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7517       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7518                        SCEV::FlagNSW);
7519       Pred = ICmpInst::ICMP_SGT;
7520       Changed = true;
7521     }
7522     break;
7523   case ICmpInst::ICMP_ULE:
7524     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7525       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7526                        SCEV::FlagNUW);
7527       Pred = ICmpInst::ICMP_ULT;
7528       Changed = true;
7529     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7530       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7531       Pred = ICmpInst::ICMP_ULT;
7532       Changed = true;
7533     }
7534     break;
7535   case ICmpInst::ICMP_UGE:
7536     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7537       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7538       Pred = ICmpInst::ICMP_UGT;
7539       Changed = true;
7540     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7541       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7542                        SCEV::FlagNUW);
7543       Pred = ICmpInst::ICMP_UGT;
7544       Changed = true;
7545     }
7546     break;
7547   default:
7548     break;
7549   }
7550 
7551   // TODO: More simplifications are possible here.
7552 
7553   // Recursively simplify until we either hit a recursion limit or nothing
7554   // changes.
7555   if (Changed)
7556     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7557 
7558   return Changed;
7559 
7560 trivially_true:
7561   // Return 0 == 0.
7562   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7563   Pred = ICmpInst::ICMP_EQ;
7564   return true;
7565 
7566 trivially_false:
7567   // Return 0 != 0.
7568   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7569   Pred = ICmpInst::ICMP_NE;
7570   return true;
7571 }
7572 
7573 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7574   return getSignedRange(S).getSignedMax().isNegative();
7575 }
7576 
7577 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7578   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7579 }
7580 
7581 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7582   return !getSignedRange(S).getSignedMin().isNegative();
7583 }
7584 
7585 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7586   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7587 }
7588 
7589 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7590   return isKnownNegative(S) || isKnownPositive(S);
7591 }
7592 
7593 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7594                                        const SCEV *LHS, const SCEV *RHS) {
7595   // Canonicalize the inputs first.
7596   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7597 
7598   // If LHS or RHS is an addrec, check to see if the condition is true in
7599   // every iteration of the loop.
7600   // If LHS and RHS are both addrec, both conditions must be true in
7601   // every iteration of the loop.
7602   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7603   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7604   bool LeftGuarded = false;
7605   bool RightGuarded = false;
7606   if (LAR) {
7607     const Loop *L = LAR->getLoop();
7608     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7609         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7610       if (!RAR) return true;
7611       LeftGuarded = true;
7612     }
7613   }
7614   if (RAR) {
7615     const Loop *L = RAR->getLoop();
7616     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7617         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7618       if (!LAR) return true;
7619       RightGuarded = true;
7620     }
7621   }
7622   if (LeftGuarded && RightGuarded)
7623     return true;
7624 
7625   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7626     return true;
7627 
7628   // Otherwise see what can be done with known constant ranges.
7629   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7630 }
7631 
7632 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7633                                            ICmpInst::Predicate Pred,
7634                                            bool &Increasing) {
7635   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7636 
7637 #ifndef NDEBUG
7638   // Verify an invariant: inverting the predicate should turn a monotonically
7639   // increasing change to a monotonically decreasing one, and vice versa.
7640   bool IncreasingSwapped;
7641   bool ResultSwapped = isMonotonicPredicateImpl(
7642       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7643 
7644   assert(Result == ResultSwapped && "should be able to analyze both!");
7645   if (ResultSwapped)
7646     assert(Increasing == !IncreasingSwapped &&
7647            "monotonicity should flip as we flip the predicate");
7648 #endif
7649 
7650   return Result;
7651 }
7652 
7653 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7654                                                ICmpInst::Predicate Pred,
7655                                                bool &Increasing) {
7656 
7657   // A zero step value for LHS means the induction variable is essentially a
7658   // loop invariant value. We don't really depend on the predicate actually
7659   // flipping from false to true (for increasing predicates, and the other way
7660   // around for decreasing predicates), all we care about is that *if* the
7661   // predicate changes then it only changes from false to true.
7662   //
7663   // A zero step value in itself is not very useful, but there may be places
7664   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7665   // as general as possible.
7666 
7667   switch (Pred) {
7668   default:
7669     return false; // Conservative answer
7670 
7671   case ICmpInst::ICMP_UGT:
7672   case ICmpInst::ICMP_UGE:
7673   case ICmpInst::ICMP_ULT:
7674   case ICmpInst::ICMP_ULE:
7675     if (!LHS->hasNoUnsignedWrap())
7676       return false;
7677 
7678     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7679     return true;
7680 
7681   case ICmpInst::ICMP_SGT:
7682   case ICmpInst::ICMP_SGE:
7683   case ICmpInst::ICMP_SLT:
7684   case ICmpInst::ICMP_SLE: {
7685     if (!LHS->hasNoSignedWrap())
7686       return false;
7687 
7688     const SCEV *Step = LHS->getStepRecurrence(*this);
7689 
7690     if (isKnownNonNegative(Step)) {
7691       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7692       return true;
7693     }
7694 
7695     if (isKnownNonPositive(Step)) {
7696       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7697       return true;
7698     }
7699 
7700     return false;
7701   }
7702 
7703   }
7704 
7705   llvm_unreachable("switch has default clause!");
7706 }
7707 
7708 bool ScalarEvolution::isLoopInvariantPredicate(
7709     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7710     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7711     const SCEV *&InvariantRHS) {
7712 
7713   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7714   if (!isLoopInvariant(RHS, L)) {
7715     if (!isLoopInvariant(LHS, L))
7716       return false;
7717 
7718     std::swap(LHS, RHS);
7719     Pred = ICmpInst::getSwappedPredicate(Pred);
7720   }
7721 
7722   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7723   if (!ArLHS || ArLHS->getLoop() != L)
7724     return false;
7725 
7726   bool Increasing;
7727   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7728     return false;
7729 
7730   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7731   // true as the loop iterates, and the backedge is control dependent on
7732   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7733   //
7734   //   * if the predicate was false in the first iteration then the predicate
7735   //     is never evaluated again, since the loop exits without taking the
7736   //     backedge.
7737   //   * if the predicate was true in the first iteration then it will
7738   //     continue to be true for all future iterations since it is
7739   //     monotonically increasing.
7740   //
7741   // For both the above possibilities, we can replace the loop varying
7742   // predicate with its value on the first iteration of the loop (which is
7743   // loop invariant).
7744   //
7745   // A similar reasoning applies for a monotonically decreasing predicate, by
7746   // replacing true with false and false with true in the above two bullets.
7747 
7748   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7749 
7750   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7751     return false;
7752 
7753   InvariantPred = Pred;
7754   InvariantLHS = ArLHS->getStart();
7755   InvariantRHS = RHS;
7756   return true;
7757 }
7758 
7759 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7760     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7761   if (HasSameValue(LHS, RHS))
7762     return ICmpInst::isTrueWhenEqual(Pred);
7763 
7764   // This code is split out from isKnownPredicate because it is called from
7765   // within isLoopEntryGuardedByCond.
7766 
7767   auto CheckRanges =
7768       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7769     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7770         .contains(RangeLHS);
7771   };
7772 
7773   // The check at the top of the function catches the case where the values are
7774   // known to be equal.
7775   if (Pred == CmpInst::ICMP_EQ)
7776     return false;
7777 
7778   if (Pred == CmpInst::ICMP_NE)
7779     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7780            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7781            isKnownNonZero(getMinusSCEV(LHS, RHS));
7782 
7783   if (CmpInst::isSigned(Pred))
7784     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7785 
7786   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7787 }
7788 
7789 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7790                                                     const SCEV *LHS,
7791                                                     const SCEV *RHS) {
7792 
7793   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7794   // Return Y via OutY.
7795   auto MatchBinaryAddToConst =
7796       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7797              SCEV::NoWrapFlags ExpectedFlags) {
7798     const SCEV *NonConstOp, *ConstOp;
7799     SCEV::NoWrapFlags FlagsPresent;
7800 
7801     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7802         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7803       return false;
7804 
7805     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7806     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7807   };
7808 
7809   APInt C;
7810 
7811   switch (Pred) {
7812   default:
7813     break;
7814 
7815   case ICmpInst::ICMP_SGE:
7816     std::swap(LHS, RHS);
7817   case ICmpInst::ICMP_SLE:
7818     // X s<= (X + C)<nsw> if C >= 0
7819     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7820       return true;
7821 
7822     // (X + C)<nsw> s<= X if C <= 0
7823     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7824         !C.isStrictlyPositive())
7825       return true;
7826     break;
7827 
7828   case ICmpInst::ICMP_SGT:
7829     std::swap(LHS, RHS);
7830   case ICmpInst::ICMP_SLT:
7831     // X s< (X + C)<nsw> if C > 0
7832     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7833         C.isStrictlyPositive())
7834       return true;
7835 
7836     // (X + C)<nsw> s< X if C < 0
7837     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7838       return true;
7839     break;
7840   }
7841 
7842   return false;
7843 }
7844 
7845 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7846                                                    const SCEV *LHS,
7847                                                    const SCEV *RHS) {
7848   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7849     return false;
7850 
7851   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7852   // the stack can result in exponential time complexity.
7853   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7854 
7855   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7856   //
7857   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7858   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7859   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7860   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7861   // use isKnownPredicate later if needed.
7862   return isKnownNonNegative(RHS) &&
7863          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7864          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7865 }
7866 
7867 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7868                                         ICmpInst::Predicate Pred,
7869                                         const SCEV *LHS, const SCEV *RHS) {
7870   // No need to even try if we know the module has no guards.
7871   if (!HasGuards)
7872     return false;
7873 
7874   return any_of(*BB, [&](Instruction &I) {
7875     using namespace llvm::PatternMatch;
7876 
7877     Value *Condition;
7878     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7879                          m_Value(Condition))) &&
7880            isImpliedCond(Pred, LHS, RHS, Condition, false);
7881   });
7882 }
7883 
7884 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7885 /// protected by a conditional between LHS and RHS.  This is used to
7886 /// to eliminate casts.
7887 bool
7888 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7889                                              ICmpInst::Predicate Pred,
7890                                              const SCEV *LHS, const SCEV *RHS) {
7891   // Interpret a null as meaning no loop, where there is obviously no guard
7892   // (interprocedural conditions notwithstanding).
7893   if (!L) return true;
7894 
7895   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7896     return true;
7897 
7898   BasicBlock *Latch = L->getLoopLatch();
7899   if (!Latch)
7900     return false;
7901 
7902   BranchInst *LoopContinuePredicate =
7903     dyn_cast<BranchInst>(Latch->getTerminator());
7904   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7905       isImpliedCond(Pred, LHS, RHS,
7906                     LoopContinuePredicate->getCondition(),
7907                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7908     return true;
7909 
7910   // We don't want more than one activation of the following loops on the stack
7911   // -- that can lead to O(n!) time complexity.
7912   if (WalkingBEDominatingConds)
7913     return false;
7914 
7915   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7916 
7917   // See if we can exploit a trip count to prove the predicate.
7918   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7919   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7920   if (LatchBECount != getCouldNotCompute()) {
7921     // We know that Latch branches back to the loop header exactly
7922     // LatchBECount times.  This means the backdege condition at Latch is
7923     // equivalent to  "{0,+,1} u< LatchBECount".
7924     Type *Ty = LatchBECount->getType();
7925     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7926     const SCEV *LoopCounter =
7927       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7928     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7929                       LatchBECount))
7930       return true;
7931   }
7932 
7933   // Check conditions due to any @llvm.assume intrinsics.
7934   for (auto &AssumeVH : AC.assumptions()) {
7935     if (!AssumeVH)
7936       continue;
7937     auto *CI = cast<CallInst>(AssumeVH);
7938     if (!DT.dominates(CI, Latch->getTerminator()))
7939       continue;
7940 
7941     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7942       return true;
7943   }
7944 
7945   // If the loop is not reachable from the entry block, we risk running into an
7946   // infinite loop as we walk up into the dom tree.  These loops do not matter
7947   // anyway, so we just return a conservative answer when we see them.
7948   if (!DT.isReachableFromEntry(L->getHeader()))
7949     return false;
7950 
7951   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7952     return true;
7953 
7954   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7955        DTN != HeaderDTN; DTN = DTN->getIDom()) {
7956 
7957     assert(DTN && "should reach the loop header before reaching the root!");
7958 
7959     BasicBlock *BB = DTN->getBlock();
7960     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7961       return true;
7962 
7963     BasicBlock *PBB = BB->getSinglePredecessor();
7964     if (!PBB)
7965       continue;
7966 
7967     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7968     if (!ContinuePredicate || !ContinuePredicate->isConditional())
7969       continue;
7970 
7971     Value *Condition = ContinuePredicate->getCondition();
7972 
7973     // If we have an edge `E` within the loop body that dominates the only
7974     // latch, the condition guarding `E` also guards the backedge.  This
7975     // reasoning works only for loops with a single latch.
7976 
7977     BasicBlockEdge DominatingEdge(PBB, BB);
7978     if (DominatingEdge.isSingleEdge()) {
7979       // We're constructively (and conservatively) enumerating edges within the
7980       // loop body that dominate the latch.  The dominator tree better agree
7981       // with us on this:
7982       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
7983 
7984       if (isImpliedCond(Pred, LHS, RHS, Condition,
7985                         BB != ContinuePredicate->getSuccessor(0)))
7986         return true;
7987     }
7988   }
7989 
7990   return false;
7991 }
7992 
7993 bool
7994 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7995                                           ICmpInst::Predicate Pred,
7996                                           const SCEV *LHS, const SCEV *RHS) {
7997   // Interpret a null as meaning no loop, where there is obviously no guard
7998   // (interprocedural conditions notwithstanding).
7999   if (!L) return false;
8000 
8001   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8002     return true;
8003 
8004   // Starting at the loop predecessor, climb up the predecessor chain, as long
8005   // as there are predecessors that can be found that have unique successors
8006   // leading to the original header.
8007   for (std::pair<BasicBlock *, BasicBlock *>
8008          Pair(L->getLoopPredecessor(), L->getHeader());
8009        Pair.first;
8010        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8011 
8012     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8013       return true;
8014 
8015     BranchInst *LoopEntryPredicate =
8016       dyn_cast<BranchInst>(Pair.first->getTerminator());
8017     if (!LoopEntryPredicate ||
8018         LoopEntryPredicate->isUnconditional())
8019       continue;
8020 
8021     if (isImpliedCond(Pred, LHS, RHS,
8022                       LoopEntryPredicate->getCondition(),
8023                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8024       return true;
8025   }
8026 
8027   // Check conditions due to any @llvm.assume intrinsics.
8028   for (auto &AssumeVH : AC.assumptions()) {
8029     if (!AssumeVH)
8030       continue;
8031     auto *CI = cast<CallInst>(AssumeVH);
8032     if (!DT.dominates(CI, L->getHeader()))
8033       continue;
8034 
8035     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8036       return true;
8037   }
8038 
8039   return false;
8040 }
8041 
8042 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8043                                     const SCEV *LHS, const SCEV *RHS,
8044                                     Value *FoundCondValue,
8045                                     bool Inverse) {
8046   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8047     return false;
8048 
8049   auto ClearOnExit =
8050       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8051 
8052   // Recursively handle And and Or conditions.
8053   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8054     if (BO->getOpcode() == Instruction::And) {
8055       if (!Inverse)
8056         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8057                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8058     } else if (BO->getOpcode() == Instruction::Or) {
8059       if (Inverse)
8060         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8061                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8062     }
8063   }
8064 
8065   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8066   if (!ICI) return false;
8067 
8068   // Now that we found a conditional branch that dominates the loop or controls
8069   // the loop latch. Check to see if it is the comparison we are looking for.
8070   ICmpInst::Predicate FoundPred;
8071   if (Inverse)
8072     FoundPred = ICI->getInversePredicate();
8073   else
8074     FoundPred = ICI->getPredicate();
8075 
8076   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8077   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8078 
8079   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8080 }
8081 
8082 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8083                                     const SCEV *RHS,
8084                                     ICmpInst::Predicate FoundPred,
8085                                     const SCEV *FoundLHS,
8086                                     const SCEV *FoundRHS) {
8087   // Balance the types.
8088   if (getTypeSizeInBits(LHS->getType()) <
8089       getTypeSizeInBits(FoundLHS->getType())) {
8090     if (CmpInst::isSigned(Pred)) {
8091       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8092       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8093     } else {
8094       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8095       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8096     }
8097   } else if (getTypeSizeInBits(LHS->getType()) >
8098       getTypeSizeInBits(FoundLHS->getType())) {
8099     if (CmpInst::isSigned(FoundPred)) {
8100       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8101       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8102     } else {
8103       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8104       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8105     }
8106   }
8107 
8108   // Canonicalize the query to match the way instcombine will have
8109   // canonicalized the comparison.
8110   if (SimplifyICmpOperands(Pred, LHS, RHS))
8111     if (LHS == RHS)
8112       return CmpInst::isTrueWhenEqual(Pred);
8113   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8114     if (FoundLHS == FoundRHS)
8115       return CmpInst::isFalseWhenEqual(FoundPred);
8116 
8117   // Check to see if we can make the LHS or RHS match.
8118   if (LHS == FoundRHS || RHS == FoundLHS) {
8119     if (isa<SCEVConstant>(RHS)) {
8120       std::swap(FoundLHS, FoundRHS);
8121       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8122     } else {
8123       std::swap(LHS, RHS);
8124       Pred = ICmpInst::getSwappedPredicate(Pred);
8125     }
8126   }
8127 
8128   // Check whether the found predicate is the same as the desired predicate.
8129   if (FoundPred == Pred)
8130     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8131 
8132   // Check whether swapping the found predicate makes it the same as the
8133   // desired predicate.
8134   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8135     if (isa<SCEVConstant>(RHS))
8136       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8137     else
8138       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8139                                    RHS, LHS, FoundLHS, FoundRHS);
8140   }
8141 
8142   // Unsigned comparison is the same as signed comparison when both the operands
8143   // are non-negative.
8144   if (CmpInst::isUnsigned(FoundPred) &&
8145       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8146       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8147     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8148 
8149   // Check if we can make progress by sharpening ranges.
8150   if (FoundPred == ICmpInst::ICMP_NE &&
8151       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8152 
8153     const SCEVConstant *C = nullptr;
8154     const SCEV *V = nullptr;
8155 
8156     if (isa<SCEVConstant>(FoundLHS)) {
8157       C = cast<SCEVConstant>(FoundLHS);
8158       V = FoundRHS;
8159     } else {
8160       C = cast<SCEVConstant>(FoundRHS);
8161       V = FoundLHS;
8162     }
8163 
8164     // The guarding predicate tells us that C != V. If the known range
8165     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8166     // range we consider has to correspond to same signedness as the
8167     // predicate we're interested in folding.
8168 
8169     APInt Min = ICmpInst::isSigned(Pred) ?
8170         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8171 
8172     if (Min == C->getAPInt()) {
8173       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8174       // This is true even if (Min + 1) wraps around -- in case of
8175       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8176 
8177       APInt SharperMin = Min + 1;
8178 
8179       switch (Pred) {
8180         case ICmpInst::ICMP_SGE:
8181         case ICmpInst::ICMP_UGE:
8182           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8183           // RHS, we're done.
8184           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8185                                     getConstant(SharperMin)))
8186             return true;
8187 
8188         case ICmpInst::ICMP_SGT:
8189         case ICmpInst::ICMP_UGT:
8190           // We know from the range information that (V `Pred` Min ||
8191           // V == Min).  We know from the guarding condition that !(V
8192           // == Min).  This gives us
8193           //
8194           //       V `Pred` Min || V == Min && !(V == Min)
8195           //   =>  V `Pred` Min
8196           //
8197           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8198 
8199           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8200             return true;
8201 
8202         default:
8203           // No change
8204           break;
8205       }
8206     }
8207   }
8208 
8209   // Check whether the actual condition is beyond sufficient.
8210   if (FoundPred == ICmpInst::ICMP_EQ)
8211     if (ICmpInst::isTrueWhenEqual(Pred))
8212       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8213         return true;
8214   if (Pred == ICmpInst::ICMP_NE)
8215     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8216       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8217         return true;
8218 
8219   // Otherwise assume the worst.
8220   return false;
8221 }
8222 
8223 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8224                                      const SCEV *&L, const SCEV *&R,
8225                                      SCEV::NoWrapFlags &Flags) {
8226   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8227   if (!AE || AE->getNumOperands() != 2)
8228     return false;
8229 
8230   L = AE->getOperand(0);
8231   R = AE->getOperand(1);
8232   Flags = AE->getNoWrapFlags();
8233   return true;
8234 }
8235 
8236 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8237                                                            const SCEV *Less) {
8238   // We avoid subtracting expressions here because this function is usually
8239   // fairly deep in the call stack (i.e. is called many times).
8240 
8241   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8242     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8243     const auto *MAR = cast<SCEVAddRecExpr>(More);
8244 
8245     if (LAR->getLoop() != MAR->getLoop())
8246       return None;
8247 
8248     // We look at affine expressions only; not for correctness but to keep
8249     // getStepRecurrence cheap.
8250     if (!LAR->isAffine() || !MAR->isAffine())
8251       return None;
8252 
8253     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8254       return None;
8255 
8256     Less = LAR->getStart();
8257     More = MAR->getStart();
8258 
8259     // fall through
8260   }
8261 
8262   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8263     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8264     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8265     return M - L;
8266   }
8267 
8268   const SCEV *L, *R;
8269   SCEV::NoWrapFlags Flags;
8270   if (splitBinaryAdd(Less, L, R, Flags))
8271     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8272       if (R == More)
8273         return -(LC->getAPInt());
8274 
8275   if (splitBinaryAdd(More, L, R, Flags))
8276     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8277       if (R == Less)
8278         return LC->getAPInt();
8279 
8280   return None;
8281 }
8282 
8283 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8284     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8285     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8286   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8287     return false;
8288 
8289   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8290   if (!AddRecLHS)
8291     return false;
8292 
8293   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8294   if (!AddRecFoundLHS)
8295     return false;
8296 
8297   // We'd like to let SCEV reason about control dependencies, so we constrain
8298   // both the inequalities to be about add recurrences on the same loop.  This
8299   // way we can use isLoopEntryGuardedByCond later.
8300 
8301   const Loop *L = AddRecFoundLHS->getLoop();
8302   if (L != AddRecLHS->getLoop())
8303     return false;
8304 
8305   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8306   //
8307   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8308   //                                                                  ... (2)
8309   //
8310   // Informal proof for (2), assuming (1) [*]:
8311   //
8312   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8313   //
8314   // Then
8315   //
8316   //       FoundLHS s< FoundRHS s< INT_MIN - C
8317   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8318   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8319   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8320   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8321   // <=>  FoundLHS + C s< FoundRHS + C
8322   //
8323   // [*]: (1) can be proved by ruling out overflow.
8324   //
8325   // [**]: This can be proved by analyzing all the four possibilities:
8326   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8327   //    (A s>= 0, B s>= 0).
8328   //
8329   // Note:
8330   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8331   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8332   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8333   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8334   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8335   // C)".
8336 
8337   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8338   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8339   if (!LDiff || !RDiff || *LDiff != *RDiff)
8340     return false;
8341 
8342   if (LDiff->isMinValue())
8343     return true;
8344 
8345   APInt FoundRHSLimit;
8346 
8347   if (Pred == CmpInst::ICMP_ULT) {
8348     FoundRHSLimit = -(*RDiff);
8349   } else {
8350     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8351     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8352   }
8353 
8354   // Try to prove (1) or (2), as needed.
8355   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8356                                   getConstant(FoundRHSLimit));
8357 }
8358 
8359 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8360                                             const SCEV *LHS, const SCEV *RHS,
8361                                             const SCEV *FoundLHS,
8362                                             const SCEV *FoundRHS) {
8363   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8364     return true;
8365 
8366   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8367     return true;
8368 
8369   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8370                                      FoundLHS, FoundRHS) ||
8371          // ~x < ~y --> x > y
8372          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8373                                      getNotSCEV(FoundRHS),
8374                                      getNotSCEV(FoundLHS));
8375 }
8376 
8377 
8378 /// If Expr computes ~A, return A else return nullptr
8379 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8380   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8381   if (!Add || Add->getNumOperands() != 2 ||
8382       !Add->getOperand(0)->isAllOnesValue())
8383     return nullptr;
8384 
8385   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8386   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8387       !AddRHS->getOperand(0)->isAllOnesValue())
8388     return nullptr;
8389 
8390   return AddRHS->getOperand(1);
8391 }
8392 
8393 
8394 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8395 template<typename MaxExprType>
8396 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8397                               const SCEV *Candidate) {
8398   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8399   if (!MaxExpr) return false;
8400 
8401   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8402 }
8403 
8404 
8405 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8406 template<typename MaxExprType>
8407 static bool IsMinConsistingOf(ScalarEvolution &SE,
8408                               const SCEV *MaybeMinExpr,
8409                               const SCEV *Candidate) {
8410   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8411   if (!MaybeMaxExpr)
8412     return false;
8413 
8414   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8415 }
8416 
8417 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8418                                            ICmpInst::Predicate Pred,
8419                                            const SCEV *LHS, const SCEV *RHS) {
8420 
8421   // If both sides are affine addrecs for the same loop, with equal
8422   // steps, and we know the recurrences don't wrap, then we only
8423   // need to check the predicate on the starting values.
8424 
8425   if (!ICmpInst::isRelational(Pred))
8426     return false;
8427 
8428   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8429   if (!LAR)
8430     return false;
8431   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8432   if (!RAR)
8433     return false;
8434   if (LAR->getLoop() != RAR->getLoop())
8435     return false;
8436   if (!LAR->isAffine() || !RAR->isAffine())
8437     return false;
8438 
8439   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8440     return false;
8441 
8442   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8443                          SCEV::FlagNSW : SCEV::FlagNUW;
8444   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8445     return false;
8446 
8447   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8448 }
8449 
8450 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8451 /// expression?
8452 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8453                                         ICmpInst::Predicate Pred,
8454                                         const SCEV *LHS, const SCEV *RHS) {
8455   switch (Pred) {
8456   default:
8457     return false;
8458 
8459   case ICmpInst::ICMP_SGE:
8460     std::swap(LHS, RHS);
8461     LLVM_FALLTHROUGH;
8462   case ICmpInst::ICMP_SLE:
8463     return
8464       // min(A, ...) <= A
8465       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8466       // A <= max(A, ...)
8467       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8468 
8469   case ICmpInst::ICMP_UGE:
8470     std::swap(LHS, RHS);
8471     LLVM_FALLTHROUGH;
8472   case ICmpInst::ICMP_ULE:
8473     return
8474       // min(A, ...) <= A
8475       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8476       // A <= max(A, ...)
8477       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8478   }
8479 
8480   llvm_unreachable("covered switch fell through?!");
8481 }
8482 
8483 bool
8484 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8485                                              const SCEV *LHS, const SCEV *RHS,
8486                                              const SCEV *FoundLHS,
8487                                              const SCEV *FoundRHS) {
8488   auto IsKnownPredicateFull =
8489       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8490     return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8491            IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8492            IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8493            isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8494   };
8495 
8496   switch (Pred) {
8497   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8498   case ICmpInst::ICMP_EQ:
8499   case ICmpInst::ICMP_NE:
8500     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8501       return true;
8502     break;
8503   case ICmpInst::ICMP_SLT:
8504   case ICmpInst::ICMP_SLE:
8505     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8506         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8507       return true;
8508     break;
8509   case ICmpInst::ICMP_SGT:
8510   case ICmpInst::ICMP_SGE:
8511     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8512         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8513       return true;
8514     break;
8515   case ICmpInst::ICMP_ULT:
8516   case ICmpInst::ICMP_ULE:
8517     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8518         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8519       return true;
8520     break;
8521   case ICmpInst::ICMP_UGT:
8522   case ICmpInst::ICMP_UGE:
8523     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8524         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8525       return true;
8526     break;
8527   }
8528 
8529   return false;
8530 }
8531 
8532 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8533                                                      const SCEV *LHS,
8534                                                      const SCEV *RHS,
8535                                                      const SCEV *FoundLHS,
8536                                                      const SCEV *FoundRHS) {
8537   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8538     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8539     // reduce the compile time impact of this optimization.
8540     return false;
8541 
8542   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8543   if (!Addend)
8544     return false;
8545 
8546   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8547 
8548   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8549   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8550   ConstantRange FoundLHSRange =
8551       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8552 
8553   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8554   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8555 
8556   // We can also compute the range of values for `LHS` that satisfy the
8557   // consequent, "`LHS` `Pred` `RHS`":
8558   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8559   ConstantRange SatisfyingLHSRange =
8560       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8561 
8562   // The antecedent implies the consequent if every value of `LHS` that
8563   // satisfies the antecedent also satisfies the consequent.
8564   return SatisfyingLHSRange.contains(LHSRange);
8565 }
8566 
8567 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8568                                          bool IsSigned, bool NoWrap) {
8569   assert(isKnownPositive(Stride) && "Positive stride expected!");
8570 
8571   if (NoWrap) return false;
8572 
8573   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8574   const SCEV *One = getOne(Stride->getType());
8575 
8576   if (IsSigned) {
8577     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8578     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8579     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8580                                 .getSignedMax();
8581 
8582     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8583     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8584   }
8585 
8586   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8587   APInt MaxValue = APInt::getMaxValue(BitWidth);
8588   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8589                               .getUnsignedMax();
8590 
8591   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8592   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8593 }
8594 
8595 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8596                                          bool IsSigned, bool NoWrap) {
8597   if (NoWrap) return false;
8598 
8599   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8600   const SCEV *One = getOne(Stride->getType());
8601 
8602   if (IsSigned) {
8603     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8604     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8605     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8606                                .getSignedMax();
8607 
8608     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8609     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8610   }
8611 
8612   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8613   APInt MinValue = APInt::getMinValue(BitWidth);
8614   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8615                             .getUnsignedMax();
8616 
8617   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8618   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8619 }
8620 
8621 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8622                                             bool Equality) {
8623   const SCEV *One = getOne(Step->getType());
8624   Delta = Equality ? getAddExpr(Delta, Step)
8625                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8626   return getUDivExpr(Delta, Step);
8627 }
8628 
8629 ScalarEvolution::ExitLimit
8630 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8631                                   const Loop *L, bool IsSigned,
8632                                   bool ControlsExit, bool AllowPredicates) {
8633   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8634   // We handle only IV < Invariant
8635   if (!isLoopInvariant(RHS, L))
8636     return getCouldNotCompute();
8637 
8638   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8639   bool PredicatedIV = false;
8640 
8641   if (!IV && AllowPredicates) {
8642     // Try to make this an AddRec using runtime tests, in the first X
8643     // iterations of this loop, where X is the SCEV expression found by the
8644     // algorithm below.
8645     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8646     PredicatedIV = true;
8647   }
8648 
8649   // Avoid weird loops
8650   if (!IV || IV->getLoop() != L || !IV->isAffine())
8651     return getCouldNotCompute();
8652 
8653   bool NoWrap = ControlsExit &&
8654                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8655 
8656   const SCEV *Stride = IV->getStepRecurrence(*this);
8657 
8658   bool PositiveStride = isKnownPositive(Stride);
8659 
8660   // Avoid negative or zero stride values.
8661   if (!PositiveStride) {
8662     // We can compute the correct backedge taken count for loops with unknown
8663     // strides if we can prove that the loop is not an infinite loop with side
8664     // effects. Here's the loop structure we are trying to handle -
8665     //
8666     // i = start
8667     // do {
8668     //   A[i] = i;
8669     //   i += s;
8670     // } while (i < end);
8671     //
8672     // The backedge taken count for such loops is evaluated as -
8673     // (max(end, start + stride) - start - 1) /u stride
8674     //
8675     // The additional preconditions that we need to check to prove correctness
8676     // of the above formula is as follows -
8677     //
8678     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8679     //    NoWrap flag).
8680     // b) loop is single exit with no side effects.
8681     //
8682     //
8683     // Precondition a) implies that if the stride is negative, this is a single
8684     // trip loop. The backedge taken count formula reduces to zero in this case.
8685     //
8686     // Precondition b) implies that the unknown stride cannot be zero otherwise
8687     // we have UB.
8688     //
8689     // The positive stride case is the same as isKnownPositive(Stride) returning
8690     // true (original behavior of the function).
8691     //
8692     // We want to make sure that the stride is truly unknown as there are edge
8693     // cases where ScalarEvolution propagates no wrap flags to the
8694     // post-increment/decrement IV even though the increment/decrement operation
8695     // itself is wrapping. The computed backedge taken count may be wrong in
8696     // such cases. This is prevented by checking that the stride is not known to
8697     // be either positive or non-positive. For example, no wrap flags are
8698     // propagated to the post-increment IV of this loop with a trip count of 2 -
8699     //
8700     // unsigned char i;
8701     // for(i=127; i<128; i+=129)
8702     //   A[i] = i;
8703     //
8704     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8705         !loopHasNoSideEffects(L))
8706       return getCouldNotCompute();
8707 
8708   } else if (!Stride->isOne() &&
8709              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8710     // Avoid proven overflow cases: this will ensure that the backedge taken
8711     // count will not generate any unsigned overflow. Relaxed no-overflow
8712     // conditions exploit NoWrapFlags, allowing to optimize in presence of
8713     // undefined behaviors like the case of C language.
8714     return getCouldNotCompute();
8715 
8716   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8717                                       : ICmpInst::ICMP_ULT;
8718   const SCEV *Start = IV->getStart();
8719   const SCEV *End = RHS;
8720   if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8721     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
8722 
8723   const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8724 
8725   APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8726                             : getUnsignedRange(Start).getUnsignedMin();
8727 
8728   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8729 
8730   APInt StrideForMaxBECount;
8731 
8732   if (PositiveStride)
8733     StrideForMaxBECount = IsSigned ? getSignedRange(Stride).getSignedMin()
8734                                    : getUnsignedRange(Stride).getUnsignedMin();
8735   else
8736     // Using a stride of 1 is safe when computing max backedge taken count for
8737     // a loop with unknown stride.
8738     StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8739 
8740   APInt Limit =
8741       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8742                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8743 
8744   // Although End can be a MAX expression we estimate MaxEnd considering only
8745   // the case End = RHS. This is safe because in the other case (End - Start)
8746   // is zero, leading to a zero maximum backedge taken count.
8747   APInt MaxEnd =
8748     IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8749              : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8750 
8751   const SCEV *MaxBECount;
8752   if (isa<SCEVConstant>(BECount))
8753     MaxBECount = BECount;
8754   else
8755     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8756                                 getConstant(StrideForMaxBECount), false);
8757 
8758   if (isa<SCEVCouldNotCompute>(MaxBECount))
8759     MaxBECount = BECount;
8760 
8761   return ExitLimit(BECount, MaxBECount, Predicates);
8762 }
8763 
8764 ScalarEvolution::ExitLimit
8765 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8766                                      const Loop *L, bool IsSigned,
8767                                      bool ControlsExit, bool AllowPredicates) {
8768   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8769   // We handle only IV > Invariant
8770   if (!isLoopInvariant(RHS, L))
8771     return getCouldNotCompute();
8772 
8773   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8774   if (!IV && AllowPredicates)
8775     // Try to make this an AddRec using runtime tests, in the first X
8776     // iterations of this loop, where X is the SCEV expression found by the
8777     // algorithm below.
8778     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8779 
8780   // Avoid weird loops
8781   if (!IV || IV->getLoop() != L || !IV->isAffine())
8782     return getCouldNotCompute();
8783 
8784   bool NoWrap = ControlsExit &&
8785                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8786 
8787   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8788 
8789   // Avoid negative or zero stride values
8790   if (!isKnownPositive(Stride))
8791     return getCouldNotCompute();
8792 
8793   // Avoid proven overflow cases: this will ensure that the backedge taken count
8794   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8795   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8796   // behaviors like the case of C language.
8797   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8798     return getCouldNotCompute();
8799 
8800   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8801                                       : ICmpInst::ICMP_UGT;
8802 
8803   const SCEV *Start = IV->getStart();
8804   const SCEV *End = RHS;
8805   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8806     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
8807 
8808   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8809 
8810   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8811                             : getUnsignedRange(Start).getUnsignedMax();
8812 
8813   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8814                              : getUnsignedRange(Stride).getUnsignedMin();
8815 
8816   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8817   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8818                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8819 
8820   // Although End can be a MIN expression we estimate MinEnd considering only
8821   // the case End = RHS. This is safe because in the other case (Start - End)
8822   // is zero, leading to a zero maximum backedge taken count.
8823   APInt MinEnd =
8824     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8825              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8826 
8827 
8828   const SCEV *MaxBECount = getCouldNotCompute();
8829   if (isa<SCEVConstant>(BECount))
8830     MaxBECount = BECount;
8831   else
8832     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8833                                 getConstant(MinStride), false);
8834 
8835   if (isa<SCEVCouldNotCompute>(MaxBECount))
8836     MaxBECount = BECount;
8837 
8838   return ExitLimit(BECount, MaxBECount, Predicates);
8839 }
8840 
8841 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
8842                                                     ScalarEvolution &SE) const {
8843   if (Range.isFullSet())  // Infinite loop.
8844     return SE.getCouldNotCompute();
8845 
8846   // If the start is a non-zero constant, shift the range to simplify things.
8847   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8848     if (!SC->getValue()->isZero()) {
8849       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8850       Operands[0] = SE.getZero(SC->getType());
8851       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8852                                              getNoWrapFlags(FlagNW));
8853       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8854         return ShiftedAddRec->getNumIterationsInRange(
8855             Range.subtract(SC->getAPInt()), SE);
8856       // This is strange and shouldn't happen.
8857       return SE.getCouldNotCompute();
8858     }
8859 
8860   // The only time we can solve this is when we have all constant indices.
8861   // Otherwise, we cannot determine the overflow conditions.
8862   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
8863     return SE.getCouldNotCompute();
8864 
8865   // Okay at this point we know that all elements of the chrec are constants and
8866   // that the start element is zero.
8867 
8868   // First check to see if the range contains zero.  If not, the first
8869   // iteration exits.
8870   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8871   if (!Range.contains(APInt(BitWidth, 0)))
8872     return SE.getZero(getType());
8873 
8874   if (isAffine()) {
8875     // If this is an affine expression then we have this situation:
8876     //   Solve {0,+,A} in Range  ===  Ax in Range
8877 
8878     // We know that zero is in the range.  If A is positive then we know that
8879     // the upper value of the range must be the first possible exit value.
8880     // If A is negative then the lower of the range is the last possible loop
8881     // value.  Also note that we already checked for a full range.
8882     APInt One(BitWidth,1);
8883     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
8884     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8885 
8886     // The exit value should be (End+A)/A.
8887     APInt ExitVal = (End + A).udiv(A);
8888     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8889 
8890     // Evaluate at the exit value.  If we really did fall out of the valid
8891     // range, then we computed our trip count, otherwise wrap around or other
8892     // things must have happened.
8893     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
8894     if (Range.contains(Val->getValue()))
8895       return SE.getCouldNotCompute();  // Something strange happened
8896 
8897     // Ensure that the previous value is in the range.  This is a sanity check.
8898     assert(Range.contains(
8899            EvaluateConstantChrecAtConstant(this,
8900            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
8901            "Linear scev computation is off in a bad way!");
8902     return SE.getConstant(ExitValue);
8903   } else if (isQuadratic()) {
8904     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8905     // quadratic equation to solve it.  To do this, we must frame our problem in
8906     // terms of figuring out when zero is crossed, instead of when
8907     // Range.getUpper() is crossed.
8908     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
8909     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
8910     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
8911 
8912     // Next, solve the constructed addrec
8913     if (auto Roots =
8914             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
8915       const SCEVConstant *R1 = Roots->first;
8916       const SCEVConstant *R2 = Roots->second;
8917       // Pick the smallest positive root value.
8918       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8919               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8920         if (!CB->getZExtValue())
8921           std::swap(R1, R2); // R1 is the minimum root now.
8922 
8923         // Make sure the root is not off by one.  The returned iteration should
8924         // not be in the range, but the previous one should be.  When solving
8925         // for "X*X < 5", for example, we should not return a root of 2.
8926         ConstantInt *R1Val =
8927             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
8928         if (Range.contains(R1Val->getValue())) {
8929           // The next iteration must be out of the range...
8930           ConstantInt *NextVal =
8931               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
8932 
8933           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8934           if (!Range.contains(R1Val->getValue()))
8935             return SE.getConstant(NextVal);
8936           return SE.getCouldNotCompute(); // Something strange happened
8937         }
8938 
8939         // If R1 was not in the range, then it is a good return value.  Make
8940         // sure that R1-1 WAS in the range though, just in case.
8941         ConstantInt *NextVal =
8942             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
8943         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8944         if (Range.contains(R1Val->getValue()))
8945           return R1;
8946         return SE.getCouldNotCompute(); // Something strange happened
8947       }
8948     }
8949   }
8950 
8951   return SE.getCouldNotCompute();
8952 }
8953 
8954 namespace {
8955 struct FindUndefs {
8956   bool Found;
8957   FindUndefs() : Found(false) {}
8958 
8959   bool follow(const SCEV *S) {
8960     if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8961       if (isa<UndefValue>(C->getValue()))
8962         Found = true;
8963     } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8964       if (isa<UndefValue>(C->getValue()))
8965         Found = true;
8966     }
8967 
8968     // Keep looking if we haven't found it yet.
8969     return !Found;
8970   }
8971   bool isDone() const {
8972     // Stop recursion if we have found an undef.
8973     return Found;
8974   }
8975 };
8976 }
8977 
8978 // Return true when S contains at least an undef value.
8979 static inline bool
8980 containsUndefs(const SCEV *S) {
8981   FindUndefs F;
8982   SCEVTraversal<FindUndefs> ST(F);
8983   ST.visitAll(S);
8984 
8985   return F.Found;
8986 }
8987 
8988 namespace {
8989 // Collect all steps of SCEV expressions.
8990 struct SCEVCollectStrides {
8991   ScalarEvolution &SE;
8992   SmallVectorImpl<const SCEV *> &Strides;
8993 
8994   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8995       : SE(SE), Strides(S) {}
8996 
8997   bool follow(const SCEV *S) {
8998     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8999       Strides.push_back(AR->getStepRecurrence(SE));
9000     return true;
9001   }
9002   bool isDone() const { return false; }
9003 };
9004 
9005 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9006 struct SCEVCollectTerms {
9007   SmallVectorImpl<const SCEV *> &Terms;
9008 
9009   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9010       : Terms(T) {}
9011 
9012   bool follow(const SCEV *S) {
9013     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
9014       if (!containsUndefs(S))
9015         Terms.push_back(S);
9016 
9017       // Stop recursion: once we collected a term, do not walk its operands.
9018       return false;
9019     }
9020 
9021     // Keep looking.
9022     return true;
9023   }
9024   bool isDone() const { return false; }
9025 };
9026 
9027 // Check if a SCEV contains an AddRecExpr.
9028 struct SCEVHasAddRec {
9029   bool &ContainsAddRec;
9030 
9031   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9032    ContainsAddRec = false;
9033   }
9034 
9035   bool follow(const SCEV *S) {
9036     if (isa<SCEVAddRecExpr>(S)) {
9037       ContainsAddRec = true;
9038 
9039       // Stop recursion: once we collected a term, do not walk its operands.
9040       return false;
9041     }
9042 
9043     // Keep looking.
9044     return true;
9045   }
9046   bool isDone() const { return false; }
9047 };
9048 
9049 // Find factors that are multiplied with an expression that (possibly as a
9050 // subexpression) contains an AddRecExpr. In the expression:
9051 //
9052 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9053 //
9054 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9055 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9056 // parameters as they form a product with an induction variable.
9057 //
9058 // This collector expects all array size parameters to be in the same MulExpr.
9059 // It might be necessary to later add support for collecting parameters that are
9060 // spread over different nested MulExpr.
9061 struct SCEVCollectAddRecMultiplies {
9062   SmallVectorImpl<const SCEV *> &Terms;
9063   ScalarEvolution &SE;
9064 
9065   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9066       : Terms(T), SE(SE) {}
9067 
9068   bool follow(const SCEV *S) {
9069     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9070       bool HasAddRec = false;
9071       SmallVector<const SCEV *, 0> Operands;
9072       for (auto Op : Mul->operands()) {
9073         if (isa<SCEVUnknown>(Op)) {
9074           Operands.push_back(Op);
9075         } else {
9076           bool ContainsAddRec;
9077           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9078           visitAll(Op, ContiansAddRec);
9079           HasAddRec |= ContainsAddRec;
9080         }
9081       }
9082       if (Operands.size() == 0)
9083         return true;
9084 
9085       if (!HasAddRec)
9086         return false;
9087 
9088       Terms.push_back(SE.getMulExpr(Operands));
9089       // Stop recursion: once we collected a term, do not walk its operands.
9090       return false;
9091     }
9092 
9093     // Keep looking.
9094     return true;
9095   }
9096   bool isDone() const { return false; }
9097 };
9098 }
9099 
9100 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9101 /// two places:
9102 ///   1) The strides of AddRec expressions.
9103 ///   2) Unknowns that are multiplied with AddRec expressions.
9104 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9105     SmallVectorImpl<const SCEV *> &Terms) {
9106   SmallVector<const SCEV *, 4> Strides;
9107   SCEVCollectStrides StrideCollector(*this, Strides);
9108   visitAll(Expr, StrideCollector);
9109 
9110   DEBUG({
9111       dbgs() << "Strides:\n";
9112       for (const SCEV *S : Strides)
9113         dbgs() << *S << "\n";
9114     });
9115 
9116   for (const SCEV *S : Strides) {
9117     SCEVCollectTerms TermCollector(Terms);
9118     visitAll(S, TermCollector);
9119   }
9120 
9121   DEBUG({
9122       dbgs() << "Terms:\n";
9123       for (const SCEV *T : Terms)
9124         dbgs() << *T << "\n";
9125     });
9126 
9127   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9128   visitAll(Expr, MulCollector);
9129 }
9130 
9131 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9132                                    SmallVectorImpl<const SCEV *> &Terms,
9133                                    SmallVectorImpl<const SCEV *> &Sizes) {
9134   int Last = Terms.size() - 1;
9135   const SCEV *Step = Terms[Last];
9136 
9137   // End of recursion.
9138   if (Last == 0) {
9139     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9140       SmallVector<const SCEV *, 2> Qs;
9141       for (const SCEV *Op : M->operands())
9142         if (!isa<SCEVConstant>(Op))
9143           Qs.push_back(Op);
9144 
9145       Step = SE.getMulExpr(Qs);
9146     }
9147 
9148     Sizes.push_back(Step);
9149     return true;
9150   }
9151 
9152   for (const SCEV *&Term : Terms) {
9153     // Normalize the terms before the next call to findArrayDimensionsRec.
9154     const SCEV *Q, *R;
9155     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9156 
9157     // Bail out when GCD does not evenly divide one of the terms.
9158     if (!R->isZero())
9159       return false;
9160 
9161     Term = Q;
9162   }
9163 
9164   // Remove all SCEVConstants.
9165   Terms.erase(
9166       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9167       Terms.end());
9168 
9169   if (Terms.size() > 0)
9170     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9171       return false;
9172 
9173   Sizes.push_back(Step);
9174   return true;
9175 }
9176 
9177 // Returns true when S contains at least a SCEVUnknown parameter.
9178 static inline bool
9179 containsParameters(const SCEV *S) {
9180   struct FindParameter {
9181     bool FoundParameter;
9182     FindParameter() : FoundParameter(false) {}
9183 
9184     bool follow(const SCEV *S) {
9185       if (isa<SCEVUnknown>(S)) {
9186         FoundParameter = true;
9187         // Stop recursion: we found a parameter.
9188         return false;
9189       }
9190       // Keep looking.
9191       return true;
9192     }
9193     bool isDone() const {
9194       // Stop recursion if we have found a parameter.
9195       return FoundParameter;
9196     }
9197   };
9198 
9199   FindParameter F;
9200   SCEVTraversal<FindParameter> ST(F);
9201   ST.visitAll(S);
9202 
9203   return F.FoundParameter;
9204 }
9205 
9206 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9207 static inline bool
9208 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9209   for (const SCEV *T : Terms)
9210     if (containsParameters(T))
9211       return true;
9212   return false;
9213 }
9214 
9215 // Return the number of product terms in S.
9216 static inline int numberOfTerms(const SCEV *S) {
9217   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9218     return Expr->getNumOperands();
9219   return 1;
9220 }
9221 
9222 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9223   if (isa<SCEVConstant>(T))
9224     return nullptr;
9225 
9226   if (isa<SCEVUnknown>(T))
9227     return T;
9228 
9229   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9230     SmallVector<const SCEV *, 2> Factors;
9231     for (const SCEV *Op : M->operands())
9232       if (!isa<SCEVConstant>(Op))
9233         Factors.push_back(Op);
9234 
9235     return SE.getMulExpr(Factors);
9236   }
9237 
9238   return T;
9239 }
9240 
9241 /// Return the size of an element read or written by Inst.
9242 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9243   Type *Ty;
9244   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9245     Ty = Store->getValueOperand()->getType();
9246   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9247     Ty = Load->getType();
9248   else
9249     return nullptr;
9250 
9251   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9252   return getSizeOfExpr(ETy, Ty);
9253 }
9254 
9255 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9256                                           SmallVectorImpl<const SCEV *> &Sizes,
9257                                           const SCEV *ElementSize) const {
9258   if (Terms.size() < 1 || !ElementSize)
9259     return;
9260 
9261   // Early return when Terms do not contain parameters: we do not delinearize
9262   // non parametric SCEVs.
9263   if (!containsParameters(Terms))
9264     return;
9265 
9266   DEBUG({
9267       dbgs() << "Terms:\n";
9268       for (const SCEV *T : Terms)
9269         dbgs() << *T << "\n";
9270     });
9271 
9272   // Remove duplicates.
9273   std::sort(Terms.begin(), Terms.end());
9274   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9275 
9276   // Put larger terms first.
9277   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9278     return numberOfTerms(LHS) > numberOfTerms(RHS);
9279   });
9280 
9281   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9282 
9283   // Try to divide all terms by the element size. If term is not divisible by
9284   // element size, proceed with the original term.
9285   for (const SCEV *&Term : Terms) {
9286     const SCEV *Q, *R;
9287     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9288     if (!Q->isZero())
9289       Term = Q;
9290   }
9291 
9292   SmallVector<const SCEV *, 4> NewTerms;
9293 
9294   // Remove constant factors.
9295   for (const SCEV *T : Terms)
9296     if (const SCEV *NewT = removeConstantFactors(SE, T))
9297       NewTerms.push_back(NewT);
9298 
9299   DEBUG({
9300       dbgs() << "Terms after sorting:\n";
9301       for (const SCEV *T : NewTerms)
9302         dbgs() << *T << "\n";
9303     });
9304 
9305   if (NewTerms.empty() ||
9306       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9307     Sizes.clear();
9308     return;
9309   }
9310 
9311   // The last element to be pushed into Sizes is the size of an element.
9312   Sizes.push_back(ElementSize);
9313 
9314   DEBUG({
9315       dbgs() << "Sizes:\n";
9316       for (const SCEV *S : Sizes)
9317         dbgs() << *S << "\n";
9318     });
9319 }
9320 
9321 void ScalarEvolution::computeAccessFunctions(
9322     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9323     SmallVectorImpl<const SCEV *> &Sizes) {
9324 
9325   // Early exit in case this SCEV is not an affine multivariate function.
9326   if (Sizes.empty())
9327     return;
9328 
9329   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9330     if (!AR->isAffine())
9331       return;
9332 
9333   const SCEV *Res = Expr;
9334   int Last = Sizes.size() - 1;
9335   for (int i = Last; i >= 0; i--) {
9336     const SCEV *Q, *R;
9337     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9338 
9339     DEBUG({
9340         dbgs() << "Res: " << *Res << "\n";
9341         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9342         dbgs() << "Res divided by Sizes[i]:\n";
9343         dbgs() << "Quotient: " << *Q << "\n";
9344         dbgs() << "Remainder: " << *R << "\n";
9345       });
9346 
9347     Res = Q;
9348 
9349     // Do not record the last subscript corresponding to the size of elements in
9350     // the array.
9351     if (i == Last) {
9352 
9353       // Bail out if the remainder is too complex.
9354       if (isa<SCEVAddRecExpr>(R)) {
9355         Subscripts.clear();
9356         Sizes.clear();
9357         return;
9358       }
9359 
9360       continue;
9361     }
9362 
9363     // Record the access function for the current subscript.
9364     Subscripts.push_back(R);
9365   }
9366 
9367   // Also push in last position the remainder of the last division: it will be
9368   // the access function of the innermost dimension.
9369   Subscripts.push_back(Res);
9370 
9371   std::reverse(Subscripts.begin(), Subscripts.end());
9372 
9373   DEBUG({
9374       dbgs() << "Subscripts:\n";
9375       for (const SCEV *S : Subscripts)
9376         dbgs() << *S << "\n";
9377     });
9378 }
9379 
9380 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9381 /// sizes of an array access. Returns the remainder of the delinearization that
9382 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9383 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9384 /// expressions in the stride and base of a SCEV corresponding to the
9385 /// computation of a GCD (greatest common divisor) of base and stride.  When
9386 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9387 ///
9388 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9389 ///
9390 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9391 ///
9392 ///    for (long i = 0; i < n; i++)
9393 ///      for (long j = 0; j < m; j++)
9394 ///        for (long k = 0; k < o; k++)
9395 ///          A[i][j][k] = 1.0;
9396 ///  }
9397 ///
9398 /// the delinearization input is the following AddRec SCEV:
9399 ///
9400 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9401 ///
9402 /// From this SCEV, we are able to say that the base offset of the access is %A
9403 /// because it appears as an offset that does not divide any of the strides in
9404 /// the loops:
9405 ///
9406 ///  CHECK: Base offset: %A
9407 ///
9408 /// and then SCEV->delinearize determines the size of some of the dimensions of
9409 /// the array as these are the multiples by which the strides are happening:
9410 ///
9411 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9412 ///
9413 /// Note that the outermost dimension remains of UnknownSize because there are
9414 /// no strides that would help identifying the size of the last dimension: when
9415 /// the array has been statically allocated, one could compute the size of that
9416 /// dimension by dividing the overall size of the array by the size of the known
9417 /// dimensions: %m * %o * 8.
9418 ///
9419 /// Finally delinearize provides the access functions for the array reference
9420 /// that does correspond to A[i][j][k] of the above C testcase:
9421 ///
9422 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9423 ///
9424 /// The testcases are checking the output of a function pass:
9425 /// DelinearizationPass that walks through all loads and stores of a function
9426 /// asking for the SCEV of the memory access with respect to all enclosing
9427 /// loops, calling SCEV->delinearize on that and printing the results.
9428 
9429 void ScalarEvolution::delinearize(const SCEV *Expr,
9430                                  SmallVectorImpl<const SCEV *> &Subscripts,
9431                                  SmallVectorImpl<const SCEV *> &Sizes,
9432                                  const SCEV *ElementSize) {
9433   // First step: collect parametric terms.
9434   SmallVector<const SCEV *, 4> Terms;
9435   collectParametricTerms(Expr, Terms);
9436 
9437   if (Terms.empty())
9438     return;
9439 
9440   // Second step: find subscript sizes.
9441   findArrayDimensions(Terms, Sizes, ElementSize);
9442 
9443   if (Sizes.empty())
9444     return;
9445 
9446   // Third step: compute the access functions for each subscript.
9447   computeAccessFunctions(Expr, Subscripts, Sizes);
9448 
9449   if (Subscripts.empty())
9450     return;
9451 
9452   DEBUG({
9453       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9454       dbgs() << "ArrayDecl[UnknownSize]";
9455       for (const SCEV *S : Sizes)
9456         dbgs() << "[" << *S << "]";
9457 
9458       dbgs() << "\nArrayRef";
9459       for (const SCEV *S : Subscripts)
9460         dbgs() << "[" << *S << "]";
9461       dbgs() << "\n";
9462     });
9463 }
9464 
9465 //===----------------------------------------------------------------------===//
9466 //                   SCEVCallbackVH Class Implementation
9467 //===----------------------------------------------------------------------===//
9468 
9469 void ScalarEvolution::SCEVCallbackVH::deleted() {
9470   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9471   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9472     SE->ConstantEvolutionLoopExitValue.erase(PN);
9473   SE->eraseValueFromMap(getValPtr());
9474   // this now dangles!
9475 }
9476 
9477 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9478   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9479 
9480   // Forget all the expressions associated with users of the old value,
9481   // so that future queries will recompute the expressions using the new
9482   // value.
9483   Value *Old = getValPtr();
9484   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9485   SmallPtrSet<User *, 8> Visited;
9486   while (!Worklist.empty()) {
9487     User *U = Worklist.pop_back_val();
9488     // Deleting the Old value will cause this to dangle. Postpone
9489     // that until everything else is done.
9490     if (U == Old)
9491       continue;
9492     if (!Visited.insert(U).second)
9493       continue;
9494     if (PHINode *PN = dyn_cast<PHINode>(U))
9495       SE->ConstantEvolutionLoopExitValue.erase(PN);
9496     SE->eraseValueFromMap(U);
9497     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9498   }
9499   // Delete the Old value.
9500   if (PHINode *PN = dyn_cast<PHINode>(Old))
9501     SE->ConstantEvolutionLoopExitValue.erase(PN);
9502   SE->eraseValueFromMap(Old);
9503   // this now dangles!
9504 }
9505 
9506 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9507   : CallbackVH(V), SE(se) {}
9508 
9509 //===----------------------------------------------------------------------===//
9510 //                   ScalarEvolution Class Implementation
9511 //===----------------------------------------------------------------------===//
9512 
9513 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9514                                  AssumptionCache &AC, DominatorTree &DT,
9515                                  LoopInfo &LI)
9516     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9517       CouldNotCompute(new SCEVCouldNotCompute()),
9518       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9519       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9520       FirstUnknown(nullptr) {
9521 
9522   // To use guards for proving predicates, we need to scan every instruction in
9523   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9524   // time if the IR does not actually contain any calls to
9525   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9526   //
9527   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9528   // to _add_ guards to the module when there weren't any before, and wants
9529   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9530   // efficient in lieu of being smart in that rather obscure case.
9531 
9532   auto *GuardDecl = F.getParent()->getFunction(
9533       Intrinsic::getName(Intrinsic::experimental_guard));
9534   HasGuards = GuardDecl && !GuardDecl->use_empty();
9535 }
9536 
9537 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9538     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9539       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9540       ValueExprMap(std::move(Arg.ValueExprMap)),
9541       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9542       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9543       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9544       PredicatedBackedgeTakenCounts(
9545           std::move(Arg.PredicatedBackedgeTakenCounts)),
9546       ConstantEvolutionLoopExitValue(
9547           std::move(Arg.ConstantEvolutionLoopExitValue)),
9548       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9549       LoopDispositions(std::move(Arg.LoopDispositions)),
9550       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9551       BlockDispositions(std::move(Arg.BlockDispositions)),
9552       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9553       SignedRanges(std::move(Arg.SignedRanges)),
9554       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9555       UniquePreds(std::move(Arg.UniquePreds)),
9556       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9557       FirstUnknown(Arg.FirstUnknown) {
9558   Arg.FirstUnknown = nullptr;
9559 }
9560 
9561 ScalarEvolution::~ScalarEvolution() {
9562   // Iterate through all the SCEVUnknown instances and call their
9563   // destructors, so that they release their references to their values.
9564   for (SCEVUnknown *U = FirstUnknown; U;) {
9565     SCEVUnknown *Tmp = U;
9566     U = U->Next;
9567     Tmp->~SCEVUnknown();
9568   }
9569   FirstUnknown = nullptr;
9570 
9571   ExprValueMap.clear();
9572   ValueExprMap.clear();
9573   HasRecMap.clear();
9574 
9575   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9576   // that a loop had multiple computable exits.
9577   for (auto &BTCI : BackedgeTakenCounts)
9578     BTCI.second.clear();
9579   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9580     BTCI.second.clear();
9581 
9582   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9583   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9584   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9585 }
9586 
9587 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9588   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9589 }
9590 
9591 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9592                           const Loop *L) {
9593   // Print all inner loops first
9594   for (Loop *I : *L)
9595     PrintLoopInfo(OS, SE, I);
9596 
9597   OS << "Loop ";
9598   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9599   OS << ": ";
9600 
9601   SmallVector<BasicBlock *, 8> ExitBlocks;
9602   L->getExitBlocks(ExitBlocks);
9603   if (ExitBlocks.size() != 1)
9604     OS << "<multiple exits> ";
9605 
9606   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9607     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9608   } else {
9609     OS << "Unpredictable backedge-taken count. ";
9610   }
9611 
9612   OS << "\n"
9613         "Loop ";
9614   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9615   OS << ": ";
9616 
9617   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9618     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9619   } else {
9620     OS << "Unpredictable max backedge-taken count. ";
9621   }
9622 
9623   OS << "\n"
9624         "Loop ";
9625   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9626   OS << ": ";
9627 
9628   SCEVUnionPredicate Pred;
9629   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9630   if (!isa<SCEVCouldNotCompute>(PBT)) {
9631     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9632     OS << " Predicates:\n";
9633     Pred.print(OS, 4);
9634   } else {
9635     OS << "Unpredictable predicated backedge-taken count. ";
9636   }
9637   OS << "\n";
9638 }
9639 
9640 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9641   switch (LD) {
9642   case ScalarEvolution::LoopVariant:
9643     return "Variant";
9644   case ScalarEvolution::LoopInvariant:
9645     return "Invariant";
9646   case ScalarEvolution::LoopComputable:
9647     return "Computable";
9648   }
9649   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9650 }
9651 
9652 void ScalarEvolution::print(raw_ostream &OS) const {
9653   // ScalarEvolution's implementation of the print method is to print
9654   // out SCEV values of all instructions that are interesting. Doing
9655   // this potentially causes it to create new SCEV objects though,
9656   // which technically conflicts with the const qualifier. This isn't
9657   // observable from outside the class though, so casting away the
9658   // const isn't dangerous.
9659   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9660 
9661   OS << "Classifying expressions for: ";
9662   F.printAsOperand(OS, /*PrintType=*/false);
9663   OS << "\n";
9664   for (Instruction &I : instructions(F))
9665     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9666       OS << I << '\n';
9667       OS << "  -->  ";
9668       const SCEV *SV = SE.getSCEV(&I);
9669       SV->print(OS);
9670       if (!isa<SCEVCouldNotCompute>(SV)) {
9671         OS << " U: ";
9672         SE.getUnsignedRange(SV).print(OS);
9673         OS << " S: ";
9674         SE.getSignedRange(SV).print(OS);
9675       }
9676 
9677       const Loop *L = LI.getLoopFor(I.getParent());
9678 
9679       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9680       if (AtUse != SV) {
9681         OS << "  -->  ";
9682         AtUse->print(OS);
9683         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9684           OS << " U: ";
9685           SE.getUnsignedRange(AtUse).print(OS);
9686           OS << " S: ";
9687           SE.getSignedRange(AtUse).print(OS);
9688         }
9689       }
9690 
9691       if (L) {
9692         OS << "\t\t" "Exits: ";
9693         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9694         if (!SE.isLoopInvariant(ExitValue, L)) {
9695           OS << "<<Unknown>>";
9696         } else {
9697           OS << *ExitValue;
9698         }
9699 
9700         bool First = true;
9701         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9702           if (First) {
9703             OS << "\t\t" "LoopDispositions: { ";
9704             First = false;
9705           } else {
9706             OS << ", ";
9707           }
9708 
9709           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9710           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9711         }
9712 
9713         for (auto *InnerL : depth_first(L)) {
9714           if (InnerL == L)
9715             continue;
9716           if (First) {
9717             OS << "\t\t" "LoopDispositions: { ";
9718             First = false;
9719           } else {
9720             OS << ", ";
9721           }
9722 
9723           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9724           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9725         }
9726 
9727         OS << " }";
9728       }
9729 
9730       OS << "\n";
9731     }
9732 
9733   OS << "Determining loop execution counts for: ";
9734   F.printAsOperand(OS, /*PrintType=*/false);
9735   OS << "\n";
9736   for (Loop *I : LI)
9737     PrintLoopInfo(OS, &SE, I);
9738 }
9739 
9740 ScalarEvolution::LoopDisposition
9741 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
9742   auto &Values = LoopDispositions[S];
9743   for (auto &V : Values) {
9744     if (V.getPointer() == L)
9745       return V.getInt();
9746   }
9747   Values.emplace_back(L, LoopVariant);
9748   LoopDisposition D = computeLoopDisposition(S, L);
9749   auto &Values2 = LoopDispositions[S];
9750   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9751     if (V.getPointer() == L) {
9752       V.setInt(D);
9753       break;
9754     }
9755   }
9756   return D;
9757 }
9758 
9759 ScalarEvolution::LoopDisposition
9760 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
9761   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9762   case scConstant:
9763     return LoopInvariant;
9764   case scTruncate:
9765   case scZeroExtend:
9766   case scSignExtend:
9767     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
9768   case scAddRecExpr: {
9769     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9770 
9771     // If L is the addrec's loop, it's computable.
9772     if (AR->getLoop() == L)
9773       return LoopComputable;
9774 
9775     // Add recurrences are never invariant in the function-body (null loop).
9776     if (!L)
9777       return LoopVariant;
9778 
9779     // This recurrence is variant w.r.t. L if L contains AR's loop.
9780     if (L->contains(AR->getLoop()))
9781       return LoopVariant;
9782 
9783     // This recurrence is invariant w.r.t. L if AR's loop contains L.
9784     if (AR->getLoop()->contains(L))
9785       return LoopInvariant;
9786 
9787     // This recurrence is variant w.r.t. L if any of its operands
9788     // are variant.
9789     for (auto *Op : AR->operands())
9790       if (!isLoopInvariant(Op, L))
9791         return LoopVariant;
9792 
9793     // Otherwise it's loop-invariant.
9794     return LoopInvariant;
9795   }
9796   case scAddExpr:
9797   case scMulExpr:
9798   case scUMaxExpr:
9799   case scSMaxExpr: {
9800     bool HasVarying = false;
9801     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9802       LoopDisposition D = getLoopDisposition(Op, L);
9803       if (D == LoopVariant)
9804         return LoopVariant;
9805       if (D == LoopComputable)
9806         HasVarying = true;
9807     }
9808     return HasVarying ? LoopComputable : LoopInvariant;
9809   }
9810   case scUDivExpr: {
9811     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9812     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9813     if (LD == LoopVariant)
9814       return LoopVariant;
9815     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9816     if (RD == LoopVariant)
9817       return LoopVariant;
9818     return (LD == LoopInvariant && RD == LoopInvariant) ?
9819            LoopInvariant : LoopComputable;
9820   }
9821   case scUnknown:
9822     // All non-instruction values are loop invariant.  All instructions are loop
9823     // invariant if they are not contained in the specified loop.
9824     // Instructions are never considered invariant in the function body
9825     // (null loop) because they are defined within the "loop".
9826     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9827       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9828     return LoopInvariant;
9829   case scCouldNotCompute:
9830     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9831   }
9832   llvm_unreachable("Unknown SCEV kind!");
9833 }
9834 
9835 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9836   return getLoopDisposition(S, L) == LoopInvariant;
9837 }
9838 
9839 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9840   return getLoopDisposition(S, L) == LoopComputable;
9841 }
9842 
9843 ScalarEvolution::BlockDisposition
9844 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9845   auto &Values = BlockDispositions[S];
9846   for (auto &V : Values) {
9847     if (V.getPointer() == BB)
9848       return V.getInt();
9849   }
9850   Values.emplace_back(BB, DoesNotDominateBlock);
9851   BlockDisposition D = computeBlockDisposition(S, BB);
9852   auto &Values2 = BlockDispositions[S];
9853   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9854     if (V.getPointer() == BB) {
9855       V.setInt(D);
9856       break;
9857     }
9858   }
9859   return D;
9860 }
9861 
9862 ScalarEvolution::BlockDisposition
9863 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9864   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9865   case scConstant:
9866     return ProperlyDominatesBlock;
9867   case scTruncate:
9868   case scZeroExtend:
9869   case scSignExtend:
9870     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9871   case scAddRecExpr: {
9872     // This uses a "dominates" query instead of "properly dominates" query
9873     // to test for proper dominance too, because the instruction which
9874     // produces the addrec's value is a PHI, and a PHI effectively properly
9875     // dominates its entire containing block.
9876     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9877     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9878       return DoesNotDominateBlock;
9879 
9880     // Fall through into SCEVNAryExpr handling.
9881     LLVM_FALLTHROUGH;
9882   }
9883   case scAddExpr:
9884   case scMulExpr:
9885   case scUMaxExpr:
9886   case scSMaxExpr: {
9887     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9888     bool Proper = true;
9889     for (const SCEV *NAryOp : NAry->operands()) {
9890       BlockDisposition D = getBlockDisposition(NAryOp, BB);
9891       if (D == DoesNotDominateBlock)
9892         return DoesNotDominateBlock;
9893       if (D == DominatesBlock)
9894         Proper = false;
9895     }
9896     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9897   }
9898   case scUDivExpr: {
9899     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9900     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9901     BlockDisposition LD = getBlockDisposition(LHS, BB);
9902     if (LD == DoesNotDominateBlock)
9903       return DoesNotDominateBlock;
9904     BlockDisposition RD = getBlockDisposition(RHS, BB);
9905     if (RD == DoesNotDominateBlock)
9906       return DoesNotDominateBlock;
9907     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9908       ProperlyDominatesBlock : DominatesBlock;
9909   }
9910   case scUnknown:
9911     if (Instruction *I =
9912           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9913       if (I->getParent() == BB)
9914         return DominatesBlock;
9915       if (DT.properlyDominates(I->getParent(), BB))
9916         return ProperlyDominatesBlock;
9917       return DoesNotDominateBlock;
9918     }
9919     return ProperlyDominatesBlock;
9920   case scCouldNotCompute:
9921     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9922   }
9923   llvm_unreachable("Unknown SCEV kind!");
9924 }
9925 
9926 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9927   return getBlockDisposition(S, BB) >= DominatesBlock;
9928 }
9929 
9930 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9931   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9932 }
9933 
9934 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
9935   // Search for a SCEV expression node within an expression tree.
9936   // Implements SCEVTraversal::Visitor.
9937   struct SCEVSearch {
9938     const SCEV *Node;
9939     bool IsFound;
9940 
9941     SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9942 
9943     bool follow(const SCEV *S) {
9944       IsFound |= (S == Node);
9945       return !IsFound;
9946     }
9947     bool isDone() const { return IsFound; }
9948   };
9949 
9950   SCEVSearch Search(Op);
9951   visitAll(S, Search);
9952   return Search.IsFound;
9953 }
9954 
9955 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9956   ValuesAtScopes.erase(S);
9957   LoopDispositions.erase(S);
9958   BlockDispositions.erase(S);
9959   UnsignedRanges.erase(S);
9960   SignedRanges.erase(S);
9961   ExprValueMap.erase(S);
9962   HasRecMap.erase(S);
9963 
9964   auto RemoveSCEVFromBackedgeMap =
9965       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9966         for (auto I = Map.begin(), E = Map.end(); I != E;) {
9967           BackedgeTakenInfo &BEInfo = I->second;
9968           if (BEInfo.hasOperand(S, this)) {
9969             BEInfo.clear();
9970             Map.erase(I++);
9971           } else
9972             ++I;
9973         }
9974       };
9975 
9976   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9977   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
9978 }
9979 
9980 typedef DenseMap<const Loop *, std::string> VerifyMap;
9981 
9982 /// replaceSubString - Replaces all occurrences of From in Str with To.
9983 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9984   size_t Pos = 0;
9985   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9986     Str.replace(Pos, From.size(), To.data(), To.size());
9987     Pos += To.size();
9988   }
9989 }
9990 
9991 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9992 static void
9993 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9994   std::string &S = Map[L];
9995   if (S.empty()) {
9996     raw_string_ostream OS(S);
9997     SE.getBackedgeTakenCount(L)->print(OS);
9998 
9999     // false and 0 are semantically equivalent. This can happen in dead loops.
10000     replaceSubString(OS.str(), "false", "0");
10001     // Remove wrap flags, their use in SCEV is highly fragile.
10002     // FIXME: Remove this when SCEV gets smarter about them.
10003     replaceSubString(OS.str(), "<nw>", "");
10004     replaceSubString(OS.str(), "<nsw>", "");
10005     replaceSubString(OS.str(), "<nuw>", "");
10006   }
10007 
10008   for (auto *R : reverse(*L))
10009     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
10010 }
10011 
10012 void ScalarEvolution::verify() const {
10013   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10014 
10015   // Gather stringified backedge taken counts for all loops using SCEV's caches.
10016   // FIXME: It would be much better to store actual values instead of strings,
10017   //        but SCEV pointers will change if we drop the caches.
10018   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
10019   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10020     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10021 
10022   // Gather stringified backedge taken counts for all loops using a fresh
10023   // ScalarEvolution object.
10024   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10025   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10026     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
10027 
10028   // Now compare whether they're the same with and without caches. This allows
10029   // verifying that no pass changed the cache.
10030   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10031          "New loops suddenly appeared!");
10032 
10033   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10034                            OldE = BackedgeDumpsOld.end(),
10035                            NewI = BackedgeDumpsNew.begin();
10036        OldI != OldE; ++OldI, ++NewI) {
10037     assert(OldI->first == NewI->first && "Loop order changed!");
10038 
10039     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10040     // changes.
10041     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
10042     // means that a pass is buggy or SCEV has to learn a new pattern but is
10043     // usually not harmful.
10044     if (OldI->second != NewI->second &&
10045         OldI->second.find("undef") == std::string::npos &&
10046         NewI->second.find("undef") == std::string::npos &&
10047         OldI->second != "***COULDNOTCOMPUTE***" &&
10048         NewI->second != "***COULDNOTCOMPUTE***") {
10049       dbgs() << "SCEVValidator: SCEV for loop '"
10050              << OldI->first->getHeader()->getName()
10051              << "' changed from '" << OldI->second
10052              << "' to '" << NewI->second << "'!\n";
10053       std::abort();
10054     }
10055   }
10056 
10057   // TODO: Verify more things.
10058 }
10059 
10060 char ScalarEvolutionAnalysis::PassID;
10061 
10062 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10063                                              FunctionAnalysisManager &AM) {
10064   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10065                          AM.getResult<AssumptionAnalysis>(F),
10066                          AM.getResult<DominatorTreeAnalysis>(F),
10067                          AM.getResult<LoopAnalysis>(F));
10068 }
10069 
10070 PreservedAnalyses
10071 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10072   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10073   return PreservedAnalyses::all();
10074 }
10075 
10076 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10077                       "Scalar Evolution Analysis", false, true)
10078 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10079 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10080 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10081 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10082 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10083                     "Scalar Evolution Analysis", false, true)
10084 char ScalarEvolutionWrapperPass::ID = 0;
10085 
10086 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10087   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10088 }
10089 
10090 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10091   SE.reset(new ScalarEvolution(
10092       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10093       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10094       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10095       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10096   return false;
10097 }
10098 
10099 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10100 
10101 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10102   SE->print(OS);
10103 }
10104 
10105 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10106   if (!VerifySCEV)
10107     return;
10108 
10109   SE->verify();
10110 }
10111 
10112 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10113   AU.setPreservesAll();
10114   AU.addRequiredTransitive<AssumptionCacheTracker>();
10115   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10116   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10117   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10118 }
10119 
10120 const SCEVPredicate *
10121 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10122                                    const SCEVConstant *RHS) {
10123   FoldingSetNodeID ID;
10124   // Unique this node based on the arguments
10125   ID.AddInteger(SCEVPredicate::P_Equal);
10126   ID.AddPointer(LHS);
10127   ID.AddPointer(RHS);
10128   void *IP = nullptr;
10129   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10130     return S;
10131   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10132       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10133   UniquePreds.InsertNode(Eq, IP);
10134   return Eq;
10135 }
10136 
10137 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10138     const SCEVAddRecExpr *AR,
10139     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10140   FoldingSetNodeID ID;
10141   // Unique this node based on the arguments
10142   ID.AddInteger(SCEVPredicate::P_Wrap);
10143   ID.AddPointer(AR);
10144   ID.AddInteger(AddedFlags);
10145   void *IP = nullptr;
10146   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10147     return S;
10148   auto *OF = new (SCEVAllocator)
10149       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10150   UniquePreds.InsertNode(OF, IP);
10151   return OF;
10152 }
10153 
10154 namespace {
10155 
10156 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10157 public:
10158   /// Rewrites \p S in the context of a loop L and the SCEV predication
10159   /// infrastructure.
10160   ///
10161   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10162   /// equivalences present in \p Pred.
10163   ///
10164   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10165   /// \p NewPreds such that the result will be an AddRecExpr.
10166   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10167                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10168                              SCEVUnionPredicate *Pred) {
10169     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10170     return Rewriter.visit(S);
10171   }
10172 
10173   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10174                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10175                         SCEVUnionPredicate *Pred)
10176       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10177 
10178   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10179     if (Pred) {
10180       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10181       for (auto *Pred : ExprPreds)
10182         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10183           if (IPred->getLHS() == Expr)
10184             return IPred->getRHS();
10185     }
10186 
10187     return Expr;
10188   }
10189 
10190   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10191     const SCEV *Operand = visit(Expr->getOperand());
10192     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10193     if (AR && AR->getLoop() == L && AR->isAffine()) {
10194       // This couldn't be folded because the operand didn't have the nuw
10195       // flag. Add the nusw flag as an assumption that we could make.
10196       const SCEV *Step = AR->getStepRecurrence(SE);
10197       Type *Ty = Expr->getType();
10198       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10199         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10200                                 SE.getSignExtendExpr(Step, Ty), L,
10201                                 AR->getNoWrapFlags());
10202     }
10203     return SE.getZeroExtendExpr(Operand, Expr->getType());
10204   }
10205 
10206   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10207     const SCEV *Operand = visit(Expr->getOperand());
10208     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10209     if (AR && AR->getLoop() == L && AR->isAffine()) {
10210       // This couldn't be folded because the operand didn't have the nsw
10211       // flag. Add the nssw flag as an assumption that we could make.
10212       const SCEV *Step = AR->getStepRecurrence(SE);
10213       Type *Ty = Expr->getType();
10214       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10215         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10216                                 SE.getSignExtendExpr(Step, Ty), L,
10217                                 AR->getNoWrapFlags());
10218     }
10219     return SE.getSignExtendExpr(Operand, Expr->getType());
10220   }
10221 
10222 private:
10223   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10224                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10225     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10226     if (!NewPreds) {
10227       // Check if we've already made this assumption.
10228       return Pred && Pred->implies(A);
10229     }
10230     NewPreds->insert(A);
10231     return true;
10232   }
10233 
10234   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10235   SCEVUnionPredicate *Pred;
10236   const Loop *L;
10237 };
10238 } // end anonymous namespace
10239 
10240 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10241                                                    SCEVUnionPredicate &Preds) {
10242   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10243 }
10244 
10245 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10246     const SCEV *S, const Loop *L,
10247     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10248 
10249   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10250   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10251   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10252 
10253   if (!AddRec)
10254     return nullptr;
10255 
10256   // Since the transformation was successful, we can now transfer the SCEV
10257   // predicates.
10258   for (auto *P : TransformPreds)
10259     Preds.insert(P);
10260 
10261   return AddRec;
10262 }
10263 
10264 /// SCEV predicates
10265 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10266                              SCEVPredicateKind Kind)
10267     : FastID(ID), Kind(Kind) {}
10268 
10269 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10270                                        const SCEVUnknown *LHS,
10271                                        const SCEVConstant *RHS)
10272     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10273 
10274 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10275   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10276 
10277   if (!Op)
10278     return false;
10279 
10280   return Op->LHS == LHS && Op->RHS == RHS;
10281 }
10282 
10283 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10284 
10285 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10286 
10287 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10288   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10289 }
10290 
10291 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10292                                      const SCEVAddRecExpr *AR,
10293                                      IncrementWrapFlags Flags)
10294     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10295 
10296 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10297 
10298 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10299   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10300 
10301   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10302 }
10303 
10304 bool SCEVWrapPredicate::isAlwaysTrue() const {
10305   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10306   IncrementWrapFlags IFlags = Flags;
10307 
10308   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10309     IFlags = clearFlags(IFlags, IncrementNSSW);
10310 
10311   return IFlags == IncrementAnyWrap;
10312 }
10313 
10314 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10315   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10316   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10317     OS << "<nusw>";
10318   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10319     OS << "<nssw>";
10320   OS << "\n";
10321 }
10322 
10323 SCEVWrapPredicate::IncrementWrapFlags
10324 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10325                                    ScalarEvolution &SE) {
10326   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10327   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10328 
10329   // We can safely transfer the NSW flag as NSSW.
10330   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10331     ImpliedFlags = IncrementNSSW;
10332 
10333   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10334     // If the increment is positive, the SCEV NUW flag will also imply the
10335     // WrapPredicate NUSW flag.
10336     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10337       if (Step->getValue()->getValue().isNonNegative())
10338         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10339   }
10340 
10341   return ImpliedFlags;
10342 }
10343 
10344 /// Union predicates don't get cached so create a dummy set ID for it.
10345 SCEVUnionPredicate::SCEVUnionPredicate()
10346     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10347 
10348 bool SCEVUnionPredicate::isAlwaysTrue() const {
10349   return all_of(Preds,
10350                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10351 }
10352 
10353 ArrayRef<const SCEVPredicate *>
10354 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10355   auto I = SCEVToPreds.find(Expr);
10356   if (I == SCEVToPreds.end())
10357     return ArrayRef<const SCEVPredicate *>();
10358   return I->second;
10359 }
10360 
10361 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10362   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10363     return all_of(Set->Preds,
10364                   [this](const SCEVPredicate *I) { return this->implies(I); });
10365 
10366   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10367   if (ScevPredsIt == SCEVToPreds.end())
10368     return false;
10369   auto &SCEVPreds = ScevPredsIt->second;
10370 
10371   return any_of(SCEVPreds,
10372                 [N](const SCEVPredicate *I) { return I->implies(N); });
10373 }
10374 
10375 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10376 
10377 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10378   for (auto Pred : Preds)
10379     Pred->print(OS, Depth);
10380 }
10381 
10382 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10383   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10384     for (auto Pred : Set->Preds)
10385       add(Pred);
10386     return;
10387   }
10388 
10389   if (implies(N))
10390     return;
10391 
10392   const SCEV *Key = N->getExpr();
10393   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10394                 " associated expression!");
10395 
10396   SCEVToPreds[Key].push_back(N);
10397   Preds.push_back(N);
10398 }
10399 
10400 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10401                                                      Loop &L)
10402     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10403 
10404 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10405   const SCEV *Expr = SE.getSCEV(V);
10406   RewriteEntry &Entry = RewriteMap[Expr];
10407 
10408   // If we already have an entry and the version matches, return it.
10409   if (Entry.second && Generation == Entry.first)
10410     return Entry.second;
10411 
10412   // We found an entry but it's stale. Rewrite the stale entry
10413   // acording to the current predicate.
10414   if (Entry.second)
10415     Expr = Entry.second;
10416 
10417   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10418   Entry = {Generation, NewSCEV};
10419 
10420   return NewSCEV;
10421 }
10422 
10423 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10424   if (!BackedgeCount) {
10425     SCEVUnionPredicate BackedgePred;
10426     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10427     addPredicate(BackedgePred);
10428   }
10429   return BackedgeCount;
10430 }
10431 
10432 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10433   if (Preds.implies(&Pred))
10434     return;
10435   Preds.add(&Pred);
10436   updateGeneration();
10437 }
10438 
10439 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10440   return Preds;
10441 }
10442 
10443 void PredicatedScalarEvolution::updateGeneration() {
10444   // If the generation number wrapped recompute everything.
10445   if (++Generation == 0) {
10446     for (auto &II : RewriteMap) {
10447       const SCEV *Rewritten = II.second.second;
10448       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10449     }
10450   }
10451 }
10452 
10453 void PredicatedScalarEvolution::setNoOverflow(
10454     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10455   const SCEV *Expr = getSCEV(V);
10456   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10457 
10458   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10459 
10460   // Clear the statically implied flags.
10461   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10462   addPredicate(*SE.getWrapPredicate(AR, Flags));
10463 
10464   auto II = FlagsMap.insert({V, Flags});
10465   if (!II.second)
10466     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10467 }
10468 
10469 bool PredicatedScalarEvolution::hasNoOverflow(
10470     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10471   const SCEV *Expr = getSCEV(V);
10472   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10473 
10474   Flags = SCEVWrapPredicate::clearFlags(
10475       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10476 
10477   auto II = FlagsMap.find(V);
10478 
10479   if (II != FlagsMap.end())
10480     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10481 
10482   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10483 }
10484 
10485 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10486   const SCEV *Expr = this->getSCEV(V);
10487   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10488   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10489 
10490   if (!New)
10491     return nullptr;
10492 
10493   for (auto *P : NewPreds)
10494     Preds.add(P);
10495 
10496   updateGeneration();
10497   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10498   return New;
10499 }
10500 
10501 PredicatedScalarEvolution::PredicatedScalarEvolution(
10502     const PredicatedScalarEvolution &Init)
10503     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10504       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10505   for (const auto &I : Init.FlagsMap)
10506     FlagsMap.insert(I);
10507 }
10508 
10509 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10510   // For each block.
10511   for (auto *BB : L.getBlocks())
10512     for (auto &I : *BB) {
10513       if (!SE.isSCEVable(I.getType()))
10514         continue;
10515 
10516       auto *Expr = SE.getSCEV(&I);
10517       auto II = RewriteMap.find(Expr);
10518 
10519       if (II == RewriteMap.end())
10520         continue;
10521 
10522       // Don't print things that are not interesting.
10523       if (II->second.second == Expr)
10524         continue;
10525 
10526       OS.indent(Depth) << "[PSE]" << I << ":\n";
10527       OS.indent(Depth + 2) << *Expr << "\n";
10528       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10529     }
10530 }
10531